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