Salome HOME
Run salome from KERNEL/bin/salome/ directory. Hibernate logging configuration is...
[tools/siman.git] / Workspace / Siman / src / org / splat / launcher / ToolbarApplet.java
1 package org.splat.launcher;
2
3 import java.awt.Color;
4 import java.awt.ComponentOrientation;
5 import java.awt.GridLayout;
6 import java.awt.event.ActionEvent;
7 import java.awt.event.ActionListener;
8 import java.io.BufferedReader;
9 import java.io.File;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.ObjectInputStream;
13 import java.io.UnsupportedEncodingException;
14 import java.net.MalformedURLException;
15 import java.net.URL;
16 import java.net.URLConnection;
17 import java.net.URLEncoder;
18
19 /**
20  * Applet providing a set of buttons. Each button is defined by three parameters:<BR>
21  * <ul>
22  * <li><i>icon&lt;i&gt;</i></li>
23  * <li><i>tool&lt;i&gt;</i></li>
24  * <li><i>file&lt;i&gt;</i></li> - may be null
25  * </ul>
26  * where i is an index beginning from zero.
27  */
28 public class ToolbarApplet extends java.applet.Applet implements ActionListener {
29
30         /**
31          * Serialization version id.
32          */
33         private static final long serialVersionUID = 3243053622061086715L;
34
35         /**
36          * The response key string: '<i>"canCheckout"</i> :'.
37          */
38         public static final String CHECKOUT_RES = "\"canCheckout\" :";
39
40         // ==============================================================================================================================
41         // Overridden functions
42         // ==============================================================================================================================
43
44         /**
45          * {@inheritDoc}
46          * 
47          * @see java.applet.Applet#init()
48          */
49         @Override
50         public void init() {
51                 URL appurl = getCodeBase();
52                 int hgap = 6; // Gap between icons
53                 int ntools;
54
55                 int width = getSize().width;
56                 int height = getSize().height;
57                 for (ntools = 0; ntools < (width + hgap) / (height + hgap); ntools++) {
58                         String icon = this.getParameter("icon" + ntools);
59                         String tool = this.getParameter("tool" + ntools);
60                         String file = this.getParameter("file" + ntools); // May be null
61                         if (icon != null && tool != null) {
62                                 ToolButton button = new ToolButton(height, getImage(appurl,
63                                                 "../skin/" + icon), tool, file);
64                                 add(button); // For displaying the button
65                                 button.addActionListener(this);
66                         }
67                 }
68                 setLayout(new GridLayout(1, ntools, hgap, 0)); // 1 row, {ntools} buttons
69                 setBackground(Color.decode("#D2E7FF"));
70                 applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
71         }
72
73         /**
74          * {@inheritDoc}
75          * 
76          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
77          */
78         public void actionPerformed(final ActionEvent event) {
79                 if (event.getSource() instanceof ToolButton) {
80                         ToolButton clicked = (ToolButton) event.getSource();
81                         String module = clicked.getTool();
82                         String target = clicked.getTarget();
83                         launch(module, target);
84                 }
85         }
86
87         // ==============================================================================================================================
88         // Public member functions
89         // ==============================================================================================================================
90
91         /**
92          * Launch an appropriate application for the given file.
93          * 
94          * @param name
95          *            module name
96          * @param filename
97          *            file name
98          */
99         public void launch(final String name, final String filename) {
100                 String module = name;
101                 try {
102
103                         // Opening a Web page in a new tab
104                         if (module.startsWith("http")) {
105                                 getAppletContext().showDocument(new URL(module), "_blank");
106                         } else
107
108                         // Opening a Web module in a new tab
109                         if (module.startsWith("../") || module.startsWith("/")) {
110                                 module = getCodeBase().toString() + module;
111                                 if (filename != null) {
112                                         module = module + "?open=" + filename;
113                                 }
114                                 getAppletContext().showDocument(new URL(module), "_blank");
115                         } else
116
117                         // Opening an application on the local machine
118
119                         if ("runSalome".equals(module)) {
120                                 salomeCheckout(filename);
121                         } else
122
123                         if (module.endsWith(".exe") || module.endsWith(".EXE")) {
124                                 String applikey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Applications\\"
125                                                 + module;
126                                 String valkey = ""; // Default application and file keys
127
128                                 module = WindowsRegistry.readValue(applikey
129                                                 + "\\shell\\open\\command", valkey);
130                                 if (module == null) {
131                                         module = WindowsRegistry.readValue(applikey
132                                                         + "\\shell\\edit\\command", valkey);
133                                 }
134                                 // if (module == null) module = "\"C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE\"";
135                                 if (module == null) {
136                                         module = getCodeBase().toString()
137                                                         + "error.jsp?message=launch&value=" + name;
138                                         getAppletContext().showDocument(new URL(module));
139                                 } else {
140                                         String[] parse = module.split("/");
141                                         String command = parse[0]; // Removing eventual options
142                                         if (filename != null) {
143                                                 String path = "";
144                                                 // Opening the application with a server side existing file
145                                                 if (filename.startsWith("http")) {
146                                                         path = " \"" + filename + "\"";
147                                                 }
148                                                 // Opening the application with a file previously created by the server
149                                                 else if (filename.startsWith("/jsp")) { // Document created through a JSP
150                                                         URL my = getDocumentBase();
151                                                         String http = "http://" + my.getHost() + ":"
152                                                                         + my.getPort() + "/";
153                                                         String[] jsppath = my.getPath().split("/"); // Parses "/webapp/..."
154                                                         String location = http + jsppath[1] + filename;
155
156                                                         URLConnection connection = new URL(location)
157                                                                         .openConnection();
158                                                         ObjectInputStream fromservlet = new ObjectInputStream(
159                                                                         connection.getInputStream());
160                                                         URL docurl = (URL) fromservlet.readObject();
161
162                                                         fromservlet.close();
163                                                         if (docurl != null) {
164                                                                 path = " " + docurl.toString();
165                                                         }
166                                                 }
167                                                 command = command + path;
168                                         }
169                                         Runtime.getRuntime().exec(command);
170                                 }
171                         }
172                 } catch (Exception error) {
173                         error.printStackTrace(); // RKV: NOPMD: TODO: try to use logger
174                 }
175         }
176
177         /**
178          * Checkout a scenario and start Salome with it.
179          * 
180          * @param params
181          *            Salome parameters
182          * @throws IOException
183          *             if URL connection opening/reading is failed
184          * @throws ConfigurationException
185          *             if SALOME_ROOT_DIR environment variable is not defined or Salome launcher script is not found
186          */
187         private void salomeCheckout(final String params)
188                         throws ConfigurationException, IOException {
189                 // Run SALOME
190                 // To get the SALOME_HOME environment variable
191                 String SALOME_HOME = System.getenv("SALOME_ROOT_DIR");
192                 // If SALOME_ROOT_DIR does not exist the SALOME_HOME equals to null.
193                 if (SALOME_HOME == null) {
194                         // TODO: Use logger to be more user friendly
195                         showError("SALOME_ROOT_DIR environment variable is not defined.");
196                         throw new ConfigurationException(
197                                         "SALOME_ROOT_DIR nevironment variable is not defined.");
198                 } else if (!SALOME_HOME.endsWith(File.separator)) {
199                         SALOME_HOME += File.separator;
200                 }
201                 String pathToScript = SALOME_HOME + "KERNEL" + File.separator + "bin"
202                                 + File.separator + "salome" + File.separator + "runSalome";
203
204                 // Look for the launching script in the file system
205                 File script = new File(pathToScript);
206                 if (!script.exists()) {
207                         script = new File(pathToScript + ".bat");
208                         if (!script.exists()) {
209                                 script = new File(pathToScript + ".cmd");
210                         }
211                 }
212
213                 if (script.exists()) {
214
215                         // Call to the Siman server to checkout the scenario
216                         URL checkoutUrl = new URL(getCodeBase().toString()
217                                         + "checkout.action?"
218                                         + params.replaceAll("siman-", "").replaceAll("--", "-")
219                                                         .replaceAll("-", "&").replaceAll("\\s", ""));
220
221                         BufferedReader buffer = new BufferedReader(new InputStreamReader(
222                                         checkoutUrl.openStream()));
223
224                         // Read the response of the Siman server
225                         boolean isOk = false;
226                         String response = buffer.readLine();
227                         while ((response != null)) {
228                                 if (response.contains(CHECKOUT_RES)) {
229                                         isOk = response.contains(CHECKOUT_RES + " \"true\"");
230                                         break;
231                                 }
232                                 response = buffer.readLine();
233                         }
234                         buffer.close();
235
236                         if (isOk) {
237                                 // Execute the runSalome script.
238                                 // filename here indeed a string containing parameters for runSalome.
239                                 Runtime.getRuntime().exec(
240                                                 new String[] { script.getAbsolutePath(), params });
241                                 // Refresh the current scenario view
242                                 getAppletContext().showDocument(
243                                                 new URL(this.getParameter("refresh")));
244                         } else {
245                                 // Checkout of the scenario is failed at the beginning.
246                                 if (response != null) {
247                                         response = response.substring(
248                                                         response.indexOf(CHECKOUT_RES)
249                                                                         + CHECKOUT_RES.length()).replace('}', ' ')
250                                                         .replace('"', ' ');
251                                 }
252                                 showError(response);
253                         }
254                 } else {
255                         showError("SALOME module is not found: " + script.getAbsolutePath());
256                         throw new ConfigurationException("SALOME module is not found: "
257                                         + script.getAbsolutePath());
258                 }
259         }
260
261         /**
262          * Show error message in the new window.
263          * 
264          * @param message
265          *            the error message
266          * @throws MalformedURLException
267          *             if built URL is incorrect
268          * @throws UnsupportedEncodingException
269          *             if UTF-8 encoding is not supported
270          */
271         private void showError(final String message) throws MalformedURLException,
272                         UnsupportedEncodingException {
273                 getAppletContext().showDocument(
274                                 new URL(getCodeBase().toString() + "../error.jsp?error="
275                                                 + URLEncoder.encode(message, "UTF-8")), "_blank");
276         }
277 }