Revision 30

View differences:

org.gvsig.toolbox/trunk/org.gvsig.toolbox/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3
	<modelVersion>4.0.0</modelVersion>
4
	
5
	<groupId>org.gvsig</groupId>
6
	<artifactId>org.gvsig.toolbox</artifactId>
7
	<packaging>pom</packaging>
8
	<name>Algorithms</name>
9
	<version>1.0.1-SNAPSHOT</version>
10
	
11
	<parent>
12
		<groupId>org.gvsig</groupId>
13
		<artifactId>org.gvsig.desktop</artifactId>
14
		<version>2.0.22</version>
15
	</parent>
16
	
17
	<scm>
18
        <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-toolbox/trunk/org.gvsig.toolbox</connection>
19
        <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-toolbox/trunk/org.gvsig.toolbox</developerConnection>
20
        <url>https://devel.gvsig.org/redmine/projects/gvsig-toolbox/repository/show/trunk/org.gvsig.toolbox</url>
21
    </scm>
22
	
23
	<repositories>
24
      <repository>
25
        <id>gvsig-public-http-repository</id>
26
        <name>gvSIG maven public HTTP repository</name>
27
        <url>http://devel.gvsig.org/m2repo/j2se</url>
28
        <releases>
29
          <enabled>true</enabled>
30
          <updatePolicy>daily</updatePolicy>
31
          <checksumPolicy>warn</checksumPolicy>
32
        </releases>
33
        <snapshots>
34
          <enabled>true</enabled>
35
          <updatePolicy>daily</updatePolicy>
36
          <checksumPolicy>warn</checksumPolicy>
37
        </snapshots>
38
      </repository>
39
    </repositories> 
40
    
41
	<properties>
42
    	<maven.compiler.source>1.6</maven.compiler.source>
43
    	<maven.compiler.target>1.6</maven.compiler.target>
44
	</properties>
45
	
46
	 <build>
47
	
48
	    <pluginManagement>
49
	       <plugins>
50
	          <plugin>
51
                <groupId>org.codehaus.mojo</groupId>
52
                <artifactId>animal-sniffer-maven-plugin</artifactId>
53
                <version>1.7</version>
54
              </plugin>
55
	       </plugins>
56
	    </pluginManagement>
57
	    
58
	   <sourceDirectory>src</sourceDirectory>
59
	    
60
	    <resources>
61
			<resource>
62
				<directory>resources</directory>
63
				<includes>
64
					<include>**/*</include>
65
				</includes>
66
			</resource>
67
		</resources>
68
		
69
	    <plugins>
70
        	<plugin>
71
            	<groupId>org.apache.maven.plugins</groupId>
72
            	<artifactId>maven-compiler-plugin</artifactId>
73
            	<version>2.0.2</version>
74
            	<configuration>
75
                	<source>1.6</source>
76
                	<target>1.6</target>
77
                	<encoding>ISO-8859-1</encoding>
78
            	</configuration>
79
        	</plugin>
80
        	
81
        	<plugin>
82
              <groupId>org.codehaus.mojo</groupId>
83
              <artifactId>animal-sniffer-maven-plugin</artifactId>
84
              <executions>
85
                <execution>
86
                    <id>check-java-api</id>
87
                    <phase>test</phase>
88
                    <goals>
89
                        <goal>check</goal>
90
                    </goals>
91
                    <configuration>
92
                        <signature>
93
                            <groupId>org.codehaus.mojo.signature
94
                            </groupId>
95
                            <artifactId>java16</artifactId>
96
                            <version>1.0</version>
97
                        </signature>
98
                    </configuration>
99
                </execution>
100
              </executions>
101
             </plugin>
102
             
103
             <plugin>
104
                <groupId>org.apache.maven.plugins</groupId>
105
                <artifactId>maven-release-plugin</artifactId>
106
                <configuration>
107
                    <tagBase>https://devel.gvsig.org/svn/gvsig-toolbox/tags/</tagBase>
108
                    <goals>deploy</goals>
109
                </configuration>
110
            </plugin>
111
            
112
    	  </plugins>
113
    </build>
114
	
115
	<dependencyManagement>
116
      <dependencies>
117
		<dependency>
118
			<groupId>gishur</groupId>
119
			<artifactId>gishur_x</artifactId>
120
			<version>unknown</version>
121
		</dependency>
122
		<dependency>
123
			<groupId>gishur</groupId>
124
			<artifactId>gishur_core</artifactId>
125
			<version>unknown</version>
126
		</dependency>
127
		<dependency>
128
			<groupId>com.vividsolutions</groupId>
129
			<artifactId>jts</artifactId>
130
			<version>1.13</version>
131
		</dependency>
132
		<dependency>
133
			<groupId>org.gvsig</groupId>
134
			<artifactId>org.gvsig.toolbox.core</artifactId>
135
			<version>1.0.1-SNAPSHOT</version>
136
		</dependency>
137
		<dependency>
138
			<groupId>org.gvsig</groupId>
139
			<artifactId>org.gvsig.toolbox.gui</artifactId>
140
			<version>1.0.1-SNAPSHOT</version>
141
		</dependency>
142
		<dependency>
143
			<groupId>org.gvsig</groupId>
144
			<artifactId>org.gvsig.toolbox.math</artifactId>
145
			<version>1.0.1-SNAPSHOT</version>
146
		</dependency>
147
		<dependency>
148
			<groupId>gnu.trove</groupId>
149
			<artifactId>trove</artifactId>
150
			<version>0.1.8</version>
151
		</dependency>
152
		<dependency>
153
			  <groupId>org.gvsig.legacy</groupId>
154
			  <artifactId>jama</artifactId>
155
			  <version>1.0.2</version>
156
		</dependency>
157
        <dependency>
158
			<groupId>org.nfunk</groupId>
159
			<artifactId>jep</artifactId>
160
			<version>2.4.0</version>
161
		</dependency>
162
		<dependency>
163
			<groupId>commons-codec</groupId>
164
			<artifactId>commons-codec</artifactId>
165
			<version>1.8</version>
166
		</dependency>
167
		<dependency>
168
            <groupId>es.unex</groupId>
169
            <artifactId>sextante_wps</artifactId>
170
            <version>0.6.0</version>
171
        </dependency>
172
        <dependency>
173
			<groupId>es.unex</groupId>
174
			<artifactId>libDocEngines</artifactId>
175
			<version>0.6.0</version>
176
		</dependency>
177
		<dependency>
178
			<groupId>org.beanshell</groupId>
179
			<artifactId>bsh</artifactId>
180
			<version>2.0b4</version>
181
		</dependency>
182
        <dependency>
183
            <groupId>org.japura</groupId>
184
            <artifactId>org.japura</artifactId>
185
            <version>1.14.0</version>
186
        </dependency>
187
		<dependency>
188
			<groupId>commons-codec</groupId>
189
			<artifactId>commons-codec</artifactId>
190
			<version>1.8</version>
191
		</dependency>
192
	  </dependencies>
193
	</dependencyManagement>
194
	
195
	 <modules>
196
		<module>org.gvsig.toolbox.math</module>
197
		<module>org.gvsig.toolbox.gui</module>
198
		<module>org.gvsig.toolbox.core</module>
199
		<module>org.gvsig.toolbox.algorithm</module>
200
	</modules>
201
</project>
0 202

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/MANIFEST.MF
1
Manifest-Version: 1.0
2
Ant-Version: Apache Ant 1.7.1
3
Created-By: 20.1-b02 (Sun Microsystems Inc.)
4
Implementation-Version: 0.7
5
Built-Date: 2013-03-04 16:06:37
6

  
0 7

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/jsh/shell/Utils.java
1
/*
2
 * 20:25:20 20/05/99
3
 *
4
 * The Java Shell: Utilities.
5
 * (C)1999 Romain Guy, Osvaldo Pinali Doederlein.
6
 *
7
 * LICENSE
8
 * =======
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 *
23
 * CHANGES
24
 * =======
25
 * 1.0.8 - Filled the listRoots method                   (Romain & Osvaldo)
26
 * 1.0.7 - Several bug fixes in constructPath            (Romain)
27
 * 1.0.6 - Split JDK1.1/1.2                              (Osvaldo)
28
 * 1.0.5 - Important bug fix in constructPath(String)    (Romain)
29
 * 1.0.4 - Added getSize(Enumeration)                    (Osvaldo)
30
 * 1.0.3 - Changed sortStrings bubble-sort algorithm to  (Romain)
31
 *         quick-sort (James Gosling)
32
 * 1.0.2 - Fixed two little bug in constructPath(String) (Romain)
33
 * 1.0.1 - Added listFiles(String[], boolean)            (Romain)
34
 *       - Removed unecessary createWhiteSpace(int)      (Romain)
35
 *       - Modified getWildCardMatches(String, boolean)  (Romain)
36
 *       - Slighty improved javadoc comments             (Romain)
37
 * 1.0.0 - Initial release.                              (Romain & Osvaldo)
38
 *
39
 * LINKS
40
 * =====
41
 * Contact: mailto@osvaldo.visionnaire.com.br
42
 * Site #1: http://www.geocities.com/ResearchTriangle/Node/2005/
43
 * Site #2: http://student.vub.ac.be/~opinalid/
44
 */
45

  
46
package jsh.shell;
47

  
48
import java.io.File;
49
import java.util.Enumeration;
50
import java.util.Vector;
51

  
52
import es.unex.sextante.gui.core.SextanteGUI;
53

  
54
/**
55
 * The Java Shell: Utility pack.
56
 *
57
 * @author Romain Guy.
58
 * @author Osvaldo Pinali Doederlein.
59
 */
60

  
61
public class Utils {
62

  
63
   /**
64
    * Removes some elements from a String array.
65
    *
66
    * @param arr
67
    *                The array.
68
    * @param first
69
    *                First element to keep (new 0-index).
70
    * @param last
71
    *                Last element to keep.
72
    * @return Copy of arr[first..]
73
    */
74
   public static String[] subarray(final String[] arr,
75
                                   int first,
76
                                   final int last) {
77
      final String[] newArr = new String[last - first + 1];
78

  
79
      for (int i = 0; i < newArr.length; ++i, ++first) {
80
         newArr[i] = arr[first];
81
      }
82

  
83
      return newArr;
84
   }
85

  
86

  
87
   /**
88
    * Removes some leading elements from a String array.
89
    *
90
    * @param arr
91
    *                The array.
92
    * @param first
93
    *                First element to keep (new 0-index).
94
    * @return Copy of arr[first..]
95
    */
96
   public static String[] subarray(final String[] arr,
97
                                   final int first) {
98
      return subarray(arr, first, arr.length - 1);
99
   }
100

  
101

  
102
   /**
103
    * Formats a number of bytes for output.
104
    *
105
    * @param bytes
106
    *                Number of bytes.
107
    * @return "xxxxK" form.
108
    */
109
   public static String fmtBytes(final long bytes) {
110
      return Long.toString(bytes / 1024) + "K";
111
   }
112

  
113

  
114
   /**
115
    * Formats time for output.
116
    *
117
    * @param bytes
118
    *                Number of milliseconds.
119
    * @return "x,yyys" form.
120
    */
121
   public static String fmtTime(final long ms) {
122
      return Float.toString(ms / 1000.0f) + "s";
123
   }
124

  
125

  
126
   /**
127
    * Return a String made of spaces.
128
    *
129
    * @param len
130
    *                Number of spaces
131
    */
132
   public static String getSpaces(final int len) {
133
      final StringBuffer buf = new StringBuffer();
134

  
135
      for (int i = 0; i < len; i++) {
136
         buf.append(' ');
137
      }
138

  
139
      return buf.toString();
140
   }
141

  
142

  
143
   public static String[] toArray(final Vector strings) {
144
      final String[] arr = new String[strings.size()];
145

  
146
      for (int i = 0; i < strings.size(); ++i) {
147
         arr[i] = (String) strings.elementAt(i);
148
      }
149

  
150
      return arr;
151
   }
152

  
153

  
154
   /**
155
    * When the user has to specify file names, he can use wildcards (*, ?). This methods handles the usage of these wildcards.
156
    *
157
    * @param s
158
    *                Wilcards
159
    * @param sort
160
    *                Set to true will sort file names
161
    * @return An array of String which contains all files matching <code>s</code> in current directory.
162
    * @see Utils#match(String, String)
163
    */
164

  
165
   public static String[] getWildCardMatches(final String s,
166
                                             final boolean sort) {
167
      final String args = new String(s.trim());
168
      String files[];
169
      final Vector filesThatMatchVector = new Vector();
170
      String filesThatMatch[];
171

  
172
      files = (new File(getUserDirectory())).list();
173

  
174
      for (int i = 0; i < files.length; i++) {
175
         if (match(args, files[i])) {
176
            final File temp = new File(getUserDirectory(), files[i]);
177
            filesThatMatchVector.addElement(new String(temp.getName()));
178
         }
179
      }
180

  
181
      filesThatMatch = new String[filesThatMatchVector.size()];
182
      filesThatMatchVector.copyInto(filesThatMatch);
183

  
184
      if (sort) {
185
         sortStrings(filesThatMatch);
186
      }
187

  
188
      return filesThatMatch;
189
   }
190

  
191

  
192
   /**
193
    * This method can determine if a String matches a pattern of wildcards
194
    *
195
    * @param pattern
196
    *                The pattern used for comparison
197
    * @param string
198
    *                The String to be checked
199
    * @return true if <code>string</code> matches <code>pattern</code>
200
    * @see Utils#getWildCardMatches(String)
201
    */
202

  
203
   public static boolean match(final String pattern,
204
                               final String string) {
205
      for (int p = 0;; p++) {
206
         for (int s = 0;; p++, s++) {
207
            final boolean sEnd = (s >= string.length());
208
            final boolean pEnd = (p >= pattern.length() || pattern.charAt(p) == '|');
209

  
210
            if (sEnd && pEnd) {
211
               return true;
212
            }
213
            if (sEnd || pEnd) {
214
               break;
215
            }
216
            if (pattern.charAt(p) == '?') {
217
               continue;
218
            }
219

  
220
            if (pattern.charAt(p) == '*') {
221
               int i;
222
               p++;
223

  
224
               for (i = string.length(); i >= s; --i) {
225
                  if (match(pattern.substring(p), string.substring(i))) {
226
                     return true;
227
                  }
228
               }
229

  
230
               break;
231
            }
232

  
233
            if (pattern.charAt(p) != string.charAt(s)) {
234
               break;
235
            }
236
         }
237

  
238
         p = pattern.indexOf('|', p);
239

  
240
         if (p == -1) {
241
            return false;
242
         }
243
      }
244
   }
245

  
246

  
247
   /**
248
    * Quick sort an array of Strings.
249
    *
250
    * @param string
251
    *                Strings to be sorted
252
    */
253

  
254
   public static void sortStrings(final String[] strings) {
255
      sortStrings(strings, 0, strings.length - 1);
256
   }
257

  
258

  
259
   /**
260
    * Quick sort an array of Strings.
261
    *
262
    * @param a
263
    *                Strings to be sorted
264
    * @param lo0
265
    *                Lower bound
266
    * @param hi0
267
    *                Higher bound
268
    */
269

  
270
   public static void sortStrings(final String a[],
271
                                  final int lo0,
272
                                  final int hi0) {
273
      int lo = lo0;
274
      int hi = hi0;
275
      String mid;
276

  
277
      if (hi0 > lo0) {
278
         mid = a[(lo0 + hi0) / 2];
279

  
280
         while (lo <= hi) {
281
            while (lo < hi0 && a[lo].compareTo(mid) < 0) {
282
               ++lo;
283
            }
284

  
285
            while (hi > lo0 && a[hi].compareTo(mid) > 0) {
286
               --hi;
287
            }
288

  
289
            if (lo <= hi) {
290
               swap(a, lo, hi);
291
               ++lo;
292
               --hi;
293
            }
294
         }
295

  
296
         if (lo0 < hi) {
297
            sortStrings(a, lo0, hi);
298
         }
299

  
300
         if (lo < hi0) {
301
            sortStrings(a, lo, hi0);
302
         }
303
      }
304
   }
305

  
306

  
307
   /**
308
    * Swaps two Strings.
309
    *
310
    * @param a
311
    *                The array to be swapped
312
    * @param i
313
    *                First String index
314
    * @param j
315
    *                Second String index
316
    */
317

  
318
   public static void swap(final String a[],
319
                           final int i,
320
                           final int j) {
321
      String T;
322
      T = a[i];
323
      a[i] = a[j];
324
      a[j] = T;
325
   }
326

  
327

  
328
   /**
329
    * Returns the user current directory.
330
    */
331
   public static String getUserDirectory() {
332

  
333
      String folder = SextanteGUI.getOutputFolder();
334
      if (folder == null) {
335
         folder = System.getProperty("user.home");
336
      }
337

  
338
      return folder;
339

  
340
   }
341

  
342

  
343
   /**
344
    * Sometimes, Strings are too long to be correctly displayed. This method will reduce a String, keeping first and last
345
    * characters.
346
    *
347
    * @param longString
348
    *                The String to be modified
349
    * @param maxLength
350
    *                The maximum length of the String
351
    * @return A shorter String
352
    */
353

  
354
   public static String getShortStringOf(final String longString,
355
                                         final int maxLength) {
356
      final int len = longString.length();
357

  
358
      if (len < maxLength) {
359
         return longString;
360
      }
361
      else {
362
         return longString.substring(0, maxLength / 2) + "..." + longString.substring(len - (maxLength / 2));
363
      }
364
   }
365

  
366

  
367
   /**
368
    * Because a lot of people still use JDK 1.1, we need this method to create an array of Files from an array of String.
369
    *
370
    * @param names
371
    *                Names of the files
372
    * @param construct
373
    *                Set it to true if names does not contain full paths
374
    * @return An array of Files
375
    */
376
   public static File[] listFiles(final String[] names,
377
                                  final boolean construct) {
378
      final File[] files = new File[names.length];
379

  
380
      String path = Utils.getUserDirectory();
381

  
382
      if (construct) {
383
         if (!path.endsWith(File.separator)) {
384
            path += File.separator;
385
         }
386
      }
387

  
388
      for (int i = 0; i < files.length; i++) {
389
         if (construct) {
390
            files[i] = new File(path + names[i]);
391
         }
392
         else {
393
            files[i] = new File(names[i]);
394
         }
395
      }
396

  
397
      return files;
398
   }
399

  
400

  
401
   /**
402
    * Counts things in an Enumeration (and destroys it as a side effect).
403
    *
404
    * @param enum
405
    *                The enumeration, in the start position.
406
    * @return Elements found.
407
    */
408
   public static int getSize(final Enumeration enu) {
409
      int size = 0;
410

  
411
      while (enu.hasMoreElements()) {
412
         ++size;
413
         enu.nextElement();
414
      }
415

  
416
      return size;
417
   }
418

  
419

  
420
   /**
421
    * Constructs a new path from current user path. This is an easy way to get a path if the user specified, for example,
422
    * "..\Java" as new path. This method will return the argument if this one is a path to a root (i.e, if <code>change</code>
423
    * is equal to C:\Jdk, constructPath will return C:\Jdk).
424
    *
425
    * @param change
426
    *                The modification to apply to the path
427
    * @see Utils#beginsWithRoot(String), Utils#getRoot(String)
428
    */
429

  
430
   public static String constructPath(final String change) {
431
      if (change == null || beginsWithRoot(change)) {
432
         return change;
433
      }
434

  
435
      String newPath = getUserDirectory();
436

  
437
      char current;
438
      char lastChar = '\0';
439
      boolean toAdd = false;
440
      StringBuffer buf = new StringBuffer(change.length());
441

  
442
      for (int i = 0; i < change.length(); i++) {
443
         switch ((current = change.charAt(i))) {
444
            case '.':
445
               if (lastChar == '.') {
446
                  final String parent = (new File(newPath)).getParent();
447
                  if (parent != null) {
448
                     newPath = parent;
449
                  }
450
               }
451
               else if (lastChar != '\0' && lastChar != '\\' && lastChar != '/') {
452
                  buf.append('.');
453
               }
454
               lastChar = '.';
455
               break;
456
            case '\\':
457
            case '/':
458
               if (lastChar == '\0') {
459
                  newPath = getRoot(newPath);
460
               }
461
               else {
462
                  if (!newPath.endsWith("\\")) {
463
                     newPath += File.separator + buf.toString();
464
                  }
465
                  else {
466
                     newPath += buf.toString();
467
                  }
468
                  buf = new StringBuffer();
469
                  toAdd = false;
470
               }
471
               lastChar = '\\';
472
               break;
473
            case '~':
474
               if (i < change.length() - 1) {
475
                  if (change.charAt(i + 1) == '\\' || change.charAt(i + 1) == '/') {
476
                     newPath = System.getProperties().getProperty("user.home");
477
                  }
478
                  else {
479
                     buf.append('~');
480
                  }
481
               }
482
               else if (i == 0) {
483
                  newPath = System.getProperties().getProperty("user.home");
484
               }
485
               else {
486
                  buf.append('~');
487
               }
488
               lastChar = '~';
489
               break;
490
            default:
491
               lastChar = current;
492
               buf.append(current);
493
               toAdd = true;
494
               break;
495
         }
496
      }
497

  
498
      if (toAdd) {
499
         if (!newPath.endsWith(File.separator)) {
500
            newPath += File.separator + buf.toString();
501
         }
502
         else {
503
            newPath += buf.toString();
504
         }
505
      }
506

  
507
      return newPath;
508
   }
509

  
510

  
511
   /**
512
    * It can be necessary to determine which is the root of a path. For example, the root of D:\Projects\Java is D:\.
513
    *
514
    * @param path
515
    *                The path used to get a root
516
    * @return The root which contais the specified path
517
    */
518

  
519
   public static String getRoot(final String path) {
520
      final File roots[] = listRoots(new File(path));
521

  
522
      for (int i = 0; i < roots.length; i++) {
523
         if (path.startsWith(roots[i].getPath())) {
524
            return roots[i].getPath();
525
         }
526
      }
527

  
528
      return path;
529
   }
530

  
531

  
532
   /**
533
    * It can be necessary to determine if a path begins with a root.
534
    *
535
    * @param path
536
    *                The path to check
537
    * @return True if path begins with a root, false otherwise
538
    */
539

  
540
   public static boolean beginsWithRoot(final String path) {
541
      final File roots[] = listRoots(new File(path));
542

  
543
      for (int i = 0; i < roots.length; i++) {
544
         if (path.regionMatches(true, 0, roots[i].getPath(), 0, roots[i].getPath().length())) {
545
            return true;
546
         }
547
      }
548

  
549
      return false;
550
   }
551

  
552

  
553
   /**
554
    * We override a Java2 specific method.
555
    *
556
    * @param f
557
    *                A File
558
    * @return A list of standards roots
559
    */
560

  
561
   public static File[] listRoots(final File f) {
562
      if (System.getProperty("os.name").startsWith("Windows")) {
563
         return new File[] { new File("A:\\"), new File("B:\\"), new File("C:\\"), new File("D:\\"), new File("E:\\"),
564
                  new File("F:\\"), new File("G:\\"), new File("H:\\"), new File("I:\\") };
565
         //return new File[]{new File(System.getProperty("java.home").substring(0, 3))};
566
      }
567
      else {
568
         return new File[] { new File("/") };
569
      }
570
   }
571

  
572

  
573
   /**
574
    * We override a Java2 spcific method.
575
    *
576
    * @param file
577
    *                Determine if this file is hidden or not
578
    * @return Always false
579
    */
580

  
581
   public boolean isHidden(final File file) {
582
      return false;
583
   }
584

  
585
}
586

  
587
// End of Utils.java
0 588

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/OpenCommandLineInterfaceAction.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import es.unex.sextante.core.Sextante;
4
import es.unex.sextante.gui.core.SextanteGUI;
5
import es.unex.sextante.gui.core.ToolboxAction;
6

  
7
public class OpenCommandLineInterfaceAction
8
         extends
9
            ToolboxAction {
10

  
11
   @Override
12
   public void execute() {
13

  
14
      SextanteGUI.getGUIFactory().showCommandLineDialog();
15

  
16
   }
17

  
18

  
19
   @Override
20
   public String getGroup() {
21

  
22
      return Sextante.getText("Tools");
23

  
24
   }
25

  
26

  
27
   @Override
28
   public String getName() {
29

  
30
      return Sextante.getText("OpenCommandLineInterface");
31

  
32
   }
33

  
34

  
35
   @Override
36
   public boolean isActive() {
37

  
38
      return true;
39

  
40
   }
41

  
42
}
0 43

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/EditScriptAction.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import es.unex.sextante.core.GeoAlgorithm;
4
import es.unex.sextante.core.Sextante;
5
import es.unex.sextante.gui.core.IToolboxRightButtonAction;
6

  
7
public class EditScriptAction
8
         implements
9
            IToolboxRightButtonAction {
10

  
11
   public void execute(final GeoAlgorithm alg) {
12
   // TODO Auto-generated method stub
13

  
14
   }
15

  
16

  
17
   public String getDescription() {
18

  
19
      return Sextante.getText("Edit");
20

  
21
   }
22

  
23

  
24
   public boolean canBeExecutedOnAlgorithm(final GeoAlgorithm alg) {
25

  
26
      return alg instanceof ScriptAlgorithm;
27

  
28
   }
29

  
30
}
0 31

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/ScriptEditingPanel.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import info.clearthought.layout.TableLayout;
4
import info.clearthought.layout.TableLayoutConstants;
5

  
6
import java.awt.Dimension;
7
import java.awt.event.ActionEvent;
8
import java.awt.event.ActionListener;
9
import java.io.BufferedReader;
10
import java.io.BufferedWriter;
11
import java.io.File;
12
import java.io.FileNotFoundException;
13
import java.io.FileReader;
14
import java.io.FileWriter;
15
import java.io.IOException;
16
import java.io.Writer;
17

  
18
import javax.swing.BorderFactory;
19
import javax.swing.JButton;
20
import javax.swing.JFileChooser;
21
import javax.swing.JPanel;
22
import javax.swing.JScrollPane;
23
import javax.swing.JTextArea;
24
import javax.swing.ScrollPaneConstants;
25
import javax.swing.border.BevelBorder;
26

  
27
import es.unex.sextante.core.Sextante;
28
import es.unex.sextante.gui.algorithm.GenericFileFilter;
29
import es.unex.sextante.gui.core.SextanteGUI;
30
import es.unex.sextante.gui.settings.SextanteScriptsSettings;
31

  
32
public class ScriptEditingPanel
33
         extends
34
            JPanel {
35

  
36
   private String      m_sFilename;
37
   private JButton     jButtonOpen;
38
   private JTextArea   jScriptTextArea;
39
   private JScrollPane jScrollPaneTextArea;
40
   private JButton     jButtonSave;
41

  
42

  
43
   public ScriptEditingPanel() {
44

  
45
      super();
46

  
47
      initGUI();
48

  
49
   }
50

  
51

  
52
   public ScriptEditingPanel(final String sScriptFilename) {
53

  
54
      super();
55

  
56
      m_sFilename = sScriptFilename;
57

  
58
      initGUI();
59

  
60
      openFromFile(new File(sScriptFilename));
61

  
62
   }
63

  
64

  
65
   private void initGUI() {
66

  
67
      final TableLayout layout = new TableLayout(new double[][] { { TableLayoutConstants.FILL, 70.0, 5.0, 70.0, 5 },
68
               { TableLayoutConstants.FILL, 5.0, 25.0, 5.0 } });
69
      layout.setHGap(5);
70
      layout.setVGap(5);
71

  
72
      this.setLayout(layout);
73

  
74
      this.setPreferredSize(new Dimension(600, 500));
75
      this.setSize(new Dimension(600, 500));
76
      jScriptTextArea = new JTextArea();
77
      jScriptTextArea.setEditable(true);
78
      jScriptTextArea.setLineWrap(false);
79
      jScrollPaneTextArea = new JScrollPane(jScriptTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
80
               ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
81
      this.add(jScrollPaneTextArea, "0,0,4,0");
82
      jScriptTextArea.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
83

  
84
      jButtonOpen = new JButton(Sextante.getText("Open"));
85
      this.add(jButtonOpen, "1, 2");
86
      jButtonOpen.addActionListener(new ActionListener() {
87
         public void actionPerformed(final ActionEvent e) {
88
            open();
89
         }
90
      });
91

  
92
      jButtonSave = new JButton(Sextante.getText("Save"));
93
      this.add(jButtonSave, "3, 2");
94
      jButtonSave.addActionListener(new ActionListener() {
95
         public void actionPerformed(final ActionEvent e) {
96
            save();
97
         }
98
      });
99

  
100

  
101
   }
102

  
103

  
104
   protected void save() {
105

  
106
      final JFileChooser fc = new JFileChooser();
107
      final GenericFileFilter filter = new GenericFileFilter("bsh", "SEXTANTE BeanShell Script");
108
      fc.setFileFilter(filter);
109
      if (m_sFilename != null) {
110
         fc.setSelectedFile(new File(m_sFilename));
111
      }
112
      else {
113
         final String sFolder = SextanteGUI.getSettingParameterValue(SextanteScriptsSettings.SCRIPTS_FOLDER);
114
         fc.setCurrentDirectory(new File(sFolder));
115
      }
116
      final int returnVal = fc.showSaveDialog(this);
117

  
118
      if (returnVal == JFileChooser.APPROVE_OPTION) {
119
         final File file = fc.getSelectedFile();
120
         m_sFilename = file.getAbsolutePath();
121
         saveToFile();
122
         SextanteGUI.updateAlgorithmProvider(ScriptAlgorithmProvider.class);
123
         SextanteGUI.getGUIFactory().updateToolbox();
124
      }
125

  
126
   }
127

  
128

  
129
   private void saveToFile() {
130

  
131
      Writer output = null;
132
      try {
133
         output = new BufferedWriter(new FileWriter(m_sFilename));
134
         output.write(jScriptTextArea.getText());
135

  
136
      }
137
      catch (final IOException e) {
138
         Sextante.addErrorToLog(e);
139
      }
140
      finally {
141
         if (output != null) {
142
            try {
143
               output.close();
144
            }
145
            catch (final IOException e) {
146
               Sextante.addErrorToLog(e);
147
            }
148
         }
149
      }
150

  
151

  
152
   }
153

  
154

  
155
   protected void open() {
156

  
157
      final JFileChooser fc = new JFileChooser();
158

  
159
      final String sFolder = SextanteGUI.getSettingParameterValue(SextanteScriptsSettings.SCRIPTS_FOLDER);
160
      fc.setFileFilter(new GenericFileFilter("bsh", "SEXTANTE BeanShell Script"));
161
      fc.setCurrentDirectory(new File(sFolder));
162
      final int returnVal = fc.showOpenDialog(this);
163

  
164
      if (returnVal == JFileChooser.APPROVE_OPTION) {
165
         final File file = fc.getSelectedFile();
166
         openFromFile(file);
167

  
168
      }
169

  
170

  
171
   }
172

  
173

  
174
   private void openFromFile(final File file) {
175

  
176

  
177
      BufferedReader input = null;
178
      try {
179
         input = new BufferedReader(new FileReader(file));
180
         final StringBuffer sText = new StringBuffer();
181
         String sLine = null;
182
         while ((sLine = input.readLine()) != null) {
183
            sText.append(sLine + "\n");
184
         }
185
         jScriptTextArea.setText(sText.toString());
186
      }
187
      catch (final FileNotFoundException e) {}
188
      catch (final IOException e) {}
189
      finally {
190
         try {
191
            if (input != null) {
192
               input.close();
193
            }
194
         }
195
         catch (final IOException e) {
196
            Sextante.addErrorToLog(e);
197
         }
198
      }
199

  
200

  
201
   }
202

  
203
}
0 204

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/ScriptAlgorithm.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import java.io.BufferedReader;
4
import java.io.File;
5
import java.io.FileReader;
6

  
7
import bsh.EvalError;
8
import bsh.Interpreter;
9
import es.unex.sextante.additionalInfo.AdditionalInfo;
10
import es.unex.sextante.additionalInfo.AdditionalInfoBoolean;
11
import es.unex.sextante.additionalInfo.AdditionalInfoMultipleInput;
12
import es.unex.sextante.additionalInfo.AdditionalInfoNumericalValue;
13
import es.unex.sextante.additionalInfo.AdditionalInfoRasterLayer;
14
import es.unex.sextante.additionalInfo.AdditionalInfoString;
15
import es.unex.sextante.additionalInfo.AdditionalInfoTable;
16
import es.unex.sextante.additionalInfo.AdditionalInfoVectorLayer;
17
import es.unex.sextante.core.GeoAlgorithm;
18
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
19
import es.unex.sextante.exceptions.RepeatedParameterNameException;
20
import es.unex.sextante.gui.core.SextanteGUI;
21
import es.unex.sextante.gui.exceptions.WrongScriptException;
22
import es.unex.sextante.gui.settings.SextanteScriptsSettings;
23
import es.unex.sextante.outputs.Output;
24
import es.unex.sextante.outputs.OutputRasterLayer;
25
import es.unex.sextante.outputs.OutputTable;
26
import es.unex.sextante.outputs.OutputVectorLayer;
27
import es.unex.sextante.parameters.Parameter;
28
import es.unex.sextante.parameters.ParameterBoolean;
29
import es.unex.sextante.parameters.ParameterMultipleInput;
30
import es.unex.sextante.parameters.ParameterNumericalValue;
31
import es.unex.sextante.parameters.ParameterRasterLayer;
32
import es.unex.sextante.parameters.ParameterString;
33
import es.unex.sextante.parameters.ParameterTable;
34
import es.unex.sextante.parameters.ParameterVectorLayer;
35

  
36
public class ScriptAlgorithm
37
         extends
38
            GeoAlgorithm {
39

  
40

  
41
   private static Interpreter m_Interpreter;
42
   private String             m_sDescriptionFile;
43

  
44

  
45
   public void initialize(final String sDescriptionFile) throws WrongScriptException {
46

  
47
      final String sFolder = SextanteGUI.getSettingParameterValue(SextanteScriptsSettings.SCRIPTS_FOLDER);
48
      m_sDescriptionFile = sFolder + File.separator + sDescriptionFile;
49
      setName(sDescriptionFile.substring(0, sDescriptionFile.indexOf(".")));
50
      setGroup("Scripts");
51

  
52
      setIsDeterminatedProcess(false);
53
      setUserCanDefineAnalysisExtent(true);
54
      defineCharacteristicsFromDescriptionFile();
55

  
56
      FileReader reader;
57
      try {
58
         reader = new FileReader(m_sDescriptionFile);
59
         m_Interpreter.eval(reader);
60
      }
61
      catch (final Exception e) {
62
         throw new WrongScriptException(e.getMessage());
63
      }
64

  
65

  
66
   }
67

  
68

  
69
   private void defineCharacteristicsFromDescriptionFile() throws WrongScriptException {
70

  
71
      try {
72
         final BufferedReader input = new BufferedReader(new FileReader(m_sDescriptionFile));
73
         String sLine = input.readLine().trim();
74
         while (sLine != null) {
75
            if (sLine.startsWith("//")) {
76
               processParameterLine(sLine);
77
            }
78
            sLine = input.readLine();
79
         }
80
         input.close();
81
      }
82
      catch (final Exception e) {
83

  
84
         throw new WrongScriptException(e.getMessage());
85
      }
86

  
87

  
88
   }
89

  
90

  
91
   private void processParameterLine(String sLine) throws WrongScriptException {
92

  
93
      Parameter param = null;
94
      Output out = null;
95
      AdditionalInfo additionalInfo = null;
96
      sLine = sLine.replace("/", "");
97
      final String[] sTokens = sLine.split("=");
98
      if (sTokens[1].toLowerCase().equals("raster")) {
99
         param = new ParameterRasterLayer();
100
         additionalInfo = new AdditionalInfoRasterLayer(true);
101
      }
102
      else if (sTokens[1].toLowerCase().equals("vector")) {
103
         param = new ParameterVectorLayer();
104
         additionalInfo = new AdditionalInfoVectorLayer(AdditionalInfoVectorLayer.SHAPE_TYPE_ANY, true);
105
      }
106
      else if (sTokens[1].toLowerCase().equals("table")) {
107
         param = new ParameterTable();
108
         additionalInfo = new AdditionalInfoTable(true);
109
      }
110
      else if (sTokens[1].toLowerCase().equals("multiple raster")) {
111
         param = new ParameterMultipleInput();
112
         additionalInfo = new AdditionalInfoMultipleInput(AdditionalInfoMultipleInput.DATA_TYPE_RASTER, true);
113
      }
114
      else if (sTokens[1].toLowerCase().equals("multiple vector")) {
115
         param = new ParameterMultipleInput();
116
         additionalInfo = new AdditionalInfoMultipleInput(AdditionalInfoMultipleInput.DATA_TYPE_VECTOR_ANY, true);
117

  
118
      }
119
      else if (sTokens[1].toLowerCase().equals("boolean")) {
120
         param = new ParameterBoolean();
121
         additionalInfo = new AdditionalInfoBoolean(true);
122
      }
123
      else if (sTokens[1].toLowerCase().equals("number")) {
124
         param = new ParameterNumericalValue();
125
         additionalInfo = new AdditionalInfoNumericalValue(AdditionalInfoNumericalValue.NUMERICAL_VALUE_DOUBLE, 0,
126
                  Double.NEGATIVE_INFINITY, Double.MAX_VALUE);
127
      }
128
      else if (sTokens[1].toLowerCase().equals("string")) {
129
         param = new ParameterString();
130
         additionalInfo = new AdditionalInfoString();
131
      }
132
      else if (sTokens[1].toLowerCase().equals("output raster")) {
133
         out = new OutputRasterLayer();
134
      }
135
      else if (sTokens[1].toLowerCase().equals("output vector")) {
136
         out = new OutputVectorLayer();
137
      }
138
      else if (sTokens[1].toLowerCase().equals("output table")) {
139
         out = new OutputTable();
140
      }
141

  
142
      if (param != null) {
143
         param.setParameterName(sTokens[0]);
144
         param.setParameterDescription(sTokens[0]);
145
         param.setParameterAdditionalInfo(additionalInfo);
146
         try {
147
            m_Parameters.addParameter(param);
148
         }
149
         catch (final RepeatedParameterNameException e) {
150
            throw new WrongScriptException(e.getMessage());
151
         }
152
      }
153
      else if (out != null) {
154
         out.setDescription(sTokens[0]);
155
         out.setName(sTokens[0]);
156
         m_OutputObjects.add(out);
157
      }
158
      else {
159
         throw new WrongScriptException();
160
      }
161
   }
162

  
163

  
164
   @Override
165
   public void defineCharacteristics() {}
166

  
167

  
168
   @Override
169
   public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
170

  
171
      final StringBuffer sb = new StringBuffer(getName() + "(");
172

  
173
      for (int i = 0; i < m_Parameters.getNumberOfParameters(); i++) {
174
         final Parameter param = m_Parameters.getParameter(i);
175
         sb.append(param.getCommandLineParameter() + ", ");
176
      }
177

  
178
      for (int j = 0; j < m_OutputObjects.getOutputObjectsCount(); j++) {
179
         final Output out = m_OutputObjects.getOutput(j);
180
         sb.append(out.getCommandLineParameter() + ", ");
181
      }
182

  
183
      final String sCommand = sb.substring(0, sb.length() - 2) + ")";
184
      try {
185
         m_Interpreter.eval(sCommand);
186
      }
187
      catch (final EvalError e) {
188
         e.printStackTrace();
189
         throw new GeoAlgorithmExecutionException(e.getErrorText());
190
      }
191

  
192
      //we return false because output objects should not be processed
193
      return false;
194

  
195
   }
196

  
197

  
198
   @Override
199
   public String getCommandLineName() {
200

  
201
      return getName();
202

  
203
   }
204

  
205

  
206
   public static void resetInterpreter() {
207

  
208
      m_Interpreter = new Interpreter();
209
      m_Interpreter.getNameSpace().importCommands("es.unex.sextante.gui.cmd.bshcommands");
210

  
211

  
212
   }
213

  
214

  
215
   public String getDescriptionFile() {
216

  
217
      return m_sDescriptionFile;
218

  
219
   }
220

  
221
}
0 222

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/BSHDialog.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import java.awt.BorderLayout;
4
import java.awt.Dimension;
5
import java.awt.Frame;
6
import java.io.FileReader;
7

  
8
import javax.swing.JDialog;
9

  
10
import bsh.Interpreter;
11
import bsh.util.JConsole;
12
import es.unex.sextante.core.Sextante;
13

  
14
/**
15
 * A dialog with a BeanShell interface with extended commands to execute SEXTANTE algorithms
16
 * 
17
 * @author volaya
18
 * 
19
 */
20
public class BSHDialog
21
         extends
22
            JDialog {
23

  
24
   public BSHDialog(final Frame parent) {
25

  
26
      super(parent, Sextante.getText("Command_line"), true);
27
      setSize(new Dimension(400, 300));
28
      setPreferredSize(new Dimension(400, 300));
29
      getContentPane().setLayout(new BorderLayout());
30
      final JConsole console = new JConsole();
31
      getContentPane().add("Center", console);
32
      final Interpreter interpreter = new Interpreter(console);
33
      interpreter.getNameSpace().importCommands("es.unex.sextante.gui.cmd.bshcommands");
34
      final String[] files = ScriptsIO.getScriptFiles();
35
      if (files != null) {
36
         for (int i = 0; i < files.length; i++) {
37
            try {
38
               final FileReader reader = new FileReader(files[i]);
39
               interpreter.eval(reader);
40
            }
41
            catch (final Exception e) {}
42
         }
43
      }
44
      new Thread(interpreter).start();
45

  
46
   }
47
}
0 48

  
org.gvsig.toolbox/trunk/org.gvsig.toolbox/org.gvsig.toolbox.gui/src/es/unex/sextante/gui/cmd/Parser.java
1
package es.unex.sextante.gui.cmd;
2

  
3
import java.awt.geom.Point2D;
4
import java.util.ArrayList;
5
import java.util.StringTokenizer;
6

  
7
import es.unex.sextante.additionalInfo.AdditionalInfoBand;
8
import es.unex.sextante.additionalInfo.AdditionalInfoDataObject;
9
import es.unex.sextante.additionalInfo.AdditionalInfoFixedTable;
10
import es.unex.sextante.additionalInfo.AdditionalInfoMultipleInput;
11
import es.unex.sextante.additionalInfo.AdditionalInfoSelection;
12
import es.unex.sextante.additionalInfo.AdditionalInfoTableField;
13
import es.unex.sextante.core.AnalysisExtent;
14
import es.unex.sextante.core.GeoAlgorithm;
15
import es.unex.sextante.core.OutputObjectsSet;
16
import es.unex.sextante.core.ParametersSet;
17
import es.unex.sextante.core.Sextante;
18
import es.unex.sextante.dataObjects.IRasterLayer;
19
import es.unex.sextante.dataObjects.ITable;
20
import es.unex.sextante.dataObjects.IVectorLayer;
21
import es.unex.sextante.gui.core.SextanteGUI;
22
import es.unex.sextante.gui.exceptions.AlgorithmNotFoundException;
23
import es.unex.sextante.gui.exceptions.CommandLineException;
24
import es.unex.sextante.gui.exceptions.OutputExtentNotSetException;
25
import es.unex.sextante.gui.exceptions.WrongNumberOfParametersException;
26
import es.unex.sextante.outputs.FileOutputChannel;
27
import es.unex.sextante.outputs.Output;
28
import es.unex.sextante.outputs.Output3DRasterLayer;
29
import es.unex.sextante.outputs.OutputRasterLayer;
30
import es.unex.sextante.outputs.OutputTable;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff