Statistics
| Revision:

root / org.gvsig.toolbox / trunk / org.gvsig.toolbox / org.gvsig.toolbox.gui / src / main / java / es / unex / sextante / gui / saga / SagaUtils.java @ 119

History | View | Annotate | Download (9.86 KB)

1
package es.unex.sextante.gui.saga;
2

    
3
import java.io.BufferedReader;
4
import java.io.BufferedWriter;
5
import java.io.File;
6
import java.io.FileReader;
7
import java.io.FileWriter;
8
import java.io.IOException;
9
import java.io.InputStream;
10
import java.io.InputStreamReader;
11
import java.util.ArrayList;
12
import java.util.List;
13

    
14
import es.unex.sextante.core.Sextante;
15
import es.unex.sextante.gui.core.SextanteGUI;
16
import es.unex.sextante.gui.settings.SextanteSagaSettings;
17

    
18

    
19
public class SagaUtils {
20

    
21

    
22
   public static final String   SAGACMD_USE_START_PARAMETER = "SAGACMD_USE_START_PARAMETER";
23

    
24
   private static SagaAlgorithm m_Alg;
25
   private static StringBuffer  m_sMessages;
26

    
27

    
28
   public static int installSaga() throws SagaExecutionException {
29

    
30
      deleteDescriptionFiles();
31
      createLibrariesListFile();
32
      createLibrariesDescriptionFiles();
33
      return createAlgorithmsDescriptionFiles();
34

    
35
   }
36

    
37

    
38
   public static void deleteDescriptionFiles() {
39

    
40
      final File file = new File(getSagaDescriptionFolder());
41
      final String[] files = file.list();
42

    
43
      if (files != null) {
44
         for (final String element : files) {
45
            new File(file.getAbsoluteFile() + File.separator + element).delete();
46
         }
47
      }
48

    
49
   }
50

    
51

    
52
   public static void createLibrariesListFile() throws SagaExecutionException {
53

    
54

    
55
      final String[] sCommands = new String[] { " > " + getSagaDescriptionFolder() + File.separator + "sagalibs.txt" };
56
      createSagaBatchJobFileFromSagaCommands(sCommands);
57
      executeSaga(null);
58

    
59
   }
60

    
61

    
62
   private static void createLibrariesDescriptionFiles() throws SagaExecutionException {
63

    
64

    
65
      final ArrayList<String> commands = new ArrayList<String>();
66

    
67
      final String sFile = getSagaDescriptionFolder() + File.separator + "sagalibs.txt";
68
      BufferedReader input = null;
69
      try {
70
         input = new BufferedReader(new FileReader(sFile));
71
         String sLine = null;
72
         while ((sLine = input.readLine()) != null) {
73
            if (sLine.startsWith("-")) {
74
               final String sLibraryName = sLine.substring(1, sLine.lastIndexOf(".")).trim();
75
               commands.add(sLibraryName + " > " + getSagaDescriptionFolder() + File.separator + "lib_" + sLibraryName + ".txt");
76
            }
77
         }
78
         input.close();
79
         createSagaBatchJobFileFromSagaCommands(commands.toArray(new String[0]));
80
         executeSaga(null);
81
      }
82
      catch (final Exception e) {
83
         throw new SagaExecutionException();
84
      }
85

    
86
   }
87

    
88

    
89
   private static int createAlgorithmsDescriptionFiles() throws SagaExecutionException {
90

    
91
      int iAlg = 0;
92
      final ArrayList<String> commands = new ArrayList<String>();
93

    
94
      File file = new File(getSagaDescriptionFolder());
95
      final String[] files = file.list();
96

    
97
      if (files != null) {
98
         for (final String sFilename : files) {
99
            if (sFilename.startsWith("lib")) {
100
               int iAlgsInLibrary = 0;
101
               final String sLibraryName = sFilename.substring(4, sFilename.length() - 4);
102
               file = new File(getSagaDescriptionFolder() + File.separator + sFilename);
103
               BufferedReader input = null;
104
               try {
105
                  input = new BufferedReader(new FileReader(file.getAbsolutePath()));
106
                  String sLine = null;
107
                  while ((sLine = input.readLine()) != null) {
108
                     final String[] sTokens = sLine.split("\t");
109
                     if (sTokens.length > 0) {
110
                        if (isNumber(sTokens[0].trim())) {
111
                           commands.add(sLibraryName + " " + Integer.toString(iAlgsInLibrary) + " >" + getSagaDescriptionFolder()
112
                                        + File.separator + "alg_" + sLibraryName + "_" + Integer.toString(iAlg) + ".txt 2>&1");
113
                           iAlgsInLibrary++;
114
                           iAlg++;
115

    
116
                        }
117
                     }
118
                  }
119
                  input.close();
120
               }
121
               catch (final Exception e) {
122
                  throw new SagaExecutionException();
123
               }
124
            }
125
         }
126
      }
127

    
128
      if (commands.size() != 0) {
129
         createSagaBatchJobFileFromSagaCommands(commands.toArray(new String[0]));
130
         executeSaga(null);
131
      }
132

    
133
      return iAlg;
134

    
135
   }
136

    
137

    
138
   private static boolean isNumber(final String s) {
139

    
140
      try {
141
         Integer.parseInt(s);
142
         return true;
143
      }
144
      catch (final NumberFormatException e) {
145
         return false;
146
      }
147

    
148
   }
149

    
150

    
151
   public static String getSagaDescriptionFolder() {
152

    
153

    
154
      final String sPath = SextanteGUI.getSextanteInstallPath() + File.separator + "saga" + File.separator + "description";
155

    
156
      final File file = new File(sPath);
157
      if (!file.exists()) {
158
         file.mkdir();
159
      }
160

    
161
      return sPath;
162

    
163
   }
164

    
165

    
166
   public static String getBatchJobFilename() {
167

    
168
      String sFile;
169

    
170
      if (Sextante.isUnix() || Sextante.isMacOSX()) {
171
         sFile = "saga_batch_job.sh";
172
      }
173
      else {//Windows
174
         sFile = "saga_batch_job.bat";
175
      }
176

    
177
      sFile = SextanteGUI.getUserFolder() + File.separator + sFile;
178

    
179
      return sFile;
180

    
181
   }
182

    
183

    
184
   public static void createSagaBatchJobFileFromSagaCommands(final String[] sCommands) {
185

    
186
      final String sFilename = getBatchJobFilename();
187
      final String sSagaFolder = SextanteGUI.getSettingParameterValue(SextanteSagaSettings.SAGA_FOLDER);
188
      try {
189
         final BufferedWriter output = new BufferedWriter(new FileWriter(sFilename));
190
         if (Sextante.isWindows()) {
191
            output.write("set SAGA=" + sSagaFolder + "\n");
192
            output.write("set SAGA_MLB=" + sSagaFolder + File.separator + "modules" + "\n");
193
            output.write("PATH=PATH;%SAGA%;%SAGA_MLB%\n");
194
         }
195
         else {
196
            //output.write("!#/bin/sh\n");
197
            output.write("export SAGA_MLB=" + sSagaFolder + File.separator + "modules" + "\n");
198
            output.write("PATH=$PATH:" + sSagaFolder + File.separator + "modules" + "\n");
199
            output.write("export PATH");
200
         }
201

    
202
         final String value = SextanteGUI.getSettingParameterValue(SAGACMD_USE_START_PARAMETER);
203
         boolean b = false;
204
         if (value != null) {
205
            b = Boolean.parseBoolean(value);
206
         }
207
         for (int i = 0; i < sCommands.length; i++) {
208
            if (b) {
209
               output.write("saga_cmd " + sCommands[i] + "> dummy.txt \n");
210
            }
211
            else {
212
               output.write("saga_cmd " + sCommands[i] + "\n");
213
            }
214
         }
215
         output.write("exit");
216
         output.close();
217
      }
218
      catch (final IOException e) {
219
         Sextante.addErrorToLog(e);
220
      }
221

    
222

    
223
   }
224

    
225

    
226
   public static int executeSaga(final SagaAlgorithm alg) throws SagaExecutionException {
227

    
228

    
229
      m_Alg = alg;
230
      final List<String> list = new ArrayList<String>();
231
      ProcessBuilder pb;
232
      pb = new ProcessBuilder(list);
233
      if (Sextante.isUnix() || Sextante.isMacOSX()) {
234
         setExecutable(getBatchJobFilename());
235
         list.add(getBatchJobFilename());
236
      }
237
      else { //windows
238
         list.add("cmd.exe");
239
         list.add("/C");
240
         //list.add("start");
241
         final String value = SextanteGUI.getSettingParameterValue(SAGACMD_USE_START_PARAMETER);
242
         if (value != null) {
243
            final boolean b = Boolean.parseBoolean(value);
244
            if (b) {
245
               //list.add("start");
246
            }
247
         }
248
         list.add(getBatchJobFilename());
249
      }
250

    
251
      m_sMessages = new StringBuffer();
252

    
253
      Process process;
254
      try {
255
         process = pb.start();
256
         final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream());
257
         final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream());
258
         errorGobbler.start();
259
         outputGobbler.start();
260
         final int iReturn = process.waitFor();
261
         SagaAlgorithmProvider.addMessage(m_sMessages.toString(), "SAGA execution");
262
         return iReturn;
263
      }
264
      catch (final Exception e) {
265
         throw new SagaExecutionException();
266
      }
267

    
268

    
269
   }
270

    
271

    
272
   public static void setExecutable(final String pathname) throws SagaExecutionException {
273

    
274
      final String version = System.getProperty("java.version").substring(0, 3);
275
      final Float f = Float.valueOf(version);
276
      if (f.floatValue() < (float) 1.6) {
277
         if (Sextante.isUnix() || Sextante.isMacOSX()) {
278
            try {
279
               Runtime.getRuntime().exec("chmod +x " + pathname);
280
            }
281
            catch (final IOException e) {
282
               throw new SagaExecutionException();
283
            }
284
         }
285
      }
286
      else {
287
         if (Sextante.isUnix() || Sextante.isMacOSX()) {
288
            new File(pathname).setExecutable(true);
289
         }
290
      }
291
   }
292

    
293

    
294
   public static void processLine(String line) {
295

    
296
      if (m_Alg == null) {
297
         return;
298
      }
299

    
300
      line = line.replace("%", "").trim();
301
      try {
302
         final int i = Integer.parseInt(line);
303
         m_Alg.updateProgress(i, 100);
304
      }
305
      catch (final Exception e) {
306
         //System.out.println(line);
307
         m_sMessages.append(line + "\n");
308

    
309
      }
310

    
311
   }
312

    
313
}
314

    
315

    
316
class StreamGobbler
317
         extends
318
            Thread {
319

    
320
   InputStream is;
321
   String      type;
322

    
323

    
324
   StreamGobbler(final InputStream is) {
325

    
326
      this.is = is;
327

    
328
   }
329

    
330

    
331
   @Override
332
   public void run() {
333
      try {
334
         final InputStreamReader isr = new InputStreamReader(is);
335
         final BufferedReader br = new BufferedReader(isr);
336
         String line = null;
337
         while ((line = br.readLine()) != null) {
338
            SagaUtils.processLine(line);
339
         }
340
      }
341
      catch (final IOException ioe) {
342

    
343
      }
344
   }
345
}