Revision 2237

View differences:

org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/buildNumber.properties
1
#maven.buildNumber.plugin properties file
2
#Wed May 15 12:24:07 CEST 2013
3
buildNumber=45
0 4

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/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
	  </includes>
38
	</dependencySet>
39
  </dependencySets>
40
</assembly>
0 41

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/IProcessActions.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.raster.process;
23

  
24
/**
25
 * Acciones que puede ejecutar un proceso sobre un objeto externo. Un proceso
26
 * debe ser independiente de objetos que sean dependientes de su funcionalidad. Es
27
 * decir, cualquier extensi?n debe poder usar un proceso y este ejecutar metodos
28
 * de la funcionalidad. Esto se hace ha trav?s de este interfaz.
29
 * 
30
 * @version 26/09/2007
31
 * @author Nacho Brodin (nachobrodin@gmail.com)
32
 *
33
 */
34
public interface IProcessActions {
35
	
36
	/**
37
	 * El proceso comunica que ha sido interrumpido
38
	 *
39
	 */
40
	public void interrupted();
41

  
42
	/**
43
	 * Acciones de finalizaci?n del proceso
44
	 */
45
	public void end(Object param);
46
}
0 47

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/OverviewsProcess.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.raster.process;
23

  
24
import org.gvsig.andami.PluginServices;
25
import org.gvsig.fmap.dal.coverage.RasterLocator;
26
import org.gvsig.fmap.dal.coverage.exception.OverviewException;
27
import org.gvsig.fmap.dal.coverage.process.BaseIncrementableTask;
28
import org.gvsig.fmap.dal.coverage.process.overview.OverviewBuilder;
29
import org.gvsig.raster.fmap.layers.FLyrRaster;
30
import org.gvsig.raster.mainplugin.config.Configuration;
31

  
32

  
33
/**
34
 * Proceso para la generaci?n de overviews.
35
 *
36
 * 10/12/2007
37
 * @author Nacho Brodin nachobrodin@gmail.com
38
 */
39
public class OverviewsProcess extends RasterProcess implements BaseIncrementableTask {
40
	private FLyrRaster   rasterSE      = null;
41
	private int          value         = 0;
42
	private int          resamplingAlg = OverviewBuilder.AVERAGE;
43
	private int[]        overviews     = new int[] { 2, 4, 8, 16 };
44
	private String       builder       = "GDAL";
45
	
46
	/*
47
	 * (non-Javadoc)
48
	 * @see org.gvsig.rastertools.RasterProcess#init()
49
	 */
50
	public void init() {
51
		rasterSE = getLayerParam("layer");
52
		builder = getStringParam("builder") != null ? getStringParam("builder") : builder;
53

  
54
		int overviewsRate = 2;
55
		int nOverviews = 4;
56
		overviewsRate = Configuration.getValue("overviews_rate", new Integer(overviewsRate)).intValue();
57
		nOverviews = Configuration.getValue("overviews_number", new Integer(nOverviews)).intValue();
58
		resamplingAlg = Configuration.getValue("overviews_resampling_algorithm", new Integer(resamplingAlg)).intValue();
59

  
60
		// Leemos de la configuraci?n los valores de algoritmo a usar,
61
		// n?mero de overviews a generar y proporci?n de la primera overview
62

  
63
		overviews = new int[nOverviews];
64
		overviews[0] = overviewsRate;
65
		for (int i = 1; i < nOverviews; i++)
66
			overviews[i] = overviewsRate * overviews[i - 1];
67
	}
68

  
69
	/**
70
	 * M?todo donde se ejecutar? el Thread, aqu? se generaran las
71
	 * overviews
72
	 * @throws ProcessException 
73
	 */
74
	public void process() throws ProcessException {
75
		insertLineLog(PluginServices.getText(this, "overviews_generating"));
76
		OverviewBuilder overviewBuilder = RasterLocator.getManager().getOverviewBuilder(builder);
77
		
78
		overviewBuilder.setIncrementListener(this);
79
		try {
80
			String[] uri = rasterSE.getDataStore().getURIByProvider();
81

  
82
			for (int i = 0; i < uri.length; i++) {
83
				insertLineLog(" Dataset: " + i);
84
				overviewBuilder.buildOverviews(resamplingAlg, uri[i], overviews);
85
			}
86

  
87
			if (externalActions != null)
88
				externalActions.end(rasterSE);
89
		} catch (OverviewException e) {
90
			if (incrementableTask != null)
91
				incrementableTask.hideWindow();
92
			throw new ProcessException("error_write_overviews", e);
93
		}
94
	}
95

  
96
	/*
97
	 * (non-Javadoc)
98
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
99
	 */
100
	public int getPercent() {
101
		return value;
102
	}
103

  
104
	/*
105
	 * (non-Javadoc)
106
	 * @see org.gvsig.addo.IOverviewIncrement#setPercent(int)
107
	 */
108
	public void setPercent(int value) {
109
		this.value = value;
110
	}
111

  
112
	/*
113
	 * (non-Javadoc)
114
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
115
	 */
116
	public String getTitle() {
117
		return PluginServices.getText(this, "incremento_overview");
118
	}
119
	
120
	/*
121
	 * (non-Javadoc)
122
	 * @see java.lang.Object#finalize()
123
	 */
124
	protected void finalize() throws Throwable {
125
		rasterSE           = null;
126
		overviews           = null;
127
		super.finalize();
128
	}
129
}
0 130

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/StatisticsProcess.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.raster.process;
23

  
24
import javax.swing.SwingUtilities;
25

  
26
import org.gvsig.andami.PluginServices;
27
import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
28
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
29
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
30
import org.gvsig.fmap.dal.coverage.store.props.Statistics;
31
import org.gvsig.raster.fmap.layers.FLyrRaster;
32

  
33

  
34
/**
35
 * Proceso para la generaci?n de estad?sticas.
36
 *
37
 * 10/12/2007
38
 * @author Nacho Brodin nachobrodin@gmail.com
39
 */
40
public class StatisticsProcess extends RasterProcess {
41
	private FLyrRaster            lyr   = null;
42
	private Statistics            stats = null;
43
	private boolean               force = false;
44
	private double                scale = 1;
45

  
46
	/**
47
	 * Lanzador del procesos de estad?sticas
48
	 * @param lyr Capa a calcular las estad?sticas
49
	 * @param actions Clase que recoge eventos del proceso
50
	 */
51
	public static void launcher(FLyrRaster lyr, IProcessActions actions) {
52
		RasterProcess process = new StatisticsProcess();
53
		process.addParam("layer", lyr);
54
		process.addParam("force", new Boolean(false));
55
		process.setActions(actions);
56
		process.start();	
57
	}
58
	
59
	/*
60
	 * (non-Javadoc)
61
	 * @see org.gvsig.rastertools.RasterProcess#init()
62
	 */
63
	public void init() {
64
		lyr = getLayerParam("layer");
65
		force = getBooleanParam("force");
66
		double s = getDoubleParam("scale");
67
		if(s > 0 && s < 1)
68
			scale = s;
69
	}
70

  
71
	/**
72
	 * M?todo donde se ejecutar? el Thread, aqu? se calcular?n las 
73
	 * estad?sticas.
74
	 * @throws ProcessException 
75
	 */
76
	public void process() throws ProcessInterruptedException, ProcessException {
77
		insertLineLog(PluginServices.getText(this, "statistics_generation"));
78
		if(lyr == null || lyr.getDataStore() == null)
79
			return;
80
		stats = lyr.getDataStore().getStatistics();
81
		lyr.setReadingData(Thread.currentThread().getId() + "");
82
		if (force)
83
			stats.forceToRecalc();
84
		try {
85
			stats.calculate(scale);
86
			SwingUtilities.invokeLater(new Runnable() {
87
				public void run() {
88
					if (externalActions != null)
89
						externalActions.end(lyr);
90
				}
91
			});
92
		} catch (FileNotOpenException e) {
93
			throw new ProcessException("No se ha podido escribir en el fichero rmf", e);
94
		} catch (RasterDriverException e) {
95
			throw new ProcessException("Error leyendo bloques de datos para calcular estad?sticas", e);
96
		} finally {
97
			lyr.setReadingData(null);
98
		}
99
	}
100

  
101
	/*
102
	 * (non-Javadoc)
103
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
104
	 */
105
	public int getPercent() {
106
		return (stats != null) ? stats.getPercent() : 0;
107
	}
108

  
109
	/*
110
	 * (non-Javadoc)
111
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
112
	 */
113
	public String getTitle() {
114
		return PluginServices.getText(this, "increase_statistics");
115
	}
116
}
0 117

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/UniqueProcessQueue.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.raster.process;
23

  
24
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
25
import org.gvsig.raster.util.Queue;
26

  
27
/**
28
 * Cola de procesos de ejecuci?n exclusiva. Los procesos de esta lista se ir?n ejecutando
29
 * por orden de llegada impidiendo que se ejecuten dos al mismo tiempo.
30
 * 
31
 * 16/05/2008
32
 * @author Nacho Brodin nachobrodin@gmail.com
33
 */
34
public class UniqueProcessQueue implements IProcessActions {
35
	private static final int          LAPSE_TIME       = 1000;
36

  
37
	private Queue                     queue            = new Queue();
38
	private RasterProcess             executionProcess = null;
39
	static private UniqueProcessQueue singleton        = new UniqueProcessQueue();
40

  
41
	/**
42
	 * Dejamos el constructor privado para que nadie pueda referenciarlo
43
	 */
44
	private UniqueProcessQueue() {}
45
	
46
	/**
47
	 * Devuelve una instancia al unico objeto de UniqueProcessQueue que puede existir.
48
	 * @return
49
	 */
50
	static public UniqueProcessQueue getSingleton() {
51
		return singleton;
52
	}
53
	
54
	/**
55
	 * A?ade un proceso a la cola.
56
	 * @param id Identificador del proceso
57
	 * @param process Proceso
58
	 */
59
	public synchronized void add(RasterProcess process) {
60
		queue.put(process);
61
		process.setUniqueProcessActions(this);
62
		
63
		//Decisi?n de arranque
64
		if(queue.size() >= 1 && executionProcess != null)
65
			start();
66
	}
67
	
68
	/**
69
	 * Pone en marcha el primer proceso de la lista
70
	 */
71
	public void start() {
72
		nextProcess();
73
	}
74
	
75
	private void nextProcess() {
76
		executionProcess = ((RasterProcess) queue.get());
77
		if (executionProcess != null)
78
			executionProcess.start();
79
	}
80

  
81
	/**
82
	 * Evento de finalizaci?n de un proceso. Cuando un proceso acaba se 
83
	 * pone en marcha el siguiente de la lista si existe. Se asigna un tiempo de latencia para
84
	 * la ejecuci?n del siguiente marcado por LAPSE_TIME.  
85
	 */
86
	public void end(Object param) {
87
		try {
88
			Thread.sleep(LAPSE_TIME);
89
		} catch (InterruptedException e) {
90
			RasterToolsUtil.debug("sleep Exception", null, e);
91
		}
92
		nextProcess();
93
	}
94
	
95
	/**
96
	 * How many elements are there in this queue?
97
	 */
98
	public int size() {
99
		return queue.size();
100
	}
101

  
102
	/*
103
	 * (non-Javadoc)
104
	 * @see org.gvsig.raster.IProcessActions#interrupted()
105
	 */
106
	public void interrupted() {}	
107
}
0 108

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/HistogramProcess.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.raster.process;
23

  
24
import javax.swing.SwingUtilities;
25

  
26
import org.gvsig.andami.PluginServices;
27
import org.gvsig.fmap.dal.coverage.datastruct.BufferHistogram;
28
import org.gvsig.fmap.dal.coverage.exception.HistogramException;
29
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
30
import org.gvsig.fmap.dal.coverage.store.props.HistogramComputer;
31

  
32
/**
33
* Process to calculate a Histogram using a Histogramable object. A Histogramable object
34
* has its own method to build an histogram an this process will call to this function. 
35
* 
36
* @author Nacho Brodin (nachobrodin@gmail.com)
37
*/
38
public class HistogramProcess extends RasterProcess {
39
	private BufferHistogram        lastHistogram  = null;
40
	private HistogramComputer      histogramable  = null;
41
	
42
	/*
43
	 * (non-Javadoc)
44
	 * @see org.gvsig.rastertools.RasterProcess#init()
45
	 */
46
	public void init() {
47
		histogramable = (HistogramComputer) getParam("histogramable");
48
	}
49

  
50
	/*
51
	 * (non-Javadoc)
52
	 * @see org.gvsig.rastertools.RasterProcess#process()
53
	 */
54
	public void process() throws ProcessInterruptedException, ProcessException {
55
		try {
56
			// Proceso duro de obtener un histograma. Puede durar bastante tiempo.
57
			lastHistogram = histogramable.getBufferHistogram();
58
			// Ya tenemos el histograma y lo representamos en la ventana
59
			SwingUtilities.invokeLater(new Runnable() {
60
				public void run() {
61
					if ((externalActions != null) && (lastHistogram != null))
62
						externalActions.end(lastHistogram);
63
				}
64
			});
65
			
66
		} catch (HistogramException e) {
67
			throw new ProcessException("Error calculando el histograma", e);
68
		} 
69
	}
70
	
71
	/*
72
	 * (non-Javadoc)
73
	 * @see org.gvsig.raster.RasterProcess#getResult()
74
	 */
75
	public Object getResult() {
76
		return lastHistogram;
77
	}
78

  
79
	/*
80
	 * (non-Javadoc)
81
	 * @see org.gvsig.rastertools.RasterProcess#getLog()
82
	 */
83
	public String getLog() {
84
		return PluginServices.getText(this, "calculando_histograma") + "...\n";
85
	}
86

  
87
	/*
88
	 * (non-Javadoc)
89
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
90
	 */
91
	public int getPercent() {
92
		if (histogramable != null)
93
			return histogramable.getPercent();
94
		return 0;
95
	}
96

  
97
	/*
98
	 * (non-Javadoc)
99
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
100
	 */
101
	public String getTitle() {
102
		return PluginServices.getText(this, "calculando_histograma");
103
	}
104
	
105
	/*
106
	 * (non-Javadoc)
107
	 * @see java.lang.Object#finalize()
108
	 */
109
	protected void finalize() throws Throwable {
110
		lastHistogram           = null;
111
		histogramable           = null;
112
		super.finalize();
113
	}
114
}
0 115

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/ProcessException.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.raster.process;
23
/**
24
 * This exception is thrown when a problem inside a raster process
25
 * is detected. 
26
 * 
27
 * @author Nacho Brodin (nachobrodin@gmail.com)
28
 */
29
public class ProcessException extends Exception {
30
	private static final long serialVersionUID = 666908550965442025L;
31

  
32
	public ProcessException(String msg, Throwable e) {
33
		super(msg, e);
34
	}
35
	
36
	public ProcessException(String msg){
37
		super(msg);
38
	}
39
}
0 40

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/RasterProcess.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.raster.process;
23

  
24
import java.util.Hashtable;
25

  
26
import org.gvsig.fmap.dal.coverage.RasterLocator;
27
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
28
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
29
import org.gvsig.fmap.dal.coverage.process.CancelEvent;
30
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
31
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
32
import org.gvsig.gui.beans.incrementabletask.IIncrementable;
33
import org.gvsig.gui.beans.incrementabletask.IncrementableEvent;
34
import org.gvsig.gui.beans.incrementabletask.IncrementableListener;
35
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
36
import org.gvsig.raster.fmap.layers.FLyrRaster;
37
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
38
import org.gvsig.tools.dispose.Disposable;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41
/**
42
 * Clase base de todos los procesos raster. En ella se genstionan todas las
43
 * funciones comunes como incremento de la tarea, gesti?n de eventos a la tarea, 
44
 * par?metros de la tarea, etc ...
45
 * 
46
 * 18/12/2007
47
 * @author Nacho Brodin nachobrodin@gmail.com
48
 * @deprecated Use DataProcess in org.gvsig.raster.algorithm
49
 */
50
public abstract class RasterProcess implements IIncrementable, IncrementableListener, Runnable, Disposable {
51
	protected IncrementableTask incrementableTask = null;
52
	protected volatile Thread   blinker           = null;
53
	protected TaskEventManager  taskEventManager  = null;
54
	protected IProcessActions   externalActions   = null;
55
	protected Hashtable<String, Object>
56
	                            taskParams        = new Hashtable<String, Object>();
57

  
58
	private String              log               = "";
59
	private String              lastLine          = "";
60
	private long                time              = 0;
61
	private boolean             progressActive    = true;
62
	private IProcessActions     queueActions      = null;
63
	private Logger              logger            = LoggerFactory.getLogger(RasterProcess.class.toString());
64

  
65
	
66
	/**
67
	 * Crea la ventana de IncrementableTask
68
	 */
69
	public IncrementableTask getIncrementableTask() {
70
		if (incrementableTask == null) {
71
			incrementableTask = new IncrementableTask(this);
72
			incrementableTask.addIncrementableListener(this);
73
		}
74
		return incrementableTask;
75
	}
76
	
77
	/**
78
	 * Define si se puede cancelar el proceso. Por defecto es true.
79
	 * @param enabled
80
	 */
81
	public void setCancelable(boolean enabled) {
82
		getIncrementableTask().getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_CANCEL, enabled);
83
	}
84
	
85
	/**
86
	 * Muestra la ventana de IncrementableTask
87
	 */
88
	public void showIncrementableWindow() {
89
		if (progressActive) {
90
			getIncrementableTask().showWindow();
91
			getIncrementableTask().start();
92
		}
93
	}
94

  
95
	/**
96
	 * Arranca el proceso de recorte de un layer
97
	 */
98
	public void start() {
99
		showIncrementableWindow();
100
		if(blinker == null)
101
			blinker = new Thread(this);
102
		blinker.start();
103
	}
104
		
105
	/**
106
	 * Proceso de carga de par?metros. Puede no hacerse una carga de par?metros 
107
	 * explicita y obtenerlos directamente de la tabla Hash cuando vayan a usarse. 
108
	 * Esto queda a elecci?n del programador. En caso de hacerse una carga de par?metros
109
	 * explicita esta llamada deber?a hacerse justo despues del constructor de la clase
110
	 * que contendr? el proceso.
111
	 */
112
	public abstract void init();
113
	
114
	/**
115
	 * Proceso
116
	 * @throws InterruptedException
117
	 */
118
	public abstract void process() throws ProcessInterruptedException, ProcessException;
119
	
120
	/**
121
	 * Obtenci?n de un objeto de resultado. Este objeto deber? ser el mismo que el que se
122
	 * pasa por par?metro en el "end" de IProcessActions. Este m?todo es util cuando la tarea no se
123
	 * lanza en un Thread (ejecutamos process directamente) y queremos recoger el resultado
124
	 * sin registrarnos al evento de finalizaci?n de tarea.
125
	 * @return objeto resultado de la tarea
126
	 */
127
	public Object getResult() {
128
		return null;
129
	}
130
	
131
	/**
132
	 * Proceso
133
	 * @throws ProcessException 
134
	 */
135
	public void execute() throws ProcessInterruptedException, ProcessException {
136
		init();
137
		process();
138
	}
139
	
140
	/**
141
	 * M?todo donde se ejecutar? el Thread. Este har? las acciones globales para 
142
	 * cualquier tarea y llamar? al m?todo execute especifico de una tarea.
143
	 */
144
	public void run() {
145
		long t1 = new java.util.Date().getTime();
146

  
147
		try {
148
			taskEventManager = RasterLocator.getManager().createRasterTask(this);
149
			execute();
150
		} catch (ProcessInterruptedException e) {
151
			if (externalActions != null)
152
				externalActions.interrupted();
153
			Thread.currentThread().interrupt();
154
		} catch (ProcessException e) {
155
			if (progressActive) {
156
				if (incrementableTask != null) {
157
					getIncrementableTask().processFinalize();
158
					incrementableTask = null;
159
				}
160
			}
161
			logger.warn(RasterLocator.getManager().getRasterUtils().getTrace(e));
162
			if(e.getMessage() != null && e.getMessage().compareTo("") != 0)
163
				RasterToolsUtil.messageBoxError(e.getMessage(), this);
164
			else
165
				RasterToolsUtil.messageBoxError("error_processing", this);
166
			queueActions = null;
167

  
168
		} catch (Exception e) {
169
			if (progressActive) {
170
				if (incrementableTask != null) {
171
					getIncrementableTask().processFinalize();
172
					incrementableTask = null;
173
				}
174
			}
175
			logger.warn(RasterLocator.getManager().getRasterUtils().getTrace(e));
176
			if(e.getMessage() != null && e.getMessage().compareTo("") != 0)
177
				RasterToolsUtil.messageBoxError(e.getMessage(), this);
178
			else
179
				RasterToolsUtil.messageBoxError("error_processing", this);
180
			queueActions = null;
181
		} finally {
182
			taskEventManager.removeTask();
183
			if (progressActive) {
184
				if (incrementableTask != null)
185
					getIncrementableTask().processFinalize();
186
			}
187
			if (queueActions != null)
188
				queueActions.end(this);
189
			time = new java.util.Date().getTime() - t1;
190
			blinker = null;
191
		}
192
	}
193
	
194
	/**
195
	 * Activa o desactiva el interfaz de progreso en el lanzamiento de la tarea como un thread.
196
	 * @param active true para activarlo o false para desactivarlo
197
	 */
198
	public void setProgressActive(boolean active){
199
		this.progressActive = active;
200
	}
201
	
202
	/**
203
	 * Obtiene el tiempo que tard? en ejecutarse la tarea 
204
	 * la ?ltima vez que se proces?
205
	 */
206
	public long getTime() {
207
		return time;
208
	}
209
	
210
	/**
211
	 * Obtiene el objeto para ejecutar acciones externar.
212
	 * @param IProcessActions
213
	 */
214
	public IProcessActions getActions() {
215
		return externalActions;
216
	}
217

  
218
	/**
219
	 * Asigna el objeto para ejecutar acciones externar.
220
	 * @param IProcessActions
221
	 */
222
	public void setActions(IProcessActions actions) {
223
		this.externalActions = actions;
224
	}
225
	
226
	/**
227
	 * Obtiene el objeto para ejecutar acciones de la cola de procesos de ejecuci?n exclusiva.
228
	 * @param IProcessActions
229
	 */
230
	public IProcessActions getUniqueProcessActions() {
231
		return queueActions;
232
	}
233

  
234
	/**
235
	 * Asigna el objeto para ejecutar acciones externar.
236
	 * @param IProcessActions
237
	 */
238
	public void setUniqueProcessActions(IProcessActions actions) {
239
		this.queueActions = actions;
240
	}
241
	
242
	/**
243
	 * Inserta una nueva l?nea en el log del cuadro de incremento de tarea
244
	 * @param line
245
	 */
246
	protected void insertLineLog(String line) {
247
		lastLine = line;
248
		log = log + line + "\n";
249
	}
250
	
251
	/**
252
	 * Obtiene la ?ltima l?nea introducida en el log del cuadro de incremento.
253
	 */
254
	public String getLabel() {
255
		return lastLine;
256
	}
257
	
258
	/**
259
	 * Obtiene el texto de log del cuadro de incremento completo.
260
	 */
261
	public String getLog() {
262
		return log;
263
	}
264
	
265
	/**
266
	 * Un evento de cancelado es enviado a la tarea cuando actionCanceled es activado. Para
267
	 * ello se crear? un objeto CancelEvent y se asignar? a la tarea en ejecuci?n. Esta lo
268
	 * procesar? cuando pueda e interrumpir? el proceso.
269
	 */
270
	public void actionCanceled(IncrementableEvent e) {
271
		taskEventManager.setEvent(new CancelEvent(this));
272
	}
273
	
274
	/**
275
	 * A?ade un par?metro a la tarea
276
	 * @param name Clave del par?metro
277
	 * @param param Objeto pasado como par?metro
278
	 */
279
	public void addParam(String name, Object param) {
280
		if (param != null)
281
			taskParams.put(name, param);
282
		else
283
			taskParams.remove(name);
284
	}
285

  
286
	/**
287
	 * Elimina un par?metro de la tarea
288
	 * @param name Clave del par?metro a eliminar
289
	 */
290
	public void removeParam(String name) {
291
		taskParams.remove(name);
292
	}
293

  
294
	/**
295
	 * Obtiene un par?metro a partir de la clave
296
	 * @param name Par?metro
297
	 * @return Par?metro
298
	 */
299
	public Object getParam(String name) {
300
		return taskParams.get(name);
301
	}
302
	
303
	/**
304
	 * Obtiene un par?metro String a partir de la clave
305
	 * @param name Par?metro
306
	 * @return Par?metro
307
	 */
308
	public String getStringParam(String name) {
309
		Object value = taskParams.get(name);
310
		return (value != null && value instanceof String) ? (String)value : null;
311
	}
312
	
313
	/**
314
	 * Obtiene un par?metro byte a partir de la clave
315
	 * @param name Par?metro
316
	 * @return Par?metro
317
	 */
318
	public byte getByteParam(String name) {
319
		Object value = taskParams.get(name);
320
		return (value != null && value instanceof Byte) ? ((Byte)value).byteValue() : 0;
321
	}
322
	
323
	/**
324
	 * Obtiene un par?metro float a partir de la clave
325
	 * @param name Par?metro
326
	 * @return Par?metro
327
	 */
328
	public float getFloatParam(String name) {
329
		Object value = taskParams.get(name);
330
		return (value != null && value instanceof Float) ? ((Float)value).floatValue() : 0F;
331
	}
332
	
333
	/**
334
	 * Obtiene un par?metro double a partir de la clave
335
	 * @param name Par?metro
336
	 * @return Par?metro
337
	 */
338
	public double getDoubleParam(String name) {
339
		Object value = taskParams.get(name);
340
		return (value != null && value instanceof Double) ? ((Double)value).doubleValue() : 0D;
341
	}
342
	
343
	/**
344
	 * Obtiene un par?metro entero a partir de la clave
345
	 * @param name Par?metro
346
	 * @return Par?metro
347
	 */
348
	public int getIntParam(String name) {
349
		Object value = taskParams.get(name);
350
		return (value != null && value instanceof Integer) ? ((Integer)value).intValue() : 0;
351
	}
352
	
353
	/**
354
	 * Obtiene un par?metro boolean a partir de la clave
355
	 * @param name Par?metro
356
	 * @return Par?metro
357
	 */
358
	public boolean getBooleanParam(String name) {
359
		Object value = taskParams.get(name);
360
		return (value != null && value instanceof Boolean) ? ((Boolean)value).booleanValue() : false;
361
	}
362
	
363
	/**
364
	 * Obtiene un par?metro int[] a partir de la clave
365
	 * @param name Par?metro
366
	 * @return Par?metro
367
	 */
368
	public int[] getIntArrayParam(String name) {
369
		Object value = taskParams.get(name);
370
		return (value != null && value instanceof int[]) ? ((int[])value) : null;
371
	}
372
	
373
	/**
374
	 * Obtiene un par?metro double[] a partir de la clave
375
	 * @param name Par?metro
376
	 * @return Par?metro
377
	 */
378
	public double[] getDoubleArrayParam(String name) {
379
		Object value = taskParams.get(name);
380
		return (value != null && value instanceof double[]) ? ((double[])value) : null;
381
	}
382
	
383
	/**
384
	 * Obtiene un par?metro capa raster a partir de la clave
385
	 * @param name Par?metro
386
	 * @return Par?metro
387
	 */
388
	public FLyrRaster getLayerParam(String name) {
389
		Object value = taskParams.get(name);
390
		return (value != null && value instanceof FLyrRaster) ? ((FLyrRaster)value) : null;
391
	}
392
	
393
	/**
394
	 * Obtiene un par?metro extent a partir de la clave
395
	 * @param name Par?metro
396
	 * @return Par?metro
397
	 */
398
	public Extent getExtentParam(String name) {
399
		Object value = taskParams.get(name);
400
		return (value != null && value instanceof Extent) ? ((Extent)value) : null;
401
	}
402
	
403
	/*
404
	 * (non-Javadoc)
405
	 * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionResumed(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
406
	 */
407
	public void actionResumed(IncrementableEvent e) {	
408
	}
409
	
410
	/*
411
	 * (non-Javadoc)
412
	 * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionSuspended(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
413
	 */
414
	public void actionSuspended(IncrementableEvent e) {
415
	}
416
	
417
	/*
418
	 * (non-Javadoc)
419
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#isCancelable()
420
	 */
421
	public boolean isCancelable() {
422
		return true;
423
	}
424

  
425
	/*
426
	 * (non-Javadoc)
427
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#isPausable()
428
	 */
429
	public boolean isPausable() {
430
		return false;
431
	}
432
	
433
	public void dispose() {
434
		try {
435
			finalize();
436
		} catch (Throwable e) {
437
		}
438
	}
439
	
440
	/*
441
	 * (non-Javadoc)
442
	 * @see java.lang.Object#finalize()
443
	 */
444
	@Override
445
	protected void finalize() throws Throwable {
446
		incrementableTask           = null;
447
		blinker                     = null;
448
		externalActions             = null;
449
		if(taskParams != null) {
450
			taskParams.clear();
451
			taskParams = null;
452
		}
453
		log                         = null;
454
		lastLine                    = null;
455
		queueActions                = null;
456
		logger                      = null;
457
		super.finalize();
458
	}
459
}
0 460

  
org.gvsig.raster.tools/branches/org.gvsig.raster.tools_dataaccess_refactoring/org.gvsig.raster.tools.app.basic/src/main/java/org/gvsig/raster/tools/app/basic/raster/process/ClippingProcess.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.raster.process;
23

  
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.Point2D;
26
import java.io.File;
27
import java.io.IOException;
28
import java.util.ArrayList;
29
import java.util.List;
30

  
31
import org.cresques.cts.IProjection;
32
import org.gvsig.app.project.ProjectManager;
33
import org.gvsig.app.project.documents.Document;
34
import org.gvsig.app.project.documents.view.BaseViewDocument;
35
import org.gvsig.fmap.dal.DALLocator;
36
import org.gvsig.fmap.dal.DataManager;
37
import org.gvsig.fmap.dal.DataServerExplorer;
38
import org.gvsig.fmap.dal.DataServerExplorerParameters;
39
import org.gvsig.fmap.dal.coverage.RasterLibrary;
40
import org.gvsig.fmap.dal.coverage.RasterLocator;
41
import org.gvsig.fmap.dal.coverage.RasterManager;
42
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
43
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
44
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
45
import org.gvsig.fmap.dal.coverage.datastruct.Params;
46
import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
47
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
48
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
49
import org.gvsig.fmap.dal.coverage.exception.ROIException;
50
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
51
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
52
import org.gvsig.fmap.dal.coverage.process.BaseIncrementableTask;
53
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
54
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
55
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
56
import org.gvsig.fmap.dal.coverage.store.parameter.NewRasterStoreParameters;
57
import org.gvsig.fmap.dal.coverage.store.parameter.RemoteStoreParameters;
58
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
59
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
60
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
61
import org.gvsig.fmap.dal.exception.CloseException;
62
import org.gvsig.fmap.dal.exception.DataException;
63
import org.gvsig.fmap.dal.exception.InitializeException;
64
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
65
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
66
import org.gvsig.fmap.mapcontext.layers.FLayer;
67
import org.gvsig.fmap.mapcontext.layers.FLayers;
68
import org.gvsig.i18n.Messages;
69
import org.gvsig.raster.algorithm.process.DataProcess;
70
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
71
import org.gvsig.raster.mainplugin.RasterMainPluginUtils;
72
import org.gvsig.raster.roi.ROI;
73
import org.gvsig.raster.swing.RasterSwingLibrary;
74
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
75
import org.gvsig.raster.util.RasterNotLoadException;
76
/**
77
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
78
 * para aplicar un recorte a una capa y guardarlo en disco. Muestra una barra
79
 * de incremento informativa.
80
 *
81
 * @author BorSanZa - Borja S?nchez Zamorano
82
 */
83
public class ClippingProcess extends DataProcess {
84
	public static final String            PROCESS_LABEL       = "ClippingProcess";
85
	public static String                  FILENAME            = "filename";
86
	public static String                  SUFFIX              = "suffix";
87
	public static String                  VIEWNAME            = "viewname";
88
	public static String                  PX_COORDS           = "pixelcoordinates";
89
	public static String                  WORLD_COORDS        = "realcoordinates";
90
	public static String                  RASTER_STORE        = "layer";
91
	public static String                  DRAWABLE_BANDS      = "drawablebands";
92
	public static String                  ONE_LYE_PER_BAND    = "onelayerperband";
93
	public static String                  INTERP_METHOD       = "interpolationmethod";
94
	public static String                  AT                  = "affinetransform";
95
	public static String                  COLOR_INTERPR       = "colorInterpretation";
96
	public static String                  SELECTED_ROIS       = "selectedrois";
97
	public static String                  RESOLUTION          = "resolution";
98
	public static String                  DRIVER_PARAMS       = "driverparams";
99
	public static String                  VIEW_PROJ           = "viewProjection";
100
	
101
	private String                        fileName            = "";
102
	private String                        suffix              = ".tif";
103
	private RasterDataStore               dataStore           = null;
104
	private boolean                       oneLayerPerBand     = false;
105
	private int[]                         drawableBands       = { 0, 1, 2 };
106
	private double[]                      pValues             = null;
107
	private int                           interpolationMethod = Buffer.INTERPOLATION_Undefined;
108
	private String                        viewName            = "";
109
	private Params                        params              = null;
110
	private ColorInterpretation           colorInterp         = null;
111
	private ArrayList<ROI>                selectedRois        = null;
112
	private AffineTransform               affineTransform     = null;
113
	private double[]                      wcValues            = null;
114
	private RasterManager                 rManager            = RasterLocator.getManager();
115
	private BaseIncrementableTask         processIncrement    = null; 
116
	
117
	/**
118
	 * Variables de la resoluci?n de salida
119
	 */
120
	private int                           resolutionWidth     = 0;
121
	private int                           resolutionHeight    = 0;
122
	
123
	private Buffer                        buffer              = null;
124
	private IProjection                   viewProjection      = null;
125
	
126
	public static void registerParameters() {
127
		registerInputParameter(FILENAME, String.class, PROCESS_LABEL);
128
		registerInputParameter(SUFFIX, String.class, PROCESS_LABEL);
129
		registerInputParameter(VIEWNAME, String.class, PROCESS_LABEL);
130
		registerInputParameter(PX_COORDS, Double.class, PROCESS_LABEL);
131
		registerInputParameter(WORLD_COORDS, Double.class, PROCESS_LABEL);
132
		registerInputParameter(RASTER_STORE, RasterDataStore.class, PROCESS_LABEL);
133
		registerInputParameter(DRAWABLE_BANDS, Integer[].class, PROCESS_LABEL);
134
		registerInputParameter(ONE_LYE_PER_BAND, Boolean.class, PROCESS_LABEL);
135
		registerInputParameter(INTERP_METHOD, Integer.class, PROCESS_LABEL);
136
		registerInputParameter(AT, AffineTransform.class, PROCESS_LABEL);
137
		registerInputParameter(COLOR_INTERPR, ColorInterpretation.class, PROCESS_LABEL);
138
		registerInputParameter(SELECTED_ROIS, ArrayList.class, PROCESS_LABEL);
139
		registerInputParameter(RESOLUTION, Integer[].class, PROCESS_LABEL);
140
		registerInputParameter(DRIVER_PARAMS, Params.class, PROCESS_LABEL);
141
		registerInputParameter(VIEW_PROJ, IProjection.class, PROCESS_LABEL);
142
		
143
		//TODO: Falta definir salidas y asignarlas en el Map
144
		registerOutputParameter(FILENAME, String.class, PROCESS_LABEL);
145
	}
146
	
147
	/**
148
	 * Par?metros obligatorios al proceso:
149
	 * <UL>
150
	 * <LI>filename: Nombre del fichero de salida</LI>
151
	 * <LI>datawriter: Escritor de datos</LI>
152
	 * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
153
	 * <LI>pixelcoordinates: Coordenadas pixel del recorte (ulx, uly, lrx, lry)</LI>
154
	 * <LI>layer: Capa de entrada para el recorte</LI>
155
	 * <LI>drawablebands: Bandas de entrada</LI>
156
	 * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
157
	 * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
158
	 * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
159
	 * <LI>resolution: Ancho y alto de la capa de salida</LI>
160
	 * </UL> 
161
	 */
162
	@SuppressWarnings("unchecked")
163
	public void init() {
164
		fileName = getStringParam("filename");
165
		suffix = getStringParam("suffix");
166
		viewName = getStringParam("viewname");
167
		pValues = getDoubleArrayParam("pixelcoordinates");
168
		wcValues = getDoubleArrayParam("realcoordinates");
169
		dataStore = getParam("layer") != null ? (RasterDataStore)getParam("layer") : null;
170
		drawableBands = getIntArrayParam("drawablebands");
171
		oneLayerPerBand = getBooleanParam("onelayerperband");
172
		interpolationMethod = getIntParam("interpolationmethod");
173
		affineTransform = (AffineTransform)getParam("affinetransform");
174
		colorInterp = (ColorInterpretation)getParam("colorInterpretation");
175
		selectedRois = (ArrayList<ROI>)getParam("selectedrois");
176
		if(getIntArrayParam("resolution") != null) {
177
			resolutionWidth = getIntArrayParam("resolution")[0];
178
			resolutionHeight = getIntArrayParam("resolution")[1];
179
		}
180
		params = (Params) getParam("driverparams");
181
		viewProjection = getParam("viewProjection") != null ? (IProjection)getParam("viewProjection") : null;
182
	}
183

  
184
	/**
185
	 * Salva la tabla de color al fichero rmf.
186
	 * @param fName
187
	 * @throws IOException
188
	 */
189
	private void saveToRmf(String fileName) {
190
		int limitNumberOfRequests = 20;
191
		while (dataStore == null && limitNumberOfRequests > 0) {
192
			try {
193
			} catch (IndexOutOfBoundsException e) {
194
				//En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
195
				//se supone que es porque hay un refresco en el mismo momento de la petici?n por lo que como es m?s lento de
196
				//gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
197
				//haberlo cargado ya.
198
				try {
199
					Thread.sleep(200);
200
				} catch (InterruptedException e1) {
201
				}
202
			}
203
			limitNumberOfRequests--;
204
		}
205
		
206
		if (dataStore == null) {
207
			//RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
208
			return;
209
		}
210

  
211
		// Guardamos en el RMF el valor NoData
212
		if(dataStore.getNoDataValue() != null) {
213
			NoData nodata = (NoData)dataStore.getNoDataValue();
214
			nodata.setFileName(fileName);
215
			nodata.save();
216
		}
217

  
218
		// Guardamos en el RMF la tabla de color
219
		ColorTable colorTable = dataStore.getColorTable();
220
		try {
221
			rManager.getProviderServices().saveObjectToRmfFile(fileName, ColorTable.class, colorTable);
222
		} catch (RmfSerializerException e) {
223
			RasterSwingLibrary.messageBoxError("error_salvando_rmf", this, e);
224
		}
225
	}
226

  
227
	/**
228
	 * Tarea de recorte
229
	 */
230
	@SuppressWarnings("deprecation")
231
	public void process() throws ProcessInterruptedException {
232
		RasterDataStore dstoreCopy = null;
233
		RasterUtils util = RasterLocator.getManager().getRasterUtils();
234
		
235
		try {
236
			long t2;
237
			long t1 = new java.util.Date().getTime();
238

  
239
			try {
240
				Thread.sleep(1000);
241
			} catch (InterruptedException e1) {
242
				e1.printStackTrace();
243
			}
244
			
245
			insertLineLog(Messages.getText("leyendo_raster"));
246
			
247
			dstoreCopy = dataStore.newDataStore();
248
			RasterQuery query = rManager.createQuery();
249
			query.setDrawableBands(drawableBands);
250

  
251
			if(dstoreCopy.getParameters() instanceof RemoteStoreParameters &&
252
				!((RemoteStoreParameters)dstoreCopy.getParameters()).isSizeFixed()) {
253
				insertLineLog(Messages.getText("downloading_image"));
254
				((RemoteStoreParameters)dstoreCopy.getParameters()).setWidth(resolutionWidth);
255
				((RemoteStoreParameters)dstoreCopy.getParameters()).setHeight(resolutionHeight);
256
				Extent bbox = RasterLocator.getManager().getDataStructFactory().createExtent(wcValues[0], wcValues[1], wcValues[2], wcValues[3]);
257
				query.setAreaOfInterest(bbox, resolutionWidth, resolutionHeight);
258
				try {
259
					buffer = dstoreCopy.query(query);
260
				} catch (InvalidSetViewException e) {
261
					RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
262
				}
263
			} else {
264
				if(interpolationMethod != Buffer.INTERPOLATION_Undefined) {
265
					try {
266
						if(pValues != null) {
267
							if (util.isBufferTooBig(new double[] { pValues[0], pValues[3], pValues[2], pValues[1] }, drawableBands.length))
268
								query.setReadOnly(true);
269
							query.setAreaOfInterest((int)pValues[0], (int)pValues[1], (int)Math.abs(pValues[2] - pValues[0]) + 1, (int)Math.abs(pValues[3] - pValues[1]) + 1);
270
						} else if(wcValues != null) {
271
							query.setReadOnly(true);
272
							query.setAreaOfInterest(wcValues[0], wcValues[1], Math.abs(wcValues[0] - wcValues[2]), Math.abs(wcValues[1] - wcValues[3]));
273
						}
274
						buffer = dstoreCopy.query(query);
275
					} catch (InvalidSetViewException e) {
276
						RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
277
					}
278

  
279
					insertLineLog(Messages.getText("interpolando"));
280
					
281
					Buffer bufTmp = buffer;
282
					processIncrement = bufTmp.getIncrementableTask(Buffer.INCREMENTABLE_INTERPOLATION);
283
					buffer = bufTmp.getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
284
					if(bufTmp != buffer)
285
						bufTmp.dispose();
286
				} else {
287
					try {
288
						if (util.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length))
289
							query.setReadOnly(true);
290
						if(pValues != null) 
291
							query.setAreaOfInterest((int)pValues[0], (int)pValues[3], (int)Math.abs(pValues[2] - pValues[0]) + 1, (int)Math.abs(pValues[1] - pValues[3]) + 1, resolutionWidth, resolutionHeight);
292
						else if(wcValues != null) {
293
							Extent bbox = RasterLocator.getManager().getDataStructFactory().createExtent(wcValues[0], wcValues[1], wcValues[2], wcValues[3]);
294
							query.setAreaOfInterest(bbox, resolutionWidth, resolutionHeight);
295
						}
296
						buffer = dstoreCopy.query(query);
297
					} catch (InvalidSetViewException e) {
298
						RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
299
					}
300
				}
301
			}
302
			
303
			//TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
304

  
305
			if ((selectedRois != null) && (!query.isReadOnly())){
306
				if (selectedRois.size() > 0){
307
					int despX = 0;
308
					int despY = 0;
309
					if (pValues != null){
310
						despX = (int)pValues[0];
311
						despY = (int)pValues[1];
312
					} else if (wcValues != null){
313
						despX = (int)dstoreCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getX();
314
						despY = (int)dstoreCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getY();
315
					}
316
					drawOnlyROIs(buffer, selectedRois, despX, despY);
317
				}
318
			}
319
			
320
			
321
			insertLineLog(Messages.getText("salvando_imagen"));
322
			
323
			DataManager manager = DALLocator.getDataManager();
324
			String provider = "Gdal Store";
325
			DataServerExplorerParameters eparams = manager.createServerExplorerParameters("FilesystemExplorer");
326
			
327
			String finalFileName = "";
328
			NewRasterStoreParameters sparams = null;
329
			processIncrement = RasterLocator.getManager().createDataServerWriter();
330
			if (oneLayerPerBand) {
331
				long[] milis = new long[drawableBands.length];
332
				String[] fileNames = new String[drawableBands.length];
333
				for (int i = 0; i < drawableBands.length; i++) {
334
					fileNames[i] = fileName + "_B" + drawableBands[i] + suffix;
335
					
336
					int index = fileNames[i].lastIndexOf(File.separator);
337
					if(index < 0)
338
						index = fileNames[i].length();
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff