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