Revision 1893

View differences:

org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
2

  
3
<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/xsd/maven-4.0.0.xsd">
4
    <modelVersion>4.0.0</modelVersion>
5
    <artifactId>org.gvsig.scripting.app.mainplugin</artifactId>
6
    <packaging>jar</packaging>
7
    <name>${project.artifactId}</name>
8
    <description><![CDATA[
9
This plugin provides support for scripting to gvSIG.
10
Among other things it contains:
11

  
12
- The gvSIG scripting engine
13
- The gvSIG script editor
14
- Script engines for:
15
   - Jython
16
   - Groovy
17
   - javascript
18
   - Renjin
19

  
20
- The script install module for the add-on manager.
21
- Utilities to generate packages of complements with our scripts.
22
- Python libraries as:
23
   - Six - Utilities for writing code that runs on Python 2 and 3
24
   - PyLint - Python source code analyzer
25
   - Pygments - syntax highlighting package
26
   - CSSUtils - CSS Cascading Style Sheets library
27
   - Docutils - Python Documentation Utilities
28
   - geopy - client for several popular geocoding web services
29
   - PyInliner - CSS-to-inline-styles conversion tool for HTML
30
   - Statistics - functions for calculating statistics of data
31
   - Cartodb - simple CartoDB client to perform requests against the CartoDB API
32

  
33
- Java libraries to use from scripting like:
34
   - Abeille forms deseigner
35
   - jOpenDocument
36
   - JNumeric
37
   - CSSBox
38

  
39

  
40
This plugin can be configured to be preinstalled automatically, allowing 
41
"Script" type plugins to be installed during the application installation process. 
42
To do this, the following entries must be added to the "packages.properties" 
43
of gvspks::
44

  
45
    installers=scripts
46
    installer.scripts.initializer=org.gvsig.scripting.app.extension.ScriptsInstallerInitializer
47
    installer.scripts.package.code=org.gvsig.scripting.app.mainplugin
48
    installer.scripts.factory.name=Script
49
    installer.scripts.libs=lib
50

  
51
If the "installers" entry already exists, add "scripts" to the end separating 
52
it with a space.    
53
                            
54
]]></description>
55
    <parent>
56
        <groupId>org.gvsig</groupId>
57
        <artifactId>org.gvsig.scripting.app</artifactId>
58
        <version>2.3.219</version>
59
    </parent>
60
    <dependencies>
61
        <dependency>
62
            <groupId>org.gvsig</groupId>
63
            <artifactId>org.gvsig.tools.lib</artifactId>
64
            <scope>compile</scope>
65
        </dependency>
66
        <!--
67
        <dependency>
68
            <groupId>org.gvsig</groupId>
69
            <artifactId>org.gvsig.tools.lib</artifactId>
70
            <scope>test</scope>
71
        </dependency>
72
        -->
73
        <dependency>
74
            <groupId>org.gvsig</groupId>
75
            <artifactId>org.gvsig.i18n</artifactId>
76
            <scope>compile</scope>
77
        </dependency>
78
        <dependency>
79
            <groupId>org.gvsig</groupId>
80
            <artifactId>org.gvsig.andami</artifactId>
81
            <scope>compile</scope>
82
        </dependency>
83
        <dependency>
84
            <groupId>org.gvsig</groupId>
85
            <artifactId>org.gvsig.app.document.table.app.mainplugin</artifactId>
86
            <scope>compile</scope>
87
        </dependency>
88
        <dependency>
89
            <groupId>org.gvsig</groupId>
90
            <artifactId>org.gvsig.app.mainplugin</artifactId>
91
            <scope>compile</scope>
92
        </dependency>
93
        <dependency>
94
            <groupId>org.gvsig</groupId>
95
            <artifactId>org.gvsig.tools.swing.impl</artifactId>
96
            <scope>compile</scope>
97
        </dependency>
98
        <dependency>
99
            <groupId>org.gvsig</groupId>
100
            <artifactId>org.gvsig.about.api</artifactId>
101
            <scope>compile</scope>
102
        </dependency>
103
        <dependency>
104
            <groupId>org.gvsig</groupId>
105
            <artifactId>org.gvsig.scripting.lib.api</artifactId>
106
            <scope>compile</scope>
107
        </dependency>
108
        <dependency>
109
            <groupId>org.gvsig</groupId>
110
            <artifactId>org.gvsig.scripting.swing.api</artifactId>
111
            <scope>compile</scope>
112
        </dependency>
113
        <dependency>
114
            <groupId>org.gvsig</groupId>
115
            <artifactId>org.gvsig.scripting.lib.impl</artifactId>
116
            <scope>compile</scope>
117
        </dependency>
118
        <dependency>
119
            <groupId>org.gvsig</groupId>
120
            <artifactId>org.gvsig.scripting.swing.impl</artifactId>
121
            <scope>compile</scope>
122
        </dependency>
123

  
124
        <!-- force adding -->
125
        <dependency>
126
            <groupId>org.ini4j</groupId>
127
            <artifactId>ini4j</artifactId>
128
            <scope>runtime</scope>
129
        </dependency>
130
        <dependency>
131
            <groupId>net.sourceforge.thinlet</groupId>
132
            <artifactId>thinlet</artifactId>
133
            <scope>runtime</scope>
134
        </dependency>
135
        <dependency>
136
            <groupId>org.gvsig</groupId>
137
            <artifactId>org.gvsig.scripting.thing</artifactId>
138
            <scope>runtime</scope>
139
        </dependency>
140
        <dependency>
141
            <groupId>com.jeta</groupId>
142
            <artifactId>abeille</artifactId>
143
            <type>tar.gz</type>
144
            <scope>runtime</scope>
145
        </dependency>
146
        <dependency>
147
            <groupId>org.jopendocument</groupId>
148
            <artifactId>jOpenDocument</artifactId>
149
            <scope>runtime</scope>
150
        </dependency>
151
        <dependency>
152
            <groupId>com.github.tbekolay.jnumeric</groupId>
153
            <artifactId>jnumeric</artifactId>
154
            <scope>runtime</scope>
155
        </dependency>
156
 
157
        <dependency>
158
            <groupId>org.apache.tika</groupId>
159
            <artifactId>tika-core</artifactId>
160
            <scope>runtime</scope>
161
        </dependency>
162

  
163
        <dependency>
164
            <groupId>org.python</groupId>
165
            <artifactId>${jython.artifactId}</artifactId>
166
            <scope>runtime</scope>
167
        </dependency>
168
        <dependency>
169
            <groupId>org.codehaus.groovy</groupId>
170
            <artifactId>groovy-all</artifactId>
171
            <scope>runtime</scope>
172
        </dependency>
173
        <dependency>
174
            <groupId>org.renjin</groupId>
175
            <artifactId>renjin-script-engine</artifactId>
176
            <classifier>jar-with-dependencies</classifier>
177
            <scope>runtime</scope>
178
        </dependency>      
179
        
180
        <!--
181
        <dependency>
182
            <groupId>org.scala-lang</groupId>
183
            <artifactId>scala-dist</artifactId>
184
            <scope>runtime</scope>
185
        </dependency>
186
        <dependency>
187
            <groupId>org.scala-lang</groupId>
188
            <artifactId>scala-compiler</artifactId>
189
            <scope>runtime</scope>
190
        </dependency>
191
        <dependency>
192
            <groupId>org.scala-lang</groupId>
193
            <artifactId>scala-library</artifactId>
194
            <scope>runtime</scope>
195
        </dependency>
196
        <dependency>
197
            <groupId>org.scala-lang</groupId>
198
            <artifactId>scala-reflect</artifactId>
199
            <scope>runtime</scope>
200
        </dependency>
201
        <dependency>
202
            <groupId>org.scala-lang</groupId>
203
            <artifactId>scalap</artifactId>
204
            <scope>runtime</scope>
205
        </dependency>
206
        <dependency>
207
            <groupId>jline</groupId>
208
            <artifactId>jline</artifactId>
209
            <scope>runtime</scope>
210
        </dependency>
211
        -->
212
        <dependency>
213
            <groupId>net.sf.cssbox</groupId>
214
            <artifactId>swingbox</artifactId>
215
            <scope>runtime</scope>
216
        </dependency>
217
        <dependency>
218
            <groupId>net.sf.cssbox</groupId>
219
            <artifactId>cssbox</artifactId>
220
            <scope>runtime</scope>
221
        </dependency>
222
        
223
        <dependency>
224
            <groupId>net.sourceforge.nekohtml</groupId>
225
            <artifactId>nekohtml</artifactId>
226
            <scope>runtime</scope>
227
        </dependency>
228
        <dependency>
229
            <groupId>net.sf.cssbox</groupId>
230
            <artifactId>jstyleparser</artifactId>
231
            <scope>runtime</scope>
232
        </dependency>
233
        <dependency>
234
            <groupId>org.antlr</groupId>
235
            <artifactId>antlr-runtime</artifactId>
236
            <!-- Ojo que forzamos una version en concreto -->
237
            <version>3.5.2</version>
238
        </dependency>     
239
        
240
        <!-- JGit runtime dependencies -->   
241
        <dependency>
242
            <groupId>org.eclipse.jgit</groupId>
243
            <artifactId>org.eclipse.jgit</artifactId>
244
            <scope>runtime</scope>
245
        </dependency>                    
246
        
247
        <dependency>
248
            <groupId>org.icepdf.os</groupId>
249
            <artifactId>icepdf-viewer</artifactId>
250
            <version>6.2.2</version>
251
            <exclusions>
252
                <exclusion>
253
                    <groupId>batik</groupId>
254
                    <artifactId>batik-awt-util</artifactId>
255
                </exclusion>        
256
                <exclusion>
257
                    <groupId>batik</groupId>
258
                    <artifactId>batik-dom</artifactId>
259
                </exclusion>        
260
                <exclusion>
261
                    <groupId>batik</groupId>
262
                    <artifactId>batik-svg-dom</artifactId>
263
                </exclusion>        
264
                <exclusion>
265
                    <groupId>batik</groupId>
266
                    <artifactId>batik-svggen</artifactId>
267
                </exclusion>        
268
                <exclusion>
269
                    <groupId>batik</groupId>
270
                    <artifactId>batik-util</artifactId>
271
                </exclusion>        
272
                <exclusion>
273
                    <groupId>batik</groupId>
274
                    <artifactId>batik-xml</artifactId>
275
                </exclusion>        
276
            </exclusions>
277
                
278
        </dependency>
279
                
280
<!--        <dependency>
281
            <groupId>com.vladsch.flexmark</groupId>
282
            <artifactId>flexmark-all</artifactId>
283
            <version>0.60.2</version>
284
        </dependency>-->
285
        <dependency>
286
            <groupId>com.vladsch.flexmark</groupId>
287
            <artifactId>flexmark-all</artifactId>
288
            <version>0.60.2</version>
289
            <scope>runtime</scope>
290
        </dependency>
291
        <dependency>
292
          <groupId>org.apache.pdfbox</groupId>
293
          <artifactId>pdfbox</artifactId>
294
          <version>2.0.16</version>
295
          <scope>runtime</scope>
296
        </dependency>
297
        <dependency>
298
          <groupId>org.apache.pdfbox</groupId>
299
          <artifactId>fontbox</artifactId>
300
          <version>2.0.16</version>
301
          <scope>runtime</scope>
302
        </dependency>
303
        <dependency>
304
          <groupId>com.sksamuel.diff</groupId>
305
          <artifactId>diff</artifactId>
306
          <version>1.1.11</version>
307
          <scope>runtime</scope>
308
        </dependency>
309

  
310
    </dependencies>
311

  
312

  
313
    <properties>
314
        <gvsig.package.info.name>Scripting framework</gvsig.package.info.name>
315
        <gvsig.package.info.dependencies>required: org.gvsig.app.document.table.app.mainplugin -ge 2</gvsig.package.info.dependencies>
316
        <gvsig.package.info.poolURL>https://devel.gvsig.org/download/projects/gvsig-scripting/pool</gvsig.package.info.poolURL>
317
        <gvsig.package.info.sourcesURL>https://devel.gvsig.org/svn/gvsig-scripting</gvsig.package.info.sourcesURL>
318
        <gvsig.package.info.state>testing</gvsig.package.info.state>
319
        <gvsig.package.info.categories>Development</gvsig.package.info.categories>
320
        <gvsig.package.info.official>true</gvsig.package.info.official>
321

  
322
    </properties>
323

  
324
    <build>
325
        <plugins>
326

  
327
            <plugin>
328
                <groupId>org.apache.maven.plugins</groupId>
329
                <artifactId>maven-dependency-plugin</artifactId>
330
                <executions>
331
                    <execution>
332
                        <id>unpack</id>
333
                        <phase>process-sources</phase>
334
                        <goals>
335
                            <goal>unpack</goal>
336
                        </goals>
337
                        <configuration>
338
                            <artifactItems>
339
                                <artifactItem>
340
                                    <groupId>com.jeta</groupId>
341
                                    <artifactId>abeille</artifactId>
342
                                    <version>2.1.0.M3</version>
343
                                    <type>tar.gz</type>
344
                                    <overWrite>true</overWrite>
345
                                    <outputDirectory>target/abeille</outputDirectory>
346
                                </artifactItem>
347
                            </artifactItems>
348
                        </configuration>
349
                    </execution>
350
                </executions>
351
            </plugin>
352

  
353
        </plugins>
354
    </build>
355

  
356
</project>
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/buildNumber.properties
1
#Sun Jul 09 18:55:59 CEST 2023
2
buildNumber=301
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/java/org/gvsig/scripting/app/extension/ScriptLaunchExtension.java
1
package org.gvsig.scripting.app.extension;
2

  
3
import java.io.File;
4
import java.util.ArrayList;
5
import java.util.Arrays;
6
import java.util.List;
7
import javax.swing.JOptionPane;
8
import org.gvsig.andami.PluginsLocator;
9
import org.gvsig.andami.PluginsManager;
10
import org.gvsig.andami.plugins.Extension;
11
import org.gvsig.app.ApplicationLocator;
12
import org.gvsig.app.ApplicationManager;
13
import org.gvsig.scripting.ScriptingLocator;
14
import org.gvsig.scripting.ScriptingManager;
15
import org.gvsig.scripting.ScriptingScript;
16
import org.slf4j.Logger;
17
import org.slf4j.LoggerFactory;
18

  
19
public class ScriptLaunchExtension extends Extension {
20

  
21
    private static final Logger logger = LoggerFactory.getLogger(ScriptLaunchExtension.class);
22

  
23
    @Override
24
    public void initialize() {
25
    }
26

  
27
    @Override
28
    public boolean isEnabled() {
29
        return true;
30
    }
31

  
32
    @Override
33
    public boolean isVisible() {
34
        return true;
35
    }
36

  
37
    @Override
38
    public boolean canQueryByAction() {
39
        return true;
40
    }
41

  
42
    @Override
43
    public void execute(String action) {
44
        ApplicationManager application = ApplicationLocator.getManager();
45
        ScriptingScript script = getScript(action);
46
        if( script == null ) {
47
            application.messageDialog(
48
                    "Can't locate script '"+action+"'", 
49
                    "Warning", 
50
                    JOptionPane.WARNING_MESSAGE
51
            );
52
            return;
53
        }
54
        try {
55
            script.runAsTask(null);
56
        } catch (Throwable th) {
57
            logger.warn("Can't execute '" + action + "' script.", th);
58
        }
59
    }
60

  
61
    @Override
62
    public void execute(String action, Object[] args) {
63
        ApplicationManager application = ApplicationLocator.getManager();
64
        ScriptingScript script = getScript(action);
65
        if( script == null ) {
66
            application.messageDialog(
67
                    "Can't locate script '"+action+"'", 
68
                    "Warning", 
69
                    JOptionPane.WARNING_MESSAGE
70
            );
71
            return;
72
        }
73
        try {
74
            script.runAsTask(args);
75
        } catch (Throwable th) {
76
            logger.warn("Can't execute '" + action + "' script.", th);
77
        }
78
    }
79

  
80
    @Override
81
    public boolean isVisible(String action) {
82
        ScriptingScript script = getScript(action);
83
        try {
84
            Boolean value = (Boolean) script.invokeFunction("isVisible", null);
85
            return value;
86
        } catch (Throwable th) {
87
            logger.warn("Can't execute isVisible in '" + action + "' script.", th);
88
        }
89
        return false;
90
    }
91

  
92
    @Override
93
    public boolean isEnabled(String action) {
94
        ScriptingScript script = getScript(action);
95
        try {
96
            Boolean value = (Boolean) script.invokeFunction("isEnabled", null);
97
            return value;
98
        } catch (Throwable th) {
99
            logger.warn("Can't execute isEnabled in '" + action + "' script.", th);
100
        }
101
        return false;
102
    }
103

  
104
    private ScriptingScript getScript(String scriptpathname) {
105
        final ScriptingManager manager = ScriptingLocator.getManager();
106
        final PluginsManager pluginManager = PluginsLocator.getManager();
107

  
108
        File scriptfile;
109
        ScriptingScript script;
110
        
111
        String s = manager.getRootUserFolder().getAbsolutePath().replace("\\", "/");
112
        scriptfile = new File(s+"/"+scriptpathname);
113
        if (scriptfile.exists()) {
114
            script = (ScriptingScript) manager.getScript(scriptfile);
115
            return script;
116
        }
117
                
118
        final List<File> pluginsFolders = new ArrayList<>();
119
        for (File f : pluginManager.getPluginsFolders()) {
120
            pluginsFolders.addAll(Arrays.asList(f.listFiles()));
121
        }
122

  
123
        for (File pluginFolder : pluginsFolders) {
124
            s = pluginFolder.getAbsolutePath().replace("\\", "/");
125
            scriptfile = new File(s+"/scripting/scripts/"+scriptpathname);
126
            if (scriptfile.exists()) {
127
                script = (ScriptingScript) manager.getScript(scriptfile);
128
                return script;
129
            }
130
        }
131
        return (ScriptingScript) manager.getScript(scriptpathname);
132
    }
133

  
134
}
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/java/org/gvsig/scripting/app/extension/DataFoldersRecoverPanel.java
1
package org.gvsig.scripting.app.extension;
2

  
3
import java.awt.Dimension;
4
import java.util.ArrayList;
5
import java.util.List;
6
import javax.swing.DefaultListModel;
7
import javax.swing.ListSelectionModel;
8
import javax.swing.event.ListSelectionEvent;
9
import javax.swing.event.ListSelectionListener;
10
import org.gvsig.scripting.DataFolderFound;
11
import org.gvsig.tools.swing.api.JListWithCheckbox;
12
import org.gvsig.tools.swing.api.ListElement;
13
import org.gvsig.tools.swing.api.ToolsSwingLocator;
14
import org.gvsig.tools.swing.api.ToolsSwingManager;
15

  
16
/**
17
 *
18
 * @author jjdelcerro
19
 */
20
public class DataFoldersRecoverPanel extends DataFoldersRecoverPanelView {
21

  
22
    private final List<DataFolderFound> dataFoldersFound;
23
    private JListWithCheckbox lstCheckedDataFolders;
24

  
25
    public DataFoldersRecoverPanel(List<DataFolderFound> dataFoldersFound) {
26
        this.dataFoldersFound = dataFoldersFound;
27
        this.initComponents();
28
    }
29

  
30
    private void initComponents() {
31
        ToolsSwingManager manager = ToolsSwingLocator.getToolsSwingManager();
32
        this.lstCheckedDataFolders = manager.createJListWithCheckbox(lstDataFolders);
33
        DefaultListModel model = new DefaultListModel();
34
        for (DataFolderFound dataFolderFound : dataFoldersFound) {
35
            if( dataFolderFound.getApplicationFolder()==null ) {
36
                continue;
37
            }
38
            model.addElement(
39
                new ListElement<>(
40
                    dataFolderFound.getApplicationName() + " ("+dataFolderFound.getDataFolderId()+")", 
41
                    dataFolderFound
42
                )
43
            );
44
        }
45
        this.lstDataFolders.setModel(model);
46
        this.lstDataFolders.addListSelectionListener(new ListSelectionListener() {
47
            @Override
48
            public void valueChanged(ListSelectionEvent e) {
49
                if( e.getValueIsAdjusting() ) {
50
                    return;
51
                }
52
                updateInterfaceData();
53
            }
54
        });
55

  
56
        this.setPreferredSize(new Dimension(500, 420));
57
    }
58

  
59
    private void updateInterfaceData() {
60
        DataFolderFound dataFolder = (DataFolderFound) ListElement.getSelected(this.lstDataFolders);
61
        if (dataFolder == null) {
62
            return;
63
        }
64
        this.txtApplication.setText(dataFolder.getApplicationName());
65
        this.txtPreferencias.setText(dataFolder.getDataFolderId());
66
        this.txtPath.setText(dataFolder.getApplicationFolder().getUserPath());
67
        String path = dataFolder.getOldDataFolder().getAbsolutePath();
68
        this.txtOldFolder.setText(path);
69
        this.txtOldFolder.setCaretPosition(path.length());
70
    }
71

  
72
    public List<DataFolderFound> getSelectedDataFolders() {
73
        List<DataFolderFound> r = new ArrayList<>();
74
        ListSelectionModel checkedModel = this.lstCheckedDataFolders.getCheckedModel();
75
        for (int i = 0; i < dataFoldersFound.size(); i++) {
76
            if (checkedModel.isSelectedIndex(i)) {
77
                r.add(dataFoldersFound.get(i));
78
            }
79
        }
80
        return r;
81
    }
82

  
83
}
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/java/org/gvsig/scripting/app/extension/ScriptingExtension.java
1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 * 
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 * 
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * 
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
 * MA  02110-1301, USA.
20
 * 
21
 */
22
package org.gvsig.scripting.app.extension;
23

  
24
import java.io.File;
25
import java.io.InputStream;
26
import java.net.MalformedURLException;
27
import java.net.URL;
28
import java.util.List;
29
import org.apache.commons.io.IOUtils;
30
import org.apache.commons.lang3.StringUtils;
31

  
32
import org.gvsig.andami.IconThemeHelper;
33
import org.gvsig.andami.PluginServices;
34
import org.gvsig.andami.PluginsLocator;
35
import org.gvsig.andami.PluginsManager;
36
import org.gvsig.andami.plugins.Extension;
37
import org.gvsig.andami.plugins.PluginClassLoader;
38
import org.gvsig.scripting.ScriptingLocator;
39
import org.gvsig.scripting.ScriptingManager;
40
import org.gvsig.scripting.swing.api.ScriptingSwingLocator;
41
import org.gvsig.scripting.swing.api.ScriptingUIManager;
42
import org.gvsig.tools.dynobject.DynObject;
43
import org.gvsig.tools.swing.impl.windowmanager.DefaultWindowManager;
44
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
46
import org.gvsig.tools.script.Script;
47
import org.gvsig.tools.util.Invocable;
48

  
49
@SuppressWarnings("UseSpecificCatch")
50
public class ScriptingExtension extends Extension {
51

  
52
    @SuppressWarnings("FieldNameHidesFieldInSuperclass")
53
    private static final Logger LOGGER = LoggerFactory.getLogger(ScriptingExtension.class);
54

  
55
    private ScriptingUtils utils;
56
    
57
    @Deprecated
58
    public static void log(String message) {
59
        ScriptingUtils.log(ScriptingUtils.INFO, message, null);
60
    }
61

  
62
    @Deprecated
63
    public static void log(int level, String message) {
64
        ScriptingUtils.log(level, message, null);
65
    }
66

  
67
    @Deprecated
68
    public static void log(int level, String message, Throwable th) {
69
        ScriptingUtils.log(level, message, th);
70
    }
71
    
72
    @Override
73
    public void initialize() {
74
        IconThemeHelper.registerIcon("action", "tools-scripting-launcher", this);
75
        IconThemeHelper.registerIcon("action", "tools-scripting-composer", this);
76
        IconThemeHelper.registerIcon("action", "tools-scripting-console-jython", this);
77

  
78
        PluginsManager pluginManager = PluginsLocator.getManager();
79
        this.utils = new ScriptingUtils();
80

  
81
        this.utils.initializaPaths(
82
                pluginManager.getPluginsFolders(), 
83
                pluginManager.getInstallFolder(), 
84
                this.getPlugin().getPluginHomeFolder(), 
85
                pluginManager.getApplicationVersion().format(ScriptsInstallerInitializer.VERSION_FORMAT)
86
        );
87
        
88
        Thread th = new Thread(new Runnable() {
89
            @Override
90
            public void run() {
91
                preloadPythonEngine();
92
            }
93
        }, "ScriptEnginesInitializer");
94
        th.start();
95
        try {
96
            th.join(1000); // force change to other thread
97
        } catch (InterruptedException ex) {
98
            // Ignore.
99
        }
100
    }
101
    
102
    public ScriptingUtils getScriptingUtils() {
103
        return this.utils;
104
    } 
105
    
106
    @Override
107
    public void execute(String actionCommand) {
108
        this.execute(actionCommand, null);
109
    }
110

  
111
    @Override
112
    public void execute(String command, Object[] args) {
113

  
114

  
115
        if( "tools-scripting-launcher".equalsIgnoreCase(command) ) {
116
            utils.runLauncher();
117
            
118
        } else if( "tools-scripting-composer".equalsIgnoreCase(command) ) {
119
            utils.runComposer();
120

  
121
        } else {
122
            utils.runScript(command, args);
123
        }
124
    }
125

  
126
    private void preloadPythonEngine() {
127
        ScriptingManager manager = (ScriptingManager) ScriptingLocator.getManager();
128
        synchronized (manager) {
129
            String respath = "/scripting/langs/python/preload.py";
130
            InputStream res = this.getClass().getResourceAsStream(respath);
131
            if( res != null ) {
132
                LOGGER.info("Scan for script engines");
133
                List<String> lines;
134
                try {
135
                    lines = IOUtils.readLines(res);
136
                    String code = StringUtils.join(lines, "\n");
137
                    LOGGER.info("Preload python script engine");
138
                    Script script = manager.createScript(
139
                        "preload",
140
                        code,
141
                        ScriptingManager.PYTHON_LANGUAGE_NAME
142
                    );
143
                    LOGGER.info("Preload python modules");
144
                    script.invokeFunction("main", null);
145

  
146
                } catch (Exception ex) {
147
                    LOGGER.warn("Can't run preload script for python.", ex);
148
                }
149
                LOGGER.info("Preload of script engines finished");
150
            }
151
        }
152
    }
153

  
154
    
155
    @Override
156
    public void postInitialize() {
157
        super.postInitialize();
158
                        
159
        PluginsManager pluginManager = PluginsLocator.getManager();
160

  
161
        pluginManager.addStartupTask(
162
            "ExecuteAutorunScripts",
163
            utils.getAutorunScriptsOnStartup(pluginManager.getPluginsFolders()),
164
            false,
165
            200
166
        );
167
        pluginManager.addStartupTask(
168
            "PostProcessArguments",
169
            new PostProcessArguments(),
170
            false,
171
            199
172
        );
173

  
174

  
175
        Invocable initializer = new ScriptsInstallerInitializer();
176
        initializer.call(this.getPlugin().getPluginName());
177
    }
178

  
179
    @Override
180
    public boolean isEnabled() {
181
        return true;
182
    }
183

  
184
    @Override
185
    public boolean isVisible() {
186
        return true;
187
    }
188

  
189
    public static void add_classpath(URL url) {
190
        if( url==null ) {
191
            LOGGER.warn("Can't add to the plugin classloader a null URL.");
192
            return;
193
        }
194
        try {
195
            PluginsManager manager = PluginsLocator.getManager();
196
            PluginServices thePlugin = manager.getPlugin(ScriptingExtension.class);
197
            PluginClassLoader loader = thePlugin.getClassLoader();
198
            loader.addURL(url);
199
        } catch(Throwable th) {
200
            LOGGER.warn("Can't add the url '"+url.toString()+"' to the plugin classloader.",th);
201
        }
202
    }
203
    
204
    public static void add_classpath(File path) {
205
        if( path==null ) {
206
            LOGGER.warn("Can't create a url from a null file.");
207
            return;
208
        }
209
        try {
210
            URL url = path.toURI().toURL();
211
            add_classpath(url);
212
        } catch (MalformedURLException ex) {
213
            LOGGER.warn("Can't create a url from the path '"+path+"'.", ex);
214
        }
215
    }
216
    
217
    public static void add_classpath(String path) {
218
        if( path==null ) {
219
            LOGGER.warn("Can't create a url from a null path.");
220
            return;
221
        }
222
        File f = new File(path);
223
        add_classpath(f);
224
    }
225

  
226
    @Override
227
    public PluginServices getPlugin() {
228
        PluginServices thePlugin = super.getPlugin();
229
        if (thePlugin == null) {
230
            thePlugin = PluginsLocator.getManager().getPlugin(ScriptingExtension.class);
231
            this.setPlugin(thePlugin);
232
        }
233
        return thePlugin;
234
    }
235
    
236
}
org.gvsig.scripting/tags/org.gvsig.scripting-2.3.219/org.gvsig.scripting.app/org.gvsig.scripting.app.mainplugin/src/main/java/org/gvsig/scripting/app/extension/ScriptingUtils.java
1
package org.gvsig.scripting.app.extension;
2

  
3
import java.awt.event.ActionEvent;
4
import java.awt.event.ActionListener;
5
import java.io.File;
6
import java.io.IOException;
7
import java.nio.file.FileVisitOption;
8
import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
9
import java.nio.file.FileVisitResult;
10
import java.nio.file.Files;
11
import java.nio.file.Path;
12
import java.nio.file.Paths;
13
import java.nio.file.SimpleFileVisitor;
14
import java.nio.file.attribute.BasicFileAttributes;
15
import java.text.MessageFormat;
16
import java.util.ArrayList;
17
import java.util.Arrays;
18
import java.util.Collections;
19
import java.util.Comparator;
20
import java.util.EnumSet;
21
import java.util.List;
22
import java.util.function.Predicate;
23
import java.util.logging.Level;
24
import javax.swing.JOptionPane;
25
import javax.swing.SwingUtilities;
26
import org.apache.commons.collections4.CollectionUtils;
27
import org.apache.commons.io.FileUtils;
28
import org.apache.commons.io.FilenameUtils;
29
import org.apache.commons.io.IOCase;
30
import org.apache.commons.lang3.BooleanUtils;
31
import org.apache.commons.lang3.StringUtils;
32
import org.gvsig.andami.PluginServices;
33
import org.gvsig.andami.PluginsLocator;
34
import org.gvsig.andami.PluginsManager;
35
import org.gvsig.expressionevaluator.Code;
36
import org.gvsig.expressionevaluator.ExpressionUtils;
37
import org.gvsig.scripting.DataFolderFound;
38
import org.gvsig.scripting.ScriptingBaseScript;
39
import org.gvsig.scripting.ScriptingFolder;
40
import org.gvsig.scripting.ScriptingLocator;
41
import org.gvsig.scripting.ScriptingManager;
42
import org.gvsig.scripting.ScriptingScript;
43
import org.gvsig.scripting.ScriptingUnit;
44
import org.gvsig.scripting.app.extension.messagewait.MessageWait;
45
import org.gvsig.scripting.swing.api.JScriptingComposer;
46
import org.gvsig.scripting.swing.api.ScriptingSwingLocator;
47
import org.gvsig.scripting.swing.api.ScriptingUIManager;
48
import static org.gvsig.scripting.swing.api.ScriptingUIManager.SCRIPT_COMPOSER_AUTORUN;
49
import org.gvsig.tools.ToolsLocator;
50
import org.gvsig.tools.dynobject.DynObject;
51
import org.gvsig.tools.exception.BaseException;
52
import org.gvsig.tools.i18n.I18nManager;
53
import org.gvsig.tools.packageutils.PackageManager;
54
import org.gvsig.tools.packageutils.Version;
55
import org.gvsig.tools.swing.api.ToolsSwingLocator;
56
import org.gvsig.tools.swing.api.threadsafedialogs.ThreadSafeDialogsManager;
57
import org.gvsig.tools.swing.api.windowmanager.Dialog;
58
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
59
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
60
import org.gvsig.tools.swing.impl.windowmanager.DefaultWindowManager;
61
import org.gvsig.tools.task.SimpleTaskStatus;
62
import org.gvsig.tools.visitor.VisitCanceledException;
63
import org.gvsig.tools.visitor.Visitor;
64
import org.slf4j.Logger;
65
import org.slf4j.LoggerFactory;
66
import org.gvsig.tools.util.FolderSet;
67
import org.gvsig.tools.util.impl.DefaultFolderSet;
68
/**
69
 *
70
 * @author jjdelcerro
71
 */
72
@SuppressWarnings("UseSpecificCatch")
73
public class ScriptingUtils {
74
    
75
    public static final String SKIP_AUTORUNS = "skipAutoruns";
76
    
77
    private static final Logger LOGGER = LoggerFactory.getLogger(ScriptingExtension.class);
78

  
79
    private boolean executingAutorunScripts = false;
80
    private static boolean composer_initialized = false;
81
    private final MessageWait message;
82

  
83
    /*
84
     * la funcion log y las constantes estan pensadas para usarlas desde los scripts.
85
     */
86
    public static final int INFO = 0;
87
    public static final int TRACE = 1;
88
    public static final int WARN = 2;
89
    public static final int ERROR = 3;
90

  
91
    public static void log(String message) {
92
        log(INFO, message, null);
93
    }
94

  
95
    public static void log(int level, String message) {
96
        log(level, message, null);
97
    }
98

  
99
    public static void log(int level, String message, Throwable th) {
100
        switch( level ) {
101
        case TRACE:
102
            LOGGER.trace(message, th);
103
            break;
104
        case ERROR:
105
            LOGGER.error(message, th);
106
            break;
107
        case WARN:
108
            LOGGER.warn(message, th);
109
            break;
110
        default:
111
        case INFO:
112
            LOGGER.info(message, th);
113
            break;
114
        }
115
    }
116
    private String appversion;
117
    private File pluginHomeFolder;
118

  
119
    public ScriptingUtils() {
120
        message = new MessageWait();
121
    }
122
    
123
    public static File getScriptsHomeFolder(File pluginHomeFolder, String appversion) {
124
        File scriptsHomeFolder;
125
        File f = FileUtils.getFile(pluginHomeFolder, "scripts-folder.txt");
126
        if( f.exists() ) {
127
            try {
128
                List<String> lines = FileUtils.readLines(f);
129
                for( String line : lines ) {
130
                    line = line.trim();
131
                    if( !line.startsWith("#") ) {
132
                        scriptsHomeFolder = new File(line);
133
                        if( !scriptsHomeFolder.isAbsolute() ) {
134
                            scriptsHomeFolder = new File(pluginHomeFolder, line);
135
                        }
136
                        scriptsHomeFolder = new File(
137
                            FilenameUtils.normalizeNoEndSeparator(
138
                                scriptsHomeFolder.getAbsolutePath(),
139
                                true
140
                            )
141
                        );
142
                        if( scriptsHomeFolder.exists() ) {
143
                            return scriptsHomeFolder;
144
                        }
145
                    }
146
                }
147
            } catch (IOException ex) {
148
            }
149
        } else {
150
            try {
151
                FileUtils.touch(f);
152
            } catch (IOException ex) {
153
            }
154
        }
155
        scriptsHomeFolder = FileUtils.getFile(pluginHomeFolder, appversion) ;
156
        return scriptsHomeFolder;
157
    }
158
    
159
    public void initializaPaths(List<File> pluginsFolder, File installFolder, File pluginHoneFolder, String appversion) {
160

  
161
        this.appversion = appversion;
162
        this.pluginHomeFolder = pluginHoneFolder;
163
        ScriptingManager manager = ScriptingLocator.getManager();
164
        manager.setHomeFolder(getScriptsHomeFolder(pluginHoneFolder, appversion));
165

  
166
        ScriptingFolder folder = manager.createLink(
167
            "Common",
168
            manager.getUserFolder(), 
169
            "../../scripts"
170
        );
171
        folder.setProperty(ScriptingUtils.SKIP_AUTORUNS, BooleanUtils.toStringTrueFalse(true));
172
        folder.save();
173
//        manager.createLink(
174
//            "Previous version",
175
//            manager.getUserFolder(), 
176
//            "../../../org.gvsig.scripting.app.extension/scripts"
177
//        );
178

  
179
        List<File> pluginsFolders = new ArrayList<>();
180
        for( File f : pluginsFolder ) {
181
            pluginsFolders.addAll(Arrays.asList(f.listFiles()));
182
        }
183

  
184
        for( File pluginFolder : pluginsFolders ) {
185
            File scriptsFolder = new File(pluginFolder, "scripting/scripts");
186
            if( scriptsFolder.exists() ) {
187
                manager.registerSystemFolder(pluginFolder.getName(), scriptsFolder);
188
            }
189
            File libFolder = new File(pluginFolder, "scripting/lib");
190
            if( libFolder.exists() ) {
191
                manager.addLibFolder(libFolder);
192
            }
193
        }
194
        manager.setPackagesFolder(installFolder);
195

  
196
        File localAddonRepositoryFolder = new File(manager.getRootUserFolder(), "addons");
197
        if( !localAddonRepositoryFolder.exists() ) {
198
            try {
199
                FileUtils.forceMkdir(localAddonRepositoryFolder);
200
            } catch (IOException ex) {
201
                LOGGER.info("Can't create addons folder in '" + localAddonRepositoryFolder.getAbsolutePath() + "'.", ex);
202
            }
203
        }
204
        File initAddonFile = new File(localAddonRepositoryFolder, "__init__.py");
205
        if( !initAddonFile.exists() ) {
206
            try {
207
                FileUtils.touch(initAddonFile);
208
            } catch (IOException ex) {
209
                LOGGER.info("Can't create addons __init__ file in '" + localAddonRepositoryFolder.getAbsolutePath() + "'.", ex);
210
            }
211
        }
212
    }
213
    
214
    
215
    public void runScript(String name, Object[] args) {
216
        if( StringUtils.isBlank(name) ) {
217
            return;
218
        }
219
        String method = null;
220
        if( name.contains(".") ) {
221
            String[] ss = StringUtils.split(name, '.');
222
            name = ss[0];
223
            if( StringUtils.isAlphanumeric(ss[1]) ) {
224
                method = ss[1];
225
            } else {
226
                try {
227
                    Code.Callable code = (Code.Callable) ExpressionUtils.compile(ss[1]);
228
                    method = code.name();
229
                    try {
230
                        code.link();
231
                        List<Object> args2 = new ArrayList<>();
232
                        for (Code param : code.parameters()) {
233
                            args2.add(((Code.Constant)param).value());
234
                        }
235
                        if( !CollectionUtils.isEmpty(args2) ) {
236
                            args = args2.toArray(new Object[args2.size()]);
237
                        }
238
                    } catch(Throwable t) {
239
                        LOGGER.warn("Can't process command args ("+name+").",t);
240
                    }
241
                } catch(Throwable t) {
242
                    LOGGER.warn("Can't process command ("+name+").",t);
243
                    method = StringUtils.left(ss[1], indexOfNonAlphanumeric(ss[1])+1);
244
                }
245
            }
246
        }
247
        ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
248
        ScriptingUIManager uimanager = ScriptingSwingLocator.getUIManager();
249
        ScriptingBaseScript script = uimanager.getManager().getScript(name);
250
        if( script != null ) {
251
            if( StringUtils.isNotBlank(method) && script instanceof ScriptingScript ) {
252
                try {
253
                    ((ScriptingScript)script).invokeFunction(method, args);
254
                } catch (NoSuchMethodException ex) {
255
                    LOGGER.warn("Can't call method '"+method+"' of script '"+name+"'.", ex);
256
                    dialogs.messageDialog(
257
                            "Can't call method '"+method+"' of script '"+name+"'.", 
258
                            "ScriptLaunch", 
259
                            JOptionPane.OK_OPTION
260
                    );
261
                }
262
            } else {
263
                script.run(args);
264
            }
265
        } else {
266
            dialogs.messageDialog(
267
                    "Can't locate script '" + name + "'.", 
268
                    "ScriptLaunch", 
269
                    JOptionPane.OK_OPTION
270
            );
271
        }
272
    }
273
    
274
    public void runLauncher() {
275
        ScriptingUIManager uimanager = ScriptingSwingLocator.getUIManager();
276
        WindowManager winmanager = ToolsSwingLocator.getWindowManager();        
277
        winmanager.showWindow(uimanager.createLauncher().asJComponent(), uimanager.getTranslation("Scripting_Launcher"), WindowManager.MODE.TOOL);        
278
    }
279
    
280
    public void runComposer() {
281
        PluginsManager pluginsManager = PluginsLocator.getPluginsManager();
282
        PluginServices plugin = pluginsManager.getPlugin(ScriptingExtension.class);
283
        if( plugin!=null ) {
284
            DynObject preferences = plugin.getPluginProperties();
285
            if( preferences!=null ) {
286
                Boolean composerUseHisWindowManager = (Boolean) preferences.getDynValue("ComposerUseHisWindowManager");
287
                if( composerUseHisWindowManager!=null && composerUseHisWindowManager ) {
288
                    DefaultWindowManager winmanager = new DefaultWindowManager();
289
                    ScriptingUIManager uimanager = ScriptingSwingLocator.getUIManager();
290
                    uimanager.setWindowManager(winmanager);
291
                }
292
            }
293
        }
294

  
295
        I18nManager i18n = ToolsLocator.getI18nManager();
296
        message.showMessage(
297
                i18n.getTranslation("_notice"),
298
                i18n.getTranslation("_Initializing_the_scripting_plugin_Xhorizontal_ellipsisX") + "\n"
299
                + i18n.getTranslation("_Waiting_to_terminate"),
300
                new MessageWait.WaitingCondition() {
301
            private Thread th = null;
302

  
303
            @Override
304
            public boolean stopWaiting() {
305
                if (executingAutorunScripts) {
306
                    return false;
307
                }
308
                if (composer_initialized) {
309
                    return true;
310
                }
311
                if (th == null) {
312
                    th = new Thread(new ExecuteScriptsFromScriptingFolders(null, "scautorun", SCRIPT_COMPOSER_AUTORUN), "StartupScriptingComposer");
313
                    th.start();
314
                }
315
                return false;
316
            }
317
        },
318
                new Runnable() {
319
            @Override
320
            public void run() {
321
                showScriptingComposer();
322
            }
323
        }
324
        );
325

  
326
    }
327
    
328
    public Runnable getAutorunScriptsOnStartup(List<File> pluginsFolders) {
329
        return new ExecuteAutorunScriptsOnStartup(pluginsFolders);
330
    }
331
    
332
    private void showScriptingComposer() {
333
        ScriptingUIManager uimanager = ScriptingSwingLocator.getUIManager();
334
        JScriptingComposer composer = uimanager.createComposer();
335
        uimanager.showWindow(
336
            composer.asJComponent(),
337
            uimanager.getTranslation("Scripting_Composer")
338
        );
339
    }
340

  
341
    private class ExecuteScriptsFromScriptingFolders extends AbstractExecuteScripts {
342
        
343
        public ExecuteScriptsFromScriptingFolders(List<File> pluginsFolders, String title, String patternName) {
344
            super(pluginsFolders, title, patternName);
345
        }
346
        
347
        @Override
348
        public void run() {            
349
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
350
            SimpleTaskStatus status = ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus("Scripts startup");
351
            status.setIndeterminate();
352
            status.setAutoremove(true);
353
            status.add();
354
            final I18nManager i18nManager = ToolsLocator.getI18nManager();            
355
            try {
356
                LOGGER.info("Searching "+title+" scripts...");
357
                dialogs.message(
358
                    i18nManager.getTranslation("_Searching_autorun_scripts_Xhorizontal_ellipsisX"),
359
                    JOptionPane.INFORMATION_MESSAGE
360
                );
361
                ScriptingManager manager = ScriptingLocator.getManager();
362
                final List<ScriptingScript> scripts = new ArrayList<>();
363
                
364
                Visitor visitor = new Visitor() {
365
                    @Override
366
                    public void visit(Object o) throws VisitCanceledException, BaseException {
367
                        ScriptingUnit unit = (ScriptingUnit) o;
368
                        if( unit instanceof ScriptingScript && 
369
                            FilenameUtils.wildcardMatch(unit.getName(), patternName, IOCase.INSENSITIVE) ) {
370
                            ScriptingScript script = (ScriptingScript) unit;
371
                            if( script.isEnabled() ) {
372
                                scripts.add(script);
373
                            } else {
374
                                LOGGER.info("Skip "+title+" script '" + script.getFile().getAbsolutePath() + "'.");
375
                            }
376
                        }
377
                    }
378
                };
379
                Predicate<ScriptingUnit> includeFilter = new Predicate<ScriptingUnit>() {
380
                    @Override
381
                    public boolean test(ScriptingUnit unit) {
382
                        if( unit instanceof ScriptingFolder ) {
383
                            return !BooleanUtils.toBoolean(unit.getProperty(SKIP_AUTORUNS));
384
                        }
385
                        return false;
386
                    }
387
                };
388
                manager.getSystemFolder().accept(visitor, includeFilter);
389
                manager.getUserFolder().accept(visitor, includeFilter);
390
                sortScripts(scripts);
391
                executeScripts(scripts, status);
392
            } catch(Throwable th) {
393
                
394
            } finally {
395
                composer_initialized = true;
396
                LOGGER.info("Running "+title+" scripts terminated.");
397
                dialogs.message("", JOptionPane.INFORMATION_MESSAGE);
398
                status.terminate();
399
            }
400
        }
401
    }
402

  
403
    public class ExecuteAutorunScriptsOnStartup implements Runnable {
404

  
405
        private final List<File> pluginsFolders;
406

  
407
        public ExecuteAutorunScriptsOnStartup(List<File> pluginsFolders) {
408
            this.pluginsFolders = pluginsFolders;
409
        }
410
        
411
        @Override
412
        public void run() {
413
            try {
414
                Runnable process = new ExecuteScriptsFromFilesystem(
415
                        this.pluginsFolders,
416
                        "autorun", 
417
                        "autorun.inf"
418
                );
419
                process.run();
420
            } catch(Throwable t) {
421
                LOGGER.error("Problems runing autorun scripts",t);
422
                I18nManager i18n = ToolsLocator.getI18nManager();
423
                ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
424
                dialogs.messageDialog(
425
                        i18n.getTranslation("_There_was_a_problem_starting_the_application_It_is_convenient_that_you_close_it_and_start_it_again"), 
426
                        "gvSIG desktop", 
427
                        JOptionPane.ERROR_MESSAGE
428
                );
429
            }
430
        }
431
    }
432

  
433
    private abstract class AbstractExecuteScripts implements Runnable {
434

  
435
        protected String patternName;
436
        protected String title;
437
        private final List<File> pluginsFolders;
438

  
439
        public AbstractExecuteScripts(List<File> pluginsFolders, String title, String patternName) {
440
            if( pluginsFolders==null ) {
441
                this.pluginsFolders = Collections.EMPTY_LIST;
442
            } else {
443
                this.pluginsFolders = pluginsFolders;
444
            }
445
            this.patternName = patternName;
446
            this.title = title;
447
        }
448
        
449
        protected List<File> getPluginsFolders() {
450
            return this.pluginsFolders;
451
        }
452
        
453
        private String getScriptOrderKey(ScriptingBaseScript o) {
454
            int groupOrder = 500;
455
            String groupName = "default";
456
            int scriptOrder = 500;
457
            String s = o.getProperty("autorun.group.order");
458
            if (s != null) {
459
                try {
460
                    groupOrder = Integer.parseInt(s);
461
                } catch (Exception ex) {
462
                    // Do nothing.
463
                }
464
            }
465
            s = o.getProperty("autorun.group.name");
466
            if (s != null) {
467
                groupName = s;
468
            }
469
            s = o.getProperty("autorun.order");
470
            if (s != null) {
471
                try {
472
                    scriptOrder = Integer.parseInt(s);
473
                } catch (Exception ex) {
474
                    // Do nothing.
475
                }
476
            }
477
            String key = MessageFormat.format(
478
                    "{0,number,000000}.{1}.{2,number,000000}",
479
                    groupOrder,
480
                    groupName,
481
                    scriptOrder
482
            );
483
            return key;
484
        }
485

  
486
        protected void sortScripts(List<ScriptingScript> scripts) {
487
            Collections.sort(scripts, new Comparator<ScriptingBaseScript>() {
488

  
489
                @Override
490
                public int compare(ScriptingBaseScript o1, ScriptingBaseScript o2) {
491
                    return getScriptOrderKey(o1).compareToIgnoreCase(getScriptOrderKey(o2));
492
                }
493
            });
494
        }
495

  
496
        protected void executeScripts(List<ScriptingScript> scripts, SimpleTaskStatus status) {
497
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
498
            final I18nManager i18nManager = ToolsLocator.getI18nManager();
499
            if (scripts != null && !scripts.isEmpty()) {
500
                LOGGER.info("Scripts to run:");
501
                for (ScriptingBaseScript script : scripts) {
502
                    try {
503
                        LOGGER.info(StringUtils.abbreviateMiddle(script.getFile().getParent(),"...",50) + " (" + getScriptOrderKey(script) + ", " + script.getIsolationGroup() + ")");
504
                    } catch(Throwable t) {
505
                        LOGGER.info("...Error...");
506
                    }
507
                }                
508
                if (status != null) {
509
                    status.setRangeOfValues(0, scripts.size());
510
                }
511
                int n = 0;
512
                for (ScriptingBaseScript script : scripts) {
513
                    if (status != null) {
514
                        status.setCurValue(n++);
515
                    }
516
                    try {
517
                        if( StringUtils.equals("autorun", title) ) {
518
                            LOGGER.info("running '" + script.getFile().getParent() + "'.");
519
                        } else {
520
                            LOGGER.info("running " + title + " '" + script.getFile().getAbsolutePath() + "'.");
521
                        }
522
                        dialogs.message(
523
                                i18nManager.getTranslation(
524
                                        "_Starting_XnameX",
525
                                        new String[]{
526
                                            script.getFile().getParentFile().getName()}
527
                                ),
528
                                JOptionPane.INFORMATION_MESSAGE
529
                        );
530
                    } catch (Exception ex) {
531
                        // Ignore it
532
                    }
533
                    try {
534
                        // Hacemos un reload por si un sript deshabilito a otro.
535
                        script.reload();
536
                        if( script.isEnabled() ) {
537
                            script.run();
538
                        } else {
539
                            LOGGER.info("Skip " + title + " script '" + script.getFile().getAbsolutePath() + "' (" + getScriptOrderKey(script) + ", " + script.getIsolationGroup() + ").");
540
                        }
541
                    } catch (Exception ex) {
542
                        LOGGER.warn("Can't execute " + title + " from '" + script.getFile().getAbsolutePath() + "'.", ex);
543
                    }
544
                }
545
            }
546

  
547
        }
548
    }
549

  
550
    private class ExecuteScriptsFromFilesystem extends AbstractExecuteScripts {
551

  
552
        public ExecuteScriptsFromFilesystem(List<File> pluginsFolder, String title, String patternName) {
553
            super(pluginsFolder, title, patternName);
554
        }
555

  
556
        @Override
557
        public void run() {
558
            ThreadSafeDialogsManager dialogs = ToolsSwingLocator.getThreadSafeDialogsManager();
559
            executingAutorunScripts = true;
560
            try {
561
                final ScriptingManager manager = ScriptingLocator.getManager();
562
                manager.loadEngines();
563

  
564
//                final PluginsManager pluginManager = PluginsLocator.getManager();
565
                final I18nManager i18nManager = ToolsLocator.getI18nManager();
566

  
567
                final List<ScriptingScript> scripts = new ArrayList<>();
568

  
569
                List<File> pluginsFolders = new ArrayList<>();
570
                for (File pluginsFolders2 : this.getPluginsFolders()) {
571
                    for (File pluginFolder : pluginsFolders2.listFiles()) {
572
                        File f = FileUtils.getFile(pluginFolder, "scripting", "scripts");
573
                        if (f.exists()) {
574
                            pluginsFolders.add(f);
575
                        }
576
                    }
577
                }
578

  
579
                dialogs.message(
580
                        i18nManager.getTranslation("_Searching_autorun_scripts_Xhorizontal_ellipsisX"),
581
                        JOptionPane.INFORMATION_MESSAGE
582
                );
583

  
584
                SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
585
                    @Override
586
                    public FileVisitResult visitFile(Path path, BasicFileAttributes bfa) throws IOException {
587
                        File file = path.toFile();
588
                        if (FilenameUtils.wildcardMatch(file.getName(), patternName, IOCase.INSENSITIVE)) {
589
                            if (file.exists()) {
590
                                ScriptingScript script = (ScriptingScript) manager.getScript(file);
591
                                if (script.isEnabled()) {
592
                                    scripts.add(script);
593
                                } else {
594
                                    LOGGER.info("Skip " + title + " script '" + file.getAbsolutePath() + "'.");
595
                                }
596
                            }
597
                        }
598
                        return FileVisitResult.CONTINUE;
599
                    }
600
                };
601
                try {
602
                    EnumSet<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
603
                    for (File pluginFolder : pluginsFolders) {
604
                        Files.walkFileTree(Paths.get(pluginFolder.toURI()), opts, Integer.MAX_VALUE, visitor);
605
                    }
606
                    Files.walkFileTree(Paths.get(manager.getRootUserFolder().toURI()), opts, Integer.MAX_VALUE, visitor);
607
                    List<ScriptingFolder> folders = manager.getAlternativeUserFolders();
608
                    for (ScriptingFolder folder : folders) {
609
                        Files.walkFileTree(Paths.get(folder.getFile().toURI()), opts, Integer.MAX_VALUE, visitor);
610
                    }
611
                } catch (Exception ex) {
612
                    LOGGER.warn("Can't execute " + title + " in home.", ex);
613
                }
614
                sortScripts(scripts);
615
                executeScripts(scripts, null);
616

  
617
            } finally {
618
                LOGGER.info("Running " + title + " scripts terminated.");
619
                dialogs.message("", JOptionPane.INFORMATION_MESSAGE);
620
                executingAutorunScripts = false;
621
            }
622
            checkDataFoldersVersions();
623
        }
624

  
625
    }
626
    
627
    private void checkDataFoldersVersions() {
628
        final ScriptingManager manager = ScriptingLocator.getManager();
629
        PackageManager versionFactory = ToolsLocator.getPackageManager();
630
        Version currentVersion = versionFactory.createVersion(this.appversion);
631
        FolderSet folders = new DefaultFolderSet();
632
        folders.add(this.pluginHomeFolder);
633
        final List<DataFolderFound> dataFoldersFound = manager.searchOldVersions(currentVersion, folders);
634
        if( dataFoldersFound == null || dataFoldersFound.isEmpty() ) {
635
            return;
636
        }
637
        Runnable askUser = new Runnable() {
638
            @Override
639
            public void run() {
640
                WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
641
                final DataFoldersRecoverPanel panel = new DataFoldersRecoverPanel(dataFoldersFound);
642
                final Dialog dialog = winManager.createDialog(
643
                        panel,
644
                        "Recuperacion de preferencias",
645
                        null,
646
                        WindowManager_v2.BUTTONS_OK_CANCEL
647
                );
648
                dialog.addActionListener(new ActionListener() {
649
                    @Override
650
                    public void actionPerformed(ActionEvent e) {
651
                        if (dialog.getAction() == WindowManager_v2.BUTTON_OK) {
652
                            List<DataFolderFound> toRestore = panel.getSelectedDataFolders();
653
                            for (DataFolderFound dataFolderFound : dataFoldersFound) {
654
                                if (toRestore.contains(dataFolderFound)) {
655
                                    dataFolderFound.restore();
656
                                } else {
657
                                    dataFolderFound.leave();
658
                                }
659
                            }
660
                        }
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff