Revision 8668

View differences:

org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/java/org/gvsig/raster/tools/LayerDatatypeSextanteAlgorithm.java
1
package org.gvsig.raster.tools;
2

  
3
import java.util.HashMap;
4
import java.util.List;
5

  
6
import org.gvsig.fmap.dal.coverage.RasterLocator;
7
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
8
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
9
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
10
import org.gvsig.geoprocess.lib.sextante.AbstractSextanteGeoProcess;
11
import org.gvsig.geoprocess.lib.sextante.dataObjects.FLyrRasterIRasterLayer;
12
import org.gvsig.raster.algorithm.RasterBaseAlgorithmLibrary;
13
import org.gvsig.raster.algorithm.process.DataProcess;
14
import org.gvsig.raster.algorithm.process.IProcessActions;
15
import org.gvsig.raster.algorithm.process.ProcessException;
16
import org.gvsig.raster.fmap.layers.FLyrRaster;
17

  
18
import es.unex.sextante.core.AnalysisExtent;
19
import es.unex.sextante.core.Sextante;
20
import es.unex.sextante.dataObjects.IRasterLayer;
21
import es.unex.sextante.exceptions.GeoAlgorithmExecutionException;
22
import es.unex.sextante.exceptions.NullParameterAdditionalInfoException;
23
import es.unex.sextante.exceptions.NullParameterValueException;
24
import es.unex.sextante.exceptions.RepeatedParameterNameException;
25
import es.unex.sextante.exceptions.WrongParameterIDException;
26
import es.unex.sextante.exceptions.WrongParameterTypeException;
27

  
28
/**
29
 * Process to change a layer of data type
30
 * @author Nacho Brodin (nachobrodin@gmail.com)
31
 */
32
public class LayerDatatypeSextanteAlgorithm extends AbstractSextanteGeoProcess implements IProcessActions {
33
    public static final String RESULT            = "RESULT";
34
    public static final String LAYER             = "RasterStore1";
35
	public static final String DATATYPE          = "Datatype";
36
	public static final String ADJUST_DEC2INT    = "AdjustDec2Int";
37
	public static final String ADJUST_BIG2SMALL  = "AdjustBig2Small";
38

  
39
	public static String[]    DEC2INT_OPTIONS    = new String[]{"Trunk", "Round", "Ceil", "Floor"};
40
	public static String[]    BIG2SMALL_OPTIONS  = new String[]{"Trunk", "Maxvalue", "NoData"};
41
	public static String[]    DATATYPES          = new String[]{"Byte", "UShort", "Short", "Integer", "Float", "Double"};
42

  
43
    private DataProcess        task            = null;
44

  
45

  
46
    public void defineCharacteristics() {
47
        setName(getTranslation("layer_datatype"));
48
        setGroup(getTranslation("raster_layer"));
49

  
50
        try {
51
            m_Parameters.addInputRasterLayer(LAYER, getTranslation("Input_layer"), true);
52
            m_Parameters.addSelection(DATATYPE, getTranslation("dst_datatype"), DATATYPES);
53
            m_Parameters.addSelection(ADJUST_DEC2INT, getTranslation("dec_2_int"), DEC2INT_OPTIONS);
54
            m_Parameters.addSelection(ADJUST_BIG2SMALL, getTranslation("big_2_small"), BIG2SMALL_OPTIONS);
55
        } catch (RepeatedParameterNameException e) {
56
            Sextante.addErrorToLog(e);
57
        }
58
        addOutputRasterLayer(RESULT, getTranslation("principalcomponents"));
59
    }
60

  
61
    public boolean processAlgorithm() throws GeoAlgorithmExecutionException {
62

  
63
    	if(existsOutPutFile(LayerDatatypeSextanteAlgorithm.RESULT, 0)) {
64
    		throw new GeoAlgorithmExecutionException(getTranslation("file_exists"));
65
    	}
66

  
67
    	IRasterLayer input = m_Parameters.getParameterValueAsRasterLayer(LAYER);
68

  
69
    	FLyrRaster lyrRaster = ((FLyrRaster)input.getBaseDataObject());
70
    	IRasterLayer output = null;
71

  
72
    	output = getNewRORasterLayer(
73
    			RESULT,
74
    			Sextante.getText("layerdatatype_description"),
75
    			input.getDataType(),
76
    			input.getBandsCount());
77

  
78
    	String fileName = ((FLyrRasterIRasterLayer)output).getName();
79

  
80
    	try {
81
    		setProgressText(getTranslation("convert_datatype"));
82
			task = createLayerDatatypeProcess(lyrRaster.getDataStore(), fileName);
83
			task.execute();
84
			HashMap<String, Object> params = task.getResult();
85
			fileName = (String)params.get("FileName");
86

  
87
			((FLyrRasterIRasterLayer)output).setBaseDataObject(fileName);
88
		} catch (ProcessInterruptedException e) {
89
			Sextante.addErrorToLog(e);
90
		} catch (ProcessException e) {
91
			Sextante.addErrorToLog(e);
92
		}
93

  
94
		if(getTaskMonitor().isCanceled())
95
			return false;
96

  
97
        return true;
98
    }
99

  
100
    /**
101
     * Creates a process to calculate statistics
102
     * @param inputStore
103
     * @return
104
     * @throws ProcessException
105
     * @throws NullParameterAdditionalInfoException
106
     * @throws NullParameterValueException
107
     * @throws WrongParameterIDException
108
     * @throws WrongParameterTypeException
109
     */
110
    private DataProcess createLayerDatatypeProcess(RasterDataStore inputStore, String fileName) throws ProcessException, WrongParameterTypeException, WrongParameterIDException, NullParameterValueException, NullParameterAdditionalInfoException {
111
    	DataProcess taskStats = RasterBaseAlgorithmLibrary.getManager().createRasterTask("LayerDatatypeProcess");
112
    	taskStats.setActions(this);
113
    	List<String> params = taskStats.getRasterTaskInputParameters("LayerDatatypeProcess");
114
    	for (int i = 0; i < params.size(); i++) {
115
    		String paramName = params.get(i);
116
    		Class<?> paramType = taskStats.getParameterTypeByProcess("LayerDatatypeProcess", paramName);
117
    		if(paramType == RasterDataStore.class) {
118
    			taskStats.addParam(paramName, (RasterDataStore)inputStore);
119
    		}
120

  
121
    		if(paramName.equals("Path")) {
122
    			taskStats.addParam(paramName, fileName);
123
    		}
124

  
125
    		if(paramName.equals(DATATYPE)) {
126
    			String value = m_Parameters.getParameterValueAsString(DATATYPE);
127
    			int position = 0;
128
    			for (int j = 0; j < DATATYPES.length; j++) {
129
					if(DATATYPES[j].equals(value))
130
						position = j;
131
				}
132
    			taskStats.addParam(paramName, position);
133
    		}
134

  
135
    		if(paramName.equals(ADJUST_DEC2INT)) {
136
    			String value = m_Parameters.getParameterValueAsString(ADJUST_DEC2INT);
137
    			int position = 0;
138
    			for (int j = 0; j < DEC2INT_OPTIONS.length; j++) {
139
					if(DEC2INT_OPTIONS[j].equals(value))
140
						position = j;
141
				}
142
    			taskStats.addParam(paramName, position);
143
    		}
144

  
145
    		if(paramName.equals(ADJUST_BIG2SMALL)) {
146
    			String value = m_Parameters.getParameterValueAsString(ADJUST_BIG2SMALL);
147
    			int position = 0;
148
    			for (int j = 0; j < BIG2SMALL_OPTIONS.length; j++) {
149
					if(BIG2SMALL_OPTIONS[j].equals(value))
150
						position = j;
151
				}
152
    			taskStats.addParam(paramName, position);
153
    		}
154

  
155
    		if(paramName.equals("WINDOW")) {
156
    			AnalysisExtent ext = getAnalysisExtent();
157
    			Extent bbox = RasterLocator.getManager().getDataStructFactory().createExtent(
158
    					ext.getXMin(), ext.getYMax(), ext.getXMax(), ext.getYMin());
159
    			Extent inputBbox = inputStore.getExtent();
160
    			if(bbox.getULX() != inputBbox.getULX() ||
161
    				bbox.getULY() != inputBbox.getULY() ||
162
    				bbox.getLRX() != inputBbox.getLRX() ||
163
    				bbox.getLRY() != inputBbox.getLRY()) {
164
    				taskStats.addParam(paramName, bbox);
165
    			}
166
    		}
167
    	}
168
    	return taskStats;
169
    }
170

  
171
	public void interrupted() {
172

  
173
	}
174

  
175
	public void end(Object param) {
176

  
177
	}
178

  
179
	public void updateProgress(int current, int total) {
180
		boolean cancelled = setProgress(current, total);
181

  
182
		if(!cancelled) {
183
			if(task != null)
184
				task.actionCanceled(null);
185
		}
186
	}
187

  
188
    /*
189
     * TODO: Customized panels
190
    @Override
191
    public Class<? extends GeoAlgorithmParametersPanel> getCustomParametersPanelClass() {
192
        return PrincipalComponentsParametersPanel.class;
193
    }*/
194
}
0 195

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/java/org/gvsig/raster/tools/RasterToolsSextanteLibrary.java
1
package org.gvsig.raster.tools;
2

  
3
import org.gvsig.geoprocess.algorithm.base.core.AlgorithmAbstractLibrary;
4
import org.gvsig.i18n.Messages;
5
import org.gvsig.tools.library.LibraryException;
6

  
7
/**
8
 * Initialization of <code>RasterToolsSextanteLibrary</code> library.
9
 */
10
public class RasterToolsSextanteLibrary extends AlgorithmAbstractLibrary {
11

  
12
    @Override
13
    protected void doInitialize() throws LibraryException {
14
        // Nothing to do
15
    }
16

  
17
    @Override
18
    protected void doPostInitialize() throws LibraryException {
19
        Messages.addResourceFamily(
20
            "org.gvsig.raster.tools.sextante.i18n.text", RasterToolsSextanteLibrary.class
21
                .getClassLoader(), RasterToolsSextanteLibrary.class.getClass().getName());
22
        
23
        registerGeoProcess(new LayerDatatypeSextanteAlgorithm());
24
    }
25

  
26
}
0 27

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/resources/org/gvsig/raster/tools/sextante/i18n/text.properties
1
layer_datatype=Cambiar tipo de dato
2
raster_layer=Capas r?ster
3
Input_layer=Capa de entrada
4
dst_datatype=Tipo de dato de destino
5
dec_2_int=De decimal a entero
6
big_2_small=De mayor a menor
7
file_exists=El fichero existe
8
convert_datatype=Convirtiendo el tipo de dato
0 9

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/resources/org/gvsig/raster/tools/sextante/i18n/text_en.properties
1
layer_datatype=Change the data type
2
raster_layer=Raster layers
3
Input_layer=Input layer
4
dst_datatype=Data type of the result
5
dec_2_int=From decimal to integer
6
big_2_small=From greater type to lesser type
7
file_exists=The file exists
8
convert_datatype=Transforming the data type
0 9

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/resources/help/LayerDatatypeSextanteAlgorithm_en.xml
1
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
2
<help>
3
	<element name="DESCRIPTION"
4
		text=""
5
		description="Descripci&#243;n" type="0">
6
		<!-- <image description="" file="">
7
		</image> -->
8
	</element>
9
	<element name="ADDITIONAL_INFO" text=""
10
		description="Informaci&#243;n adicional" type="0">
11
	</element>
12
	<element name="EXTENSION_AUTHOR" text=""
13
		description="Algoritmo creado por" type="0">
14
	</element>
15
	<element name="HELP_AUTHOR" text="" description="Ayuda creada por"
16
		type="0">
17
	</element>
18
	<element name="USER_NOTES" text="" description="Notas de usuario"
19
		type="0">
20
	</element>
21
</help>
0 22

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/resources/help/LayerDatatypeSextanteAlgorithm.xml
1
<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
2
<help>
3
	<element name="DESCRIPTION"
4
		text=""
5
		description="Descripci&#243;n" type="0">
6
		<!-- <image description="" file="">
7
		</image>-->
8
	</element>
9
	<element name="ADDITIONAL_INFO" text=""
10
		description="Informaci&#243;n adicional" type="0">
11
	</element>
12
	<element name="EXTENSION_AUTHOR" text=""
13
		description="Algoritmo creado por" type="0">
14
	</element>
15
	<element name="HELP_AUTHOR" text="" description="Ayuda creada por"
16
		type="0">
17
	</element>
18
	<element name="USER_NOTES" text="" description="Notas de usuario"
19
		type="0">
20
	</element>
21
</help>
0 22

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.raster.tools.RasterToolsSextanteLibrary
0 2

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.toolbox.algorithm/pom.xml
1
<?xml version="1.0" encoding="ISO-8859-1"?>
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/xsd/maven-4.0.0.xsd">
3

  
4
	<modelVersion>4.0.0</modelVersion>
5
	<artifactId>org.gvsig.raster.tools.toolbox.algorithm</artifactId>
6
	<packaging>jar</packaging>
7
	<name>org.gvsig.raster.tools.toolbox.algorithm</name>
8
	<parent>
9
		<groupId>org.gvsig</groupId>
10
		<artifactId>org.gvsig.raster.tools</artifactId>
11
		<version>2.2.68</version>
12
	</parent>
13
	<dependencies>
14
		<dependency>
15
		    <groupId>org.gvsig</groupId>
16
   			<artifactId>org.gvsig.raster.tools.algorithm.layerdatatype</artifactId>
17
            <scope>runtime</scope>
18
   		</dependency>
19
		<dependency>
20
		    <groupId>org.gvsig</groupId>
21
   			<artifactId>org.gvsig.raster.algorithm</artifactId>
22
            <scope>compile</scope>
23
   		</dependency>
24
		<dependency>
25
		    <groupId>org.gvsig</groupId>
26
   			<artifactId>org.gvsig.geoprocess.algorithm.base</artifactId>
27
            <scope>compile</scope>
28
   		</dependency>
29
		<dependency>
30
			<groupId>org.gvsig</groupId>
31
			<artifactId>org.gvsig.geoprocess.lib.sextante</artifactId>
32
			<scope>compile</scope>
33
		</dependency>
34
		<dependency>
35
			<groupId>org.gvsig</groupId>
36
			<artifactId>org.gvsig.tools.lib</artifactId>
37
			<scope>compile</scope>
38
		</dependency>
39
		<dependency>
40
			<groupId>org.gvsig</groupId>
41
			<artifactId>org.gvsig.ui</artifactId>
42
			<scope>compile</scope>
43
		</dependency>
44
	    <dependency>
45
			<groupId>org.gvsig</groupId>
46
			<artifactId>org.gvsig.i18n</artifactId>
47
			<scope>compile</scope>
48
		</dependency>
49
		<dependency>
50
            <groupId>org.gvsig</groupId>
51
            <artifactId>org.gvsig.fmap.mapcontext.api</artifactId>
52
            <scope>compile</scope>
53
        </dependency>
54
        <dependency>
55
            <groupId>org.gvsig</groupId>
56
            <artifactId>org.gvsig.fmap.mapcontext.impl</artifactId>
57
            <scope>runtime</scope>
58
        </dependency>
59
		<dependency>
60
            <groupId>org.gvsig</groupId>
61
            <artifactId>org.gvsig.projection.api</artifactId>
62
            <scope>compile</scope>
63
        </dependency>
64
        <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.projection.cresques.impl</artifactId>
67
            <scope>runtime</scope>
68
        </dependency>
69
   		<dependency>
70
            <groupId>org.gvsig</groupId>
71
            <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
72
            <scope>compile</scope>
73
        </dependency>
74
	</dependencies>
75
</project>
0 76

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/test/java/org/gvsig/raster/app/extension/TestNoDataPanel.java
1
package org.gvsig.raster.app.extension;
2

  
3
import javax.swing.JFrame;
4

  
5
import org.gvsig.raster.tools.app.basic.tool.properties.panel.NoDataPanel;
6

  
7
public class TestNoDataPanel {
8
		private int                          w        = 510;
9
		private int                          h        = 300;
10
		private JFrame                       frame    = new JFrame();
11
		private NoDataPanel               desc     = null;
12

  
13
		public TestNoDataPanel() {
14
			desc = new NoDataPanel();
15
			frame.getContentPane().add(desc);
16
			frame.setSize(w, h);
17
			frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
18
			frame.setVisible(true);
19
		}
20

  
21
		public static void main(String[] args) {
22
			new TestNoDataPanel();
23
		}
24
	}
0 25

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/test/java/org/gvsig/raster/app/extension/TestClipPanel.java
1
package org.gvsig.raster.app.extension;
2

  
3
import javax.swing.JFrame;
4

  
5
import org.gvsig.raster.tools.app.basic.tool.clip.ui.ClippingPanel;
6
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
7

  
8
public class TestClipPanel {
9
		private int                          w        = 510;
10
		private int                          h        = 300;
11
		private JFrame                       frame    = new JFrame();
12
		private ClippingPanel               desc     = null;
13

  
14
		public TestClipPanel() {
15
			new DefaultLibrariesInitializer().fullInitialize(true);
16
			desc = new ClippingPanel(null);
17
			frame.getContentPane().add(desc);
18
			frame.setSize(w, h);
19
			frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
20
			frame.setVisible(true);
21
		}
22

  
23
		public static void main(String[] args) {
24
			new TestClipPanel();
25
		}
26
	}
0 27

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/test/resources/README.txt
1
Put into this folder the resources needed by your test classes.
2

  
3
This folder is added to the Tests classpath, so you can load any resources 
4
through the ClassLoader.
5

  
6
By default, in this folder you can find an example of log4j configuration,
7
prepared to log messages through the console, so logging works when you
8
run your tests classes.
0 9

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/test/resources/log4j.xml
1
<?xml version="1.0" encoding="ISO-8859-1" ?>
2
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
3

  
4
<!-- 
5
Log4J configuration file for unit tests execution.
6
 -->
7
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
8

  
9
	<!-- Appender configuration to show logging messages through the console -->
10
	<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
11
		<layout class="org.apache.log4j.PatternLayout">
12
			<param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p [%c{2}.%M()]\n  %m%n" />
13
		</layout>
14
	</appender>
15

  
16
	<!-- 
17
	Activate logging messages of DEBUG level of higher only for the
18
	org.gvsig.tools packages.
19
	You can put full classes names or packages instead, to configure
20
	logging for all the classes and subpackages of the package.
21
	-->
22
	<category name="org.gvsig.tools">
23
		<priority value="DEBUG" />
24
	</category>
25
	<category name="org.gvsig.raster">
26
		<priority value="DEBUG" />
27
	</category>
28

  
29
	<!-- 
30
	By default, show only logging messages of INFO level or higher, 
31
	through the previously configured CONSOLE appender. 
32
	-->
33
	<root>
34
		<priority value="INFO" />
35
		<appender-ref ref="CONSOLE" />
36
	</root>
37
</log4j:configuration>
0 38

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/main/assembly/gvsig-plugin-package.xml
1
<assembly>
2
  <id>gvsig-plugin-package</id>
3
  <formats>
4
    <format>zip</format>
5
  </formats>
6
  <baseDirectory>${project.artifactId}</baseDirectory>
7
  <includeBaseDirectory>true</includeBaseDirectory>
8
  <files>
9
    <file>
10
      <source>target/${project.artifactId}-${project.version}.jar</source>
11
      <outputDirectory>lib</outputDirectory>
12
    </file>
13
    <file>
14
      <source>target/package.info</source>
15
    </file>
16
  </files>
17

  
18
  <fileSets>
19
    <fileSet>
20
      <directory>src/main/resources-plugin</directory>
21
      <outputDirectory>.</outputDirectory>
22
    </fileSet>
23
  </fileSets>
24

  
25

  
26
  <dependencySets>
27
    <dependencySet>
28
      <useProjectArtifact>false</useProjectArtifact>
29
	  <useTransitiveDependencies>false</useTransitiveDependencies>
30
      <outputDirectory>lib</outputDirectory>
31
      <includes> 
32
				<include>org.gvsig:org.gvsig.raster.tools.app.basic:jar</include>
33
				<include>org.gvsig:org.gvsig.raster.tools.algorithm.layerdatatype:jar</include>
34
				<include>org.gvsig:org.gvsig.raster.tools.algorithm.saveraster:jar</include>
35
				<include>org.gvsig:org.gvsig.raster.tools.algorithm.swing.api:jar</include>
36
				<include>org.gvsig:org.gvsig.raster.tools.algorithm.swing.impl:jar</include>
37
				<include>org.gvsig:org.gvsig.raster.tools.toolbox.algorithm:jar</include>
38
	  </includes>
39
	</dependencySet>
40
  </dependencySets>
41
</assembly>
0 42

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/package.html
1
<?xml version="1.0" encoding="UTF-8" ?>
2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
<html xmlns="http://www.w3.org/1999/xhtml">
4
<head>
5
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
6
<title>org.gvsig.raster package documentation</title>
7
</head>
8
<body>
9

  
10
	<p>Raster gvSIG extension</p>
11
	
12
	<p>
13
	Shows Raster into gvSIG.
14
	</p>
15

  
16
</body>
17
</html>
0 18

  
org.gvsig.raster.tools/tags/org.gvsig.raster.tools-2.2.68/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/RasterToolsUtil.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.raster.tools.app.basic;
23

  
24
import java.awt.Component;
25
import java.awt.Dimension;
26
import java.awt.Point;
27
import java.awt.Window;
28
import java.io.File;
29
import java.util.ArrayList;
30
import java.util.Iterator;
31

  
32
import javax.swing.ImageIcon;
33
import javax.swing.JOptionPane;
34

  
35
import org.cresques.cts.IProjection;
36
import org.slf4j.Logger;
37
import org.slf4j.LoggerFactory;
38

  
39
import org.gvsig.andami.IconThemeHelper;
40
import org.gvsig.andami.Launcher;
41
import org.gvsig.andami.PluginServices;
42
import org.gvsig.andami.ui.mdiManager.IWindow;
43
import org.gvsig.app.ApplicationLocator;
44
import org.gvsig.app.ApplicationManager;
45
import org.gvsig.app.prepareAction.PrepareContextView_v1;
46
import org.gvsig.app.project.Project;
47
import org.gvsig.app.project.ProjectManager;
48
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
49
import org.gvsig.app.project.documents.view.toc.actions.LayerErrorsPanel;
50
import org.gvsig.fmap.dal.DALLocator;
51
import org.gvsig.fmap.dal.DataManager;
52
import org.gvsig.fmap.dal.DataStore;
53
import org.gvsig.fmap.dal.DataStoreParameters;
54
import org.gvsig.fmap.dal.DataStoreProviderFactory;
55
import org.gvsig.fmap.dal.coverage.RasterLocator;
56
import org.gvsig.fmap.dal.coverage.datastruct.Param;
57
import org.gvsig.fmap.dal.coverage.datastruct.Params;
58
import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
59
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
60
import org.gvsig.fmap.dal.exception.DataException;
61
import org.gvsig.fmap.dal.exception.InitializeException;
62
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
63
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
64
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemFileFilter;
65
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorer;
66
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemServerExplorerParameters;
67
import org.gvsig.fmap.dal.serverexplorer.filesystem.FilesystemStoreParameters;
68
import org.gvsig.fmap.dal.serverexplorer.filesystem.swing.FilesystemExplorerWizardPanel;
69
import org.gvsig.fmap.dal.serverexplorer.filesystem.swing.FilesystemExplorerWizardPanel.MyFileFilter;
70
import org.gvsig.fmap.mapcontext.MapContext;
71
import org.gvsig.fmap.mapcontext.MapContextLocator;
72
import org.gvsig.fmap.mapcontext.MapContextManager;
73
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
74
import org.gvsig.fmap.mapcontext.layers.FLayer;
75
import org.gvsig.fmap.mapcontext.layers.FLayers;
76
import org.gvsig.fmap.mapcontrol.MapControl;
77
import org.gvsig.gui.beans.propertiespanel.PropertiesComponent;
78
import org.gvsig.gui.beans.propertiespanel.PropertyStruct;
79
import org.gvsig.i18n.Messages;
80
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
81
import org.gvsig.raster.util.RasterNotLoadException;
82
import org.gvsig.tools.ToolsLocator;
83
import org.gvsig.tools.dispose.DisposeUtils;
84
import org.gvsig.tools.dynobject.DynObject;
85
import org.gvsig.tools.i18n.I18nManager;
86
import org.gvsig.tools.identitymanagement.UnauthorizedException;
87
import org.gvsig.tools.swing.api.ToolsSwingLocator;
88
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
89

  
90
/**
91
 * Herramientas de uso general y que son dependientes de gvSIG, FMap o de
92
 * libUIComponents. En caso de no serlo existe una clase independiente de
93
 * cualquier proyecto dentro de libRaster para este tipo de funciones.
94
 *
95
 * @author Nacho Brodin (nachobrodin@gmail.com)
96
 */
97
public class RasterToolsUtil {
98

  
99
    private static final Logger logger = LoggerFactory.getLogger(RasterToolsUtil.class);
100

  
101

  
102
	/**
103
	 * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
104
	 * dentro de la agrupaci?n.
105
	 * @param srcLyrs FLayers de la vista
106
	 * @param destLyrs Lista de capas
107
	 * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
108
	 * en la lista es de abajo a arriba las que aparecen en el TOC.
109
	 */
110
	public static ArrayList<FLayer> getRasterLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
111
		if(destLyrs == null)
112
			destLyrs = new ArrayList<FLayer>();
113
		for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
114
			if(srcLyrs.getLayer(i) instanceof DefaultFLyrRaster)
115
				destLyrs.add(srcLyrs.getLayer(i));
116
			if(srcLyrs.getLayer(i) instanceof FLayers)
117
				destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
118
		}
119
		return destLyrs;
120
	}
121

  
122
	/**
123
	 * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
124
	 * dentro de la agrupaci?n.
125
	 * @param srcLyrs FLayers de la vista
126
	 * @param destLyrs Lista de capas
127
	 * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
128
	 * en la lista es de abajo a arriba las que aparecen en el TOC.
129
	 */
130
	public static ArrayList<FLayer> getLayerList(FLayers srcLyrs, ArrayList<FLayer> destLyrs) {
131
		if(srcLyrs == null)
132
			return null;
133
		if(destLyrs == null)
134
			destLyrs = new ArrayList<FLayer>();
135
		for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
136
			if(srcLyrs.getLayer(i) instanceof FLayers)
137
				destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
138
			else
139
				destLyrs.add(srcLyrs.getLayer(i));
140
		}
141
		return destLyrs;
142
	}
143

  
144
	/**
145
	 * Obtiene el nombre de la vista donde est? cargada la capa que se pasa por par?metro
146
	 * @param layer Capa cargada en una vista
147
	 * @return Nombre de la vista donde est? cargada la capa.
148
	 */
149
	public static String getView(FLayer layer) {
150
//		Project p = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
151
		Project p = ProjectManager.getInstance().getCurrentProject();
152
		return p.getViewName(layer);
153
	}
154

  
155
	/**
156
	 * Devuelve la traducci?n de un texto. En caso de no existir la traducci?n al idioma seleccionado
157
	 * devolver? la cadena de entrada.
158
	 * @param parent Ventana padre que contiene el objeto con la traducci?n
159
	 * @param text Texto a traducir
160
	 * @return Texto traducido o cadena de entrada en caso de no encontrar una traducci?n
161
	 */
162
	public static String getText(Object parent, String text) {
163
		return PluginServices.getText(parent, text);
164
	}
165

  
166
	/**
167
	 * Obtiene un icono definido por la etiqueta que se especifica en el
168
	 * par?metro
169
	 * @param ico Etiqueta del icono
170
	 * @return Icono
171
	 */
172
	public static ImageIcon getIcon(String ico) {
173
		return IconThemeHelper.getImageIcon(ico);
174
	}
175

  
176
	/**
177
	 * A?ade una ventana al gestor de ventanas
178
	 * @param window
179
	 */
180
	public static void addWindow(IWindow window) {
181
		PluginServices.getMDIManager().addWindow(window);
182
	}
183

  
184
	/**
185
	 * Elimina una ventana al gestor de ventanas
186
	 * @param window
187
	 */
188
	public static void closeWindow(IWindow window) {
189
		PluginServices.getMDIManager().closeWindow(window);
190
	}
191

  
192
	/**
193
	 * Selecciona los controles del panel de propiedades a partir de los par?mtros
194
	 * obtenidos del driver. Este m?todo realiza una transformaci?n entre Params
195
	 * obtenido del driver de escritura y los par?metros del panel de propiedades.
196
	 * @param panel Panel de propiedades
197
	 * @param params Par?metros del driver
198
	 * @param notTakeIntoAccount Nombre de par?metros que no hay que tener en cuenta. Si es null se tienen en cuenta todos.
199
	 */
200
	public static void loadPropertiesFromWriterParams(PropertiesComponent pComp, Params params, String[] notTakeIntoAccount) {
201
		for (int i = 0; i < params.getNumParams(); i++) {
202
			Param p = params.getParam(i);
203
			String name = getText(null, p.getId());
204
			String key = p.getId();
205

  
206
			//Miramos si el par?metro coincide con  alguno en la lista de parametros que no hay que
207
			//tener en cuenta. Si es as? no lo a?adimos
208
			if(notTakeIntoAccount != null && notTakeIntoAccount.length > 0) {
209
				boolean jump = false;
210
				for (int j = 0; j < notTakeIntoAccount.length; j++) {
211
					if (key.equals(notTakeIntoAccount[j]))
212
						jump = true;
213
				}
214
				if(jump)
215
					continue;
216
			}
217

  
218
			Object[] types = null;
219
			int selectedValue = 0;
220

  
221
			switch (p.getType()) {
222
				case Params.CHECK:
223
					pComp.addValue(name, key, p.getDefaultValue(), types);
224
					break;
225
				case Params.CHOICE:
226
					ArrayList<String> list = new ArrayList<String>();
227
					for (int j = 0; j < p.getList().length; j++) {
228
						list.add(p.getList()[j]);
229
						if (p.getDefaultValue() instanceof Integer)
230
							if (((Integer) p.getDefaultValue()).intValue() == j)
231
								selectedValue = j;
232
					}
233
					types = new Object[] { new Integer(PropertiesComponent.TYPE_COMBO), list };
234
					pComp.addValue(name, key, new Integer(selectedValue), types);
235
					break;
236
				case Params.SLIDER:
237
					types = new Object[] { new Integer(PropertiesComponent.TYPE_SLIDER), new Integer(p.getList()[0]), new Integer(p.getList()[1]) };
238
					pComp.addValue(name, key, p.getDefaultValue(), types);
239
					break;
240
				default:
241
					pComp.addValue(getText(null, ((Param)params.getParam(i)).getId()), params.getParam(i).getId(), params.getParam(i).getDefaultValue(), null);
242
					break;
243
			}
244
		}
245
	}
246

  
247
	/**
248
	 * Carga los par?metros del escritor WriterParams con los valores obtenidos
249
	 * de la ventana de propiedades.
250
	 */
251
	@SuppressWarnings("unchecked")
252
	public static void loadWriterParamsFromPropertiesPanel(PropertiesComponent pComp, Params params) {
253
		ArrayList<PropertyStruct> values = pComp.getValues();
254
		for (int iParam = 0; iParam < params.getNumParams(); iParam++) {
255
			Param p = params.getParam(iParam);
256
			for (int iValue = 0; iValue < values.size(); iValue++) {
257
				PropertyStruct prop = values.get(iValue);
258
				if (p.getId().compareTo(prop.getKey()) == 0) {
259
					switch (p.getType()) {
260
						case Params.CHECK:
261
							p.setDefaultValue((Boolean) prop.getNewValue());
262
							break;
263
						case Params.CHOICE:
264
							p.setDefaultValue(((Integer) prop.getNewValue()));//p.list[((Integer) prop.getNewValue()).intValue()];
265
							break;
266
						case Params.SLIDER:
267
							try {
268
								p.setDefaultValue((Integer)prop.getNewValue());
269
							} catch (NumberFormatException e) {}
270
					}
271
					break;
272
				}
273
			}
274
		}
275
	}
276

  
277
	/**
278
	 * Funci?n que devuelve true si se tiene permiso de escritura en la ruta
279
	 * indicada en el par?metro path y false si no los tiene.
280
	 * @param path Ruta a comprobar los permisosv
281
	 * @param pluginObject si es distinto de null se obtiene un mensaje de
282
	 *          advertencia y sirve como par?metro para getText de la traducci?n.
283
	 *          Si es null no se mostrar? ventana de advertencia
284
	 * @return true si se tiene permiso de escritura en la ruta indicada en el
285
	 *         par?metro path y false si no los tiene.
286
	 */
287
	public static boolean canWrite(String path) {
288
		File f = new File(path);
289
		if(f.exists() && f.canWrite())
290
			return true;
291
		else {
292
			JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
293
						Messages.getText("error_writing_raster_file"));
294
			return false;
295
		}
296
	}
297

  
298
	/**
299
	 * Carga una capa raster en una vista de gvSIG.
300
	 * @param viewName Nombre de la vista donde ha de cargarse. Si vale null se cargar? en la
301
	 * primera vista que encuentre que est? activa. Si no hay ninguna saltar? una excepci?n.
302
	 * @param fileName Nombre del fichero a cargar. No debe ser nulo nunca.
303
	 * @param layerName Nombre de la capa. Si es null se asignar? el nombre del
304
	 * fichero sin extensi?n.
305
	 * @throws RasterNotLoadException Excepci?n que se lanza cuando no se ha podido cargar la capa
306
	 * por alg?n motivo.
307
	 */
308
	@SuppressWarnings("deprecation")
309
	public static void loadLayer(String viewName, String fileName, final String layerName) throws RasterNotLoadException {
310
	    //Este m?todo, antes devolv?a la layer a?adida, pero no hevisto ning?n sitio d?nde se utilizara.
311
		if(fileName ==  null){
312
			return;
313
		}
314
		File file = new File(fileName);
315

  
316
		//Seleccionamos la vista de gvSIG
317
		AbstractViewPanel theView = null;
318
		try {
319
			IWindow[] allViews = PluginServices.getMDIManager().getAllWindows();
320
			if(viewName != null) {
321
				for (int i = 0; i < allViews.length; i++) {
322
					if (allViews[i] instanceof AbstractViewPanel
323
						&& (((AbstractViewPanel) allViews[i]).getDocument().getName().equals(viewName) ||
324
							PluginServices.getMDIManager().getWindowInfo((AbstractViewPanel) allViews[i]).getTitle().equals(viewName)))
325
						theView = (AbstractViewPanel) allViews[i];
326
				}
327
			} else {
328
				IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
329
				for (int i = 0; i < allViews.length; i++) {
330
					if (allViews[i] instanceof AbstractViewPanel && ((AbstractViewPanel)allViews[i]) == activeWindow) //En la primera vista activa
331
						theView = (AbstractViewPanel) allViews[i];
332
				}
333
				if(theView == null) {
334
					for (int i = 0; i < allViews.length; i++) {
335
						if (allViews[i] instanceof AbstractViewPanel) //En la primera vista
336
							theView = (AbstractViewPanel) allViews[i];
337
					}
338
				}
339
			}
340

  
341
			if (theView == null)
342
				throw new RasterNotLoadException("Imposible cargar la capa.");
343
		} catch (ClassCastException ex) {
344
			throw new RasterNotLoadException("No se puede hacer un casting de esa IWindow a View.");
345
		}
346

  
347
		DataManager dm = DALLocator.getDataManager();
348
        FilesystemServerExplorerParameters param;
349
        FilesystemServerExplorer explorer;
350
        try {
351
            param = (FilesystemServerExplorerParameters) dm
352
                    .createServerExplorerParameters(FilesystemServerExplorer.NAME);
353
            explorer = (FilesystemServerExplorer) dm.openServerExplorer(
354
                            FilesystemServerExplorer.NAME, param);
355
        } catch (Exception e) {
356
            throw new RuntimeException(e);
357
        }
358

  
359
        int mode = FilesystemServerExplorer.MODE_RASTER;
360

  
361
        try {
362

  
363
            final DataStoreParameters parameters = explorer.createStoreParameters(file);
364

  
365
            final MapControl mapControl = theView.getMapControl();
366
            final boolean b_isMapControlAvail = (mapControl!=null);
367
            final MapContext mapContext = mapControl.getMapContext();
368
            final ApplicationManager application = ApplicationLocator.getManager();
369
            final MapContextManager manager = MapContextLocator.getMapContextManager();
370

  
371
            logger.info("addLayer('{}',...)", layerName);
372
            Thread task = new Thread(new Runnable() {
373

  
374
                @Override
375
                public void run() {
376
                    FLayer layer = null;
377
                    FLayer preparedLayer = null;
378
                    try {
379
                        DataManager dataManager = DALLocator.getDataManager();
380
                        final DataStore dataStore = dataManager.openStore(parameters.getDataStoreName(), parameters);
381
                        DataStoreProviderFactory factory = dataStore.getProviderFactory();
382
                        //Descomentarizar si se desea tilear estas capas
383

  
384
//                        if (factory.isTiledSupported() != DataStoreProviderFactory.NO) {
385
//                            if (isTiled(parameters)) {
386
//                                DynObject tileParameters = dataManager.createStoreParameters("TileCache");
387
//
388
//                                File rootFolder = new File(Launcher.getAppHomeDir() + File.separator + "gvsig_rcache");
389
//
390
//                                if (tileParameters.getDynClass().getDynField("rootFolder") != null) {
391
//                                    tileParameters.setDynValue("rootFolder", rootFolder);
392
//                                }
393
//
394
//                                try {
395
//                                    dataStore.useCache("TileCache", tileParameters);
396
//                                } catch (DataException e) {
397
//                                    logger.warn("Can't cache the layer.", e);
398
//                                }
399
//
400
//                            }
401
//                        }
402
                        String name;
403
                        if (layerName == null) {
404
                            name = dataStore.getName();
405
                        } else {
406
                            name = layerName;
407
                        }
408
                        layer = manager.createLayer(name, dataStore);
409

  
410
                        DisposeUtils.disposeQuietly(dataStore);
411
                        preparedLayer = application.prepareOpenLayer(layer, new PrepareContextView_v1() {
412

  
413
                            @Override
414
                            public Window getOwnerWindow() {
415
                                return null;
416
                            }
417

  
418
                            @Override
419
                            public MapControl getMapControl() {
420
                                return mapControl;
421
                            }
422

  
423
                            @Override
424
                            public IProjection getViewProjection() {
425
                                return mapContext.getProjection();
426
                            }
427

  
428
                            @Override
429
                            public MapContext getMapContext() {
430
                                return mapContext;
431
                            }
432

  
433
                            @Override
434
                            public boolean isMapControlAvailable() {
435
                                return b_isMapControlAvail;
436
                            }
437
                        });
438
                        if (preparedLayer != null) {
439
                            mapContext.getLayers().addLayer(preparedLayer);
440
                        }
441
                    } catch (UnauthorizedException e) {
442
                        I18nManager i18nManager = ToolsLocator.getI18nManager();
443
                        ApplicationManager application = ApplicationLocator.getManager();
444
                        String resource = "";
445
                        if (e.getResource() instanceof FilesystemStoreParameters) {
446
                            resource = ((FilesystemStoreParameters) e.getResource()).getFile().getPath();
447
                        }
448
                        application.messageDialog(
449
                            i18nManager.getTranslation("_User_0_is_not_authorized_to_1_on_resource_2_3", new String[] {
450
                                e.getIdentity().getID(), e.getActionName(), e.getResourceName(), resource }),
451
                            i18nManager.getTranslation("_Unauthorized_access"), JOptionPane.WARNING_MESSAGE);
452
                        logger.warn("Unauthorized access to layer '" + layerName + "'.", e);
453

  
454
                    } catch (Exception e) {
455
                        LayerErrorsPanel panel = new LayerErrorsPanel(layerName, e);
456
                        if (preparedLayer != null) {
457
                            panel.setLayer(preparedLayer);
458
                        } else if (layer != null) {
459
                            panel.setLayer(layer);
460
                        }
461
                        I18nManager i18nManager = ToolsLocator.getI18nManager();
462
                        ToolsSwingLocator.getWindowManager().showWindow(panel,
463
                            i18nManager.getTranslation("_Problems_loading_the_layer"), WindowManager.MODE.WINDOW);
464
                        logger.warn("Can't load layer '" + layerName + "'.", e);
465

  
466
                    } finally {
467
                        if (preparedLayer != layer) {
468
                            DisposeUtils.disposeQuietly(preparedLayer);
469
                        }
470
                        DisposeUtils.disposeQuietly(layer);
471
                    }
472
                }
473
            });
474
            task.start();
475
            return;
476

  
477
        } catch (DataException e){
478
            throw new RasterNotLoadException("Error al cargar la capa.");
479
        }
480
	}
481

  
482
	/**
483
	 * Calculo de las coordenadas de una ventana IWindow para que quede centrada sobre el
484
	 * MainFrame. Estas coordenadas solo valen para un IWindow ya que andami mete las ventanas
485
	 * con coordenadas relativas a su ventanta principal.
486
	 * @param widthWindow Ancho de la ventana a a?adir
487
	 * @param heightWindow Alto de la ventana a a?adir
488
	 * @return Array con el ancho y el alto
489
	 */
490
	public static Point iwindowPosition(int widthWindow, int heightWindow) {
491
		int posWindowX = 0;
492
		int posWindowY = 0;
493
		Dimension dim = null;
494
		Point pos = null;
495
		if(PluginServices.getMainFrame() instanceof Component) {
496
			dim = ((Component)PluginServices.getMainFrame()).getSize();
497
			pos = ((Component)PluginServices.getMainFrame()).getLocation();
498
			if(dim != null && pos != null) {
499
				posWindowX = ((dim.width >> 1) - (widthWindow >> 1));
500
				posWindowY = ((dim.height >> 1) - (heightWindow >> 1) - 70);
501
				return new Point(posWindowX, posWindowY);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff