Revision 8846

View differences:

branches/v10/extensions/extGraph_predes/install/linux/resources/h_gvSIG-install.sh
1
echo Unpacking...
2
set -e
3
tail +$lcount $0 | tar -xz  --no-same-owner 
4
echo Launching instalation program....
5
cd ./_tmp_install
6
set +e
7
#export LD_LIBRARY_PATH="$PWD:$PWD/lib:$LD_LIBRARY_PATH"
8
./launcher-Linux >launcher_out 2>&1
9
res=$?
10
runOK=true
11
if [ $res -eq 1 -o $res -eq 0 ] 
12
then
13
	runOK=true
14
else
15
	runOK=false
16
	export LD_LIBRARY_PATH="$PWD:$PWD/lib:$LD_LIBRARY_PATH"
17
	./launcher-Linux > launcher_out2  2>&1
18
	res=$?
19
	if [  $res = 1 -o  $res = 0 ]
20
	then
21
		runOK=true
22
	fi
23
	
24
fi
25

  
26
if [ $runOK = false ]
27
then
28
	cat launcher_out	
29
	echo
30
	cat launcher_out2
31
	echo
32
	if grep -q 'libstdc++.so.6:' launcher_out ; then
33
		echo You need the libstdc++6 library correctly instaled in your system to use 
34
		echo the installation program.
35
		echo
36
		echo "In a debian-based distribution (if you have root privileges)"
37
		echo you can run the command:
38
		echo '    apt-get install libstdc++6'
39

  
40
	fi
41
	if grep -q 'libc.so.6:' launcher_out ; then
42
		echo You need the libc6 library correctly instaled in your system to use 
43
		echo the installation program.
44
		echo
45
		echo "In a debian-based distribution (if you have root privileges)"
46
		echo you can run the command:
47
		echo '    apt-get install libc6'
48
	fi
49
	echo
50
fi
51

  
52
cd ..
53
rm -r ./_tmp_install 2>&1 >/dev/null
54
exit 0 
0 55

  
branches/v10/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/GenerateNetworkExtension.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.graph;
42

  
43
import java.awt.Component;
44
import java.io.File;
45
import java.io.FileNotFoundException;
46
import java.util.HashMap;
47

  
48
import javax.swing.ImageIcon;
49
import javax.swing.JFileChooser;
50
import javax.swing.JOptionPane;
51

  
52
import com.iver.andami.PluginServices;
53
import com.iver.andami.messages.NotificationManager;
54
import com.iver.andami.plugins.Extension;
55
import com.iver.andami.preferences.IPreference;
56
import com.iver.andami.preferences.IPreferenceExtension;
57
import com.iver.andami.ui.mdiManager.IWindow;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.MapContext;
60
import com.iver.cit.gvsig.fmap.MapControl;
61
import com.iver.cit.gvsig.fmap.core.FShape;
62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
64
import com.iver.cit.gvsig.fmap.edition.EditionException;
65
import com.iver.cit.gvsig.fmap.edition.IWriter;
66
import com.iver.cit.gvsig.fmap.edition.ShpSchemaManager;
67
import com.iver.cit.gvsig.fmap.edition.writers.dbf.DbfWriter;
68
import com.iver.cit.gvsig.fmap.edition.writers.shp.MultiShpWriter;
69
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
70
import com.iver.cit.gvsig.fmap.layers.FLayer;
71
import com.iver.cit.gvsig.fmap.layers.FLayers;
72
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
73
import com.iver.cit.gvsig.fmap.layers.SingleLayerIterator;
74
import com.iver.cit.gvsig.geoprocess.core.fmap.GeoprocessException;
75
import com.iver.cit.gvsig.geoprocess.core.fmap.XTypes;
76
import com.iver.cit.gvsig.graph.core.writers.NetworkFileRedWriter;
77
import com.iver.cit.gvsig.graph.core.writers.NetworkGvTableWriter;
78
import com.iver.cit.gvsig.graph.gui.wizard.NetWizard;
79
import com.iver.cit.gvsig.graph.preferences.RoutePage;
80
import com.iver.cit.gvsig.project.documents.view.IProjectView;
81
import com.iver.cit.gvsig.project.documents.view.gui.IView;
82
import com.iver.cit.gvsig.project.documents.view.gui.View;
83
import com.iver.cit.gvsig.topology.lineclean.fmap.LineCleanGeoprocess;
84
import com.iver.utiles.SimpleFileFilter;
85
import com.iver.utiles.swing.threads.AbstractMonitorableTask;
86
import com.iver.utiles.swing.threads.IMonitorableTask;
87
import com.iver.utiles.swing.threads.IPipedTask;
88
import com.iver.utiles.swing.threads.PipeTask;
89

  
90

  
91
public class GenerateNetworkExtension extends Extension implements
92
		IPreferenceExtension {
93
	private static final IPreference thePreferencePage = new RoutePage();
94
	public void initialize() {
95
	}
96

  
97
	public void execute(String actionCommand) {
98
		IView view = (View) PluginServices.getMDIManager().getActiveWindow();
99
		MapControl mapControl = view.getMapControl();
100
		MapContext map = mapControl.getMapContext();
101
		FLayers tocLyrs = map.getLayers();
102
		SingleLayerIterator lyrIterator = new SingleLayerIterator(tocLyrs);
103
		while (lyrIterator.hasNext()) {
104
			FLayer lyr = lyrIterator.next();
105
			if ((lyr.isActive()) && (lyr instanceof FLyrVect)) {
106
				FLyrVect lyrVect = (FLyrVect) lyr;
107
				int shapeType;
108
				try {
109
					shapeType = lyrVect.getShapeType();
110
					if (shapeType == FShape.LINE) {
111
						if (actionCommand.equalsIgnoreCase("GENERATE_RED")) {
112
							generateRedNetwork(lyrVect, tocLyrs);
113
							return;
114
						}
115
					}
116
				} catch (DriverException e) {
117
					e.printStackTrace();
118
					NotificationManager.addError(e);
119
				}
120

  
121
			}
122
		}
123

  
124
	}
125

  
126
	private void generateNetwork(FLyrVect lyr) {
127
		NetworkGvTableWriter netBuilder = new NetworkGvTableWriter();
128
		// Por ahora, a pelo, pero hay que sacar un cuadro
129
		// de di?logo para hecer el mapping.
130
		// Tambi?n un cuadro de di?logo para seleccionar
131
		// en qu? tablas quiere escribir, y su formato
132
		// (dbf, postgres, etc)
133
		String fieldType = "tipored";
134
		String fieldDist = "length";
135
		String fieldSense = "sen";
136
		String fieldCost = "cost";
137
		try {
138
			netBuilder.setLayer(lyr);
139
			netBuilder.setFieldType(fieldType);
140
			netBuilder.setFieldDist(fieldDist);
141
			netBuilder.setFieldSense(fieldSense);
142
			netBuilder.setFieldCost(fieldCost);
143
			DbfWriter nodeWriter = new DbfWriter();
144
			nodeWriter.setFile(new File("c:/nodes.dbf"));
145

  
146
			DbfWriter edgeWriter = new DbfWriter();
147
			edgeWriter.setFile(new File("c:/edges.dbf"));
148

  
149
			netBuilder.setEdgeWriter(edgeWriter);
150
			netBuilder.setNodeWriter(nodeWriter);
151

  
152
			netBuilder.writeNetwork();
153
		} catch (DriverException e1) {
154
			// TODO Auto-generated catch block
155
			e1.printStackTrace();
156
		} catch (EditionException e1) {
157
			// TODO Auto-generated catch block
158
			e1.printStackTrace();
159
		}
160
		JOptionPane.showMessageDialog(null, PluginServices
161
				.getText(this, "done"));
162
	}
163
	
164
	class GenerateRedNetworkAfterCleanTask 
165
		extends AbstractMonitorableTask implements IPipedTask{
166
		
167
		File redFile;
168
		NetworkFileRedWriter netBuilder;
169
		
170
		FLyrVect inputLayer;
171
		FLyrVect pseudonodes;
172
		FLayers tocLyrs;
173
		
174
		/**
175
		 * Constructor
176
		 * @param tocLyrs
177
		 */
178
		GenerateRedNetworkAfterCleanTask(NetworkFileRedWriter netBuilder, FLayers tocLyrs) {
179
			this.netBuilder = netBuilder;
180
			this.tocLyrs = tocLyrs;
181
			setInitialStep(0);
182
			setDeterminatedProcess(true);
183
			setStatusMessage(PluginServices.getText(this,
184
			"Generando_red_a_partir_de_capa_lineal"));
185
		}
186

  
187
		public void run() throws Exception {
188
			int numShapes;
189
			try { 	
190
				numShapes = inputLayer.getSource().getShapeCount();
191
				// lo del 10 es para que termine despu?s de 
192
				// escribir los puntos
193
				setFinalStep(numShapes + 10);
194
				
195
				
196
			} catch (DriverIOException e) {
197
				// TODO Auto-generated catch block
198
				e.printStackTrace();
199
			}
200
			netBuilder.setLayer(inputLayer);
201
			netBuilder.setCancellableMonitorable(this);
202
			netBuilder.setRedFile(redFile);
203
			netBuilder.writeNetwork();
204
			tocLyrs.addLayer(inputLayer);
205
			tocLyrs.addLayer(pseudonodes);
206
			enableControls();
207
		}
208

  
209
		public String getNote() {
210
			String processText = PluginServices.getText(this, "Procesando_linea");
211
			String of = PluginServices.getText(this, "de");
212
			return processText + " " + getCurrentStep() + " " + of
213
					+ " " + getFinishStep();
214
		}
215

  
216
		public void cancel() {
217
			setCanceled(true);
218
		}
219
		
220
		public boolean isFinished() {
221
			return (getCurrentStep() >= getFinalStep());
222
		}
223

  
224
		/* (non-Javadoc)
225
		 * @see com.iver.utiles.swing.threads.IPipedTask#getResult()
226
		 */
227
		public Object getResult() {
228
			// TODO Auto-generated method stub
229
			return null;
230
		}
231

  
232
		/**
233
		 * Implementation of PipeTask interface
234
		 * */
235
		public void setEntry(Object object) {
236
			//The previous task of this piped task is clean geoprocess
237
			//whose result es FLayers with two layers
238
			//first layer has cleaned layer
239
			//and second layer has pseudonodes layer
240
			FLayers layers  = (FLayers) object;
241
			this.inputLayer = (FLyrVect) layers.getLayer(0);
242
			inputLayer.createSpatialIndex();
243
			this.redFile = NetworkUtils.getNetworkFile(inputLayer);
244
			this.pseudonodes = (FLyrVect) layers.getLayer(1);
245
		}
246
	}
247
	
248
	public void enableControls(){
249
		PluginServices.backgroundExecution(new Runnable(){
250
			public void run() {
251
				PluginServices.getMainFrame().enableControls();
252
				
253
			}});
254
	}
255
	
256

  
257
	class GenerateRedNetworkTask extends AbstractMonitorableTask {
258
		FLyrVect layer;
259

  
260
		File redFile;
261

  
262
		NetworkFileRedWriter netBuilder;
263
		
264
		
265

  
266
		/**
267
		 * Constructor
268
		 */
269
		GenerateRedNetworkTask(FLyrVect layer, File redFile,
270
				NetworkFileRedWriter netBuilder) {
271
			this.layer = layer;
272
			if(! layer.isSpatiallyIndexed())
273
				layer.createSpatialIndex();
274
			
275
			this.redFile = redFile;
276
			this.netBuilder = netBuilder;
277
			setInitialStep(0);
278
			int numShapes;
279
			try {
280
				numShapes = layer.getSource().getShapeCount();
281
				// lo del 10 es porque escribimos los nodos despu?s de
282
				// los tramos.
283
				setFinalStep(numShapes + 10);
284
				setDeterminatedProcess(true);
285
				setStatusMessage(PluginServices.getText(this,
286
						"Generando_red_a_partir_de_capa_lineal"));
287
			} catch (DriverIOException e) {
288
				// TODO Auto-generated catch block
289
				e.printStackTrace();
290
			}
291

  
292
		}
293

  
294
		public void run() throws Exception {
295
			netBuilder.setLayer(layer);
296
			netBuilder.setCancellableMonitorable(this);
297
			netBuilder.setRedFile(redFile);
298
			netBuilder.writeNetwork();
299
			enableControls();
300
		}
301

  
302
		public String getNote() {
303
			String processText = PluginServices.getText(this, "Procesando_linea");
304
			String of = PluginServices.getText(this, "de");
305
			return processText + " " + getCurrentStep() + " " + of
306
					+ " " + getFinishStep();
307
		}
308

  
309
		public void cancel() {
310
			setCanceled(true);
311
		}
312
		
313
		public Object getResult(){
314
			return null;
315
		
316
		}
317
		public void setEntry(Object object){
318
			this.layer = (FLyrVect) object;
319
		}
320
	}
321

  
322
	/**
323
	 * It returns a geoprocess to make a CLEAN of the input layer 
324
	 * */
325
	private LineCleanGeoprocess createCleanGeoprocess(FLyrVect lineLyr) {
326
		 File outputFile = null;
327
		 JOptionPane.showMessageDialog(null,
328
				PluginServices.getText(null, "Especifique_fichero_shp_resultante"),
329
				PluginServices.getText(null, "Fichero_para_capa_corregida"),
330
				JOptionPane.INFORMATION_MESSAGE);
331
		 JFileChooser jfc = new JFileChooser();
332
		SimpleFileFilter filterShp = new SimpleFileFilter("shp", PluginServices
333
				.getText(this, "shp_files"));
334
		jfc.setFileFilter(filterShp);
335
		if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
336
			File newFile = jfc.getSelectedFile();
337
			String path = newFile.getAbsolutePath();
338
			if (newFile.exists()) {
339
				int resp = JOptionPane.showConfirmDialog(
340
						(Component) PluginServices.getMainFrame(),
341
						PluginServices.getText(this,
342
								"fichero_ya_existe_seguro_desea_guardarlo"),
343
						PluginServices.getText(this, "guardar"),
344
						JOptionPane.YES_NO_OPTION);
345
				if (resp != JOptionPane.YES_OPTION) {
346
					return null;
347
				}
348
			}// if
349
			if (!(path.toLowerCase().endsWith(".shp"))) {
350
				path = path + ".shp";
351
			}
352
			outputFile = new File(path);
353
		} else {
354
			return null;
355
		}
356
		LineCleanGeoprocess geoprocess = new LineCleanGeoprocess(lineLyr);
357
		SHPLayerDefinition definition = (SHPLayerDefinition) geoprocess
358
				.createLayerDefinition();
359
		definition.setFile(outputFile);
360
		ShpSchemaManager schemaManager = new ShpSchemaManager(outputFile
361
				.getAbsolutePath());
362
		IWriter writer = null;
363
		try {
364
			int shapeType = definition.getShapeType();
365
			if (shapeType != XTypes.MULTI) {
366
				writer = new ShpWriter();
367
				((ShpWriter) writer).setFile(definition.getFile());
368
				writer.initialize(definition);
369
			} else {
370
				writer = new MultiShpWriter();
371
				((MultiShpWriter) writer).setFile(definition.getFile());
372
				writer.initialize(definition);
373
			}
374
		} catch (Exception e1) {
375
			String error = PluginServices.getText(this,
376
					"Error_escritura_resultados");
377
			String errorDescription = PluginServices.getText(this,
378
					"Error_preparar_escritura_resultados");
379
			return null;
380
		}
381
		geoprocess.setResultLayerProperties(writer, schemaManager);
382
		HashMap params = new HashMap();
383
		params.put("layer_selection", new Boolean(false));
384
		try {
385
			geoprocess.setParameters(params);
386
			geoprocess.checkPreconditions();
387
			return geoprocess;
388
			
389
		} catch (GeoprocessException e) {
390
			String error = PluginServices.getText(this, "Error_ejecucion");
391
			String errorDescription = PluginServices.getText(this,
392
					"Error_fallo_geoproceso");
393
			return null;
394
		}
395

  
396
	}
397

  
398
	private void generateRedNetwork(FLyrVect lyr, FLayers tocLyrs) {
399
		lyr.createSpatialIndex();
400
		NetworkFileRedWriter netBuilder = new NetworkFileRedWriter();
401
		// Por ahora, a pelo, pero hay que sacar un cuadro
402
		// de di?logo para hecer el mapping.
403
		// Tambi?n un cuadro de di?logo para seleccionar
404
		// en qu? tablas quiere escribir, y su formato
405
		// (dbf, postgres, etc)
406

  
407
		ImageIcon icon = new ImageIcon(this.getClass().getClassLoader()
408
				.getResource("images/net-wizard-logo.jpg"));
409

  
410
		NetWizard wiz = new NetWizard(icon, lyr);
411
		PluginServices.getMDIManager().addWindow(wiz);
412
		if (!wiz.wasFinishPressed())
413
			return;
414
		// try {
415
		String fieldType = wiz.getFieldType();
416
		String fieldLength = wiz.getFieldLength();
417
		String fieldCost = wiz.getFieldCost();
418
		String fieldSense = wiz.getFieldSense();
419
		netBuilder.setLayer(lyr);
420
		netBuilder.setFieldType(fieldType);
421
		netBuilder.setFieldDist(fieldLength);
422
		netBuilder.setFieldSense(fieldSense);
423
		netBuilder.setFieldCost(fieldCost);
424
		File redFile = NetworkUtils.getNetworkFile(lyr);
425

  
426
		boolean cleanOrigLyr = wiz.getCleanOriginalLayer();
427
		LineCleanGeoprocess clean = null;
428
		if(cleanOrigLyr)
429
			clean = createCleanGeoprocess(lyr);
430
		boolean applySnap = wiz.getApplySnapTolerance();
431
		if(applySnap){
432
			double snapTolerance = wiz.getSnapTolerance();
433
			netBuilder.setSnapTolerance(snapTolerance);
434
		}	
435
		if(clean != null){
436
			//we wont start the process of network creation
437
			//until clean geoprocess will be finished
438
			IPipedTask cleanTask = (IPipedTask) clean.createTask();
439
			GenerateRedNetworkAfterCleanTask task = 
440
				new GenerateRedNetworkAfterCleanTask(netBuilder, tocLyrs);
441
			
442
			PipeTask pipe = new PipeTask(cleanTask, (IPipedTask)task);
443
			
444
			PluginServices.cancelableBackgroundExecution(pipe);
445
//			PluginServices.cancelableBackgroundExecution(task);
446
			
447
		}else{
448
			GenerateRedNetworkTask task = new GenerateRedNetworkTask(lyr, redFile,
449
					netBuilder);
450
			PluginServices.cancelableBackgroundExecution(task);
451
		}
452
	}
453

  
454
	public boolean isEnabled() {
455
		return true;
456
	}
457

  
458
	public boolean isVisible() {
459
		IWindow f = PluginServices.getMDIManager().getActiveWindow();
460

  
461
		if (f == null) {
462
			return false;
463
		}
464

  
465
		if (f instanceof View) {
466
			View vista = (View) f;
467
			IProjectView model = vista.getModel();
468
			MapContext mapa = model.getMapContext();
469
			FLayer[] activeLayers = mapa.getLayers().getActives();
470
			if (activeLayers.length > 0)
471
				if (activeLayers[0] instanceof FLyrVect) {
472
					FLyrVect lyrVect = (FLyrVect) activeLayers[0];
473
					int shapeType;
474
					try {
475
						shapeType = lyrVect.getShapeType();
476
						if (shapeType == FShape.LINE)
477
							return true;
478
					} catch (DriverException e) {
479
						// TODO Auto-generated catch block
480
						e.printStackTrace();
481
					}
482
				}
483
		}
484
		return false;
485

  
486
	}
487

  
488
	public IPreference getPreferencesPage() {
489
		return thePreferencePage;
490
	}
491

  
492
}
0 493

  
branches/v10/extensions/extGraph_predes/src/com/iver/cit/gvsig/graph/core/writers/NetworkFileRedWriter.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.graph.core.writers;
42

  
43
import java.io.File;
44
import java.io.FileNotFoundException;
45
import java.io.IOException;
46
import java.io.RandomAccessFile;
47
import java.nio.ByteOrder;
48
import java.sql.Types;
49
import java.util.ArrayList;
50
import java.util.Hashtable;
51

  
52
import javax.imageio.stream.FileImageOutputStream;
53

  
54
import org.cresques.cts.ICoordTrans;
55

  
56
import com.hardcode.gdbms.engine.values.NumericValue;
57
import com.hardcode.gdbms.engine.values.ValueFactory;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.core.FShape;
60
import com.iver.cit.gvsig.fmap.core.IGeometry;
61
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
62
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
63
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
64
import com.iver.cit.gvsig.fmap.edition.EditionException;
65
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
66
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
67
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
68
import com.iver.cit.gvsig.graph.core.NodeGv;
69
import com.iver.cit.gvsig.util.SnappingCoordinateMap;
70
import com.iver.utiles.swing.threads.CancellableMonitorable;
71
import com.vividsolutions.jts.geom.Coordinate;
72
import com.vividsolutions.jts.geom.Geometry;
73

  
74
/**
75
 * @author fjp
76
 *
77
 * 
78
 */
79
public class NetworkFileRedWriter extends AbstractNetworkWriter {
80
	File redFile;
81
	CancellableMonitorable cancel;
82
	private double snapTolerance = 0d;
83
	public NetworkFileRedWriter() {
84
		
85
		// Set up fields for table nodes
86
		nodeFields = new FieldDescription[3];
87
		FieldDescription fieldNodeId = new FieldDescription();
88
		fieldNodeId.setFieldName("NODEID");
89
		fieldNodeId.setFieldType(Types.INTEGER);
90

  
91
		FieldDescription fieldX = new FieldDescription();
92
		fieldX.setFieldName("X");
93
		fieldX.setFieldType(Types.DOUBLE);
94
		fieldX.setFieldDecimalCount(2);
95

  
96
		FieldDescription fieldY = new FieldDescription();
97
		fieldY.setFieldName("Y");
98
		fieldY.setFieldType(Types.DOUBLE);
99
		fieldY.setFieldDecimalCount(2);
100
		
101
		nodeFields[0] = fieldNodeId;
102
		nodeFields[1] = fieldX;
103
		nodeFields[2] = fieldY;
104

  
105
		
106
		// Set up fields for table edges
107
		edgeFields = new FieldDescription[7];
108

  
109
		// ID_TRAMO ORIGINAL!!!
110
		FieldDescription fieldArcID = new FieldDescription();
111
		fieldArcID.setFieldName("ArcID");
112
		fieldArcID.setFieldType(Types.INTEGER);
113

  
114
		FieldDescription fieldDirection = new FieldDescription();
115
		fieldDirection.setFieldName("Direction");
116
		fieldDirection.setFieldType(Types.SMALLINT);
117
		
118
		FieldDescription fieldNodeOrigin = new FieldDescription();
119
		fieldNodeOrigin.setFieldName("NodeOrigin");
120
		fieldNodeOrigin.setFieldType(Types.INTEGER);
121
		FieldDescription fieldNodeEnd = new FieldDescription();
122
		fieldNodeEnd.setFieldName("NodeEnd");
123
		fieldNodeEnd.setFieldType(Types.INTEGER);
124

  
125
		FieldDescription fieldType = new FieldDescription();
126
		fieldType.setFieldName("Type");
127
		fieldType.setFieldType(Types.SMALLINT);
128

  
129
		FieldDescription fieldDistanceDist = new FieldDescription();
130
		fieldDistanceDist.setFieldName("Dist");
131
		fieldDistanceDist.setFieldType(Types.DOUBLE);
132
		
133
		FieldDescription fieldDistanceCost = new FieldDescription();
134
		fieldDistanceCost.setFieldName("Cost");
135
		fieldDistanceCost.setFieldType(Types.DOUBLE);
136
		
137
		edgeFields[0] = fieldArcID;
138
		edgeFields[1] = fieldDirection;
139
		edgeFields[2] = fieldNodeOrigin;
140
		edgeFields[3] = fieldNodeEnd;
141
		edgeFields[4] = fieldType;
142
		edgeFields[5] = fieldDistanceDist;
143
		edgeFields[6] = fieldDistanceCost;
144
	}
145

  
146
	/* (non-Javadoc)
147
	 * @see com.iver.cit.gvsig.graph.core.INetworkWriter#writeNetwork(boolean)
148
	 */
149
	public void writeNetwork() throws EditionException {
150
		// PRIMERO VAN EL NUMERO DE TRAMOS, LUEGO EL NUMERO DE ARCOS Y LUEGO
151
		// EL NUMERO DE NODOS, DESPUES
152
		// IDTRAMO-SENTIDO_DIGITALIZACION-IDNODOORIGEN-IDNODODESTINO-TIPOTRAMO-DISTANCIA
153
		// Y POR FIN
154
		// IDNODO-Xdouble-Ydouble
155

  
156
		// El campo sentido indica //3-> Doble sentido, 1-> seg?n viene, 2
157
		// -> al rev?s, cualquier otro valor-> No hay arco
158
		// TipoTamo va a ser un campo num?rico, entero.
159
		// 0-> Autopista.
160
		// 1-> Autov?a.
161
		// 2-> Nacional.
162
		// 3-> Nacional - Comarcal.
163
		// 4-> Comarcal.
164
		// 5-> Otras.
165
		// 6-> Ferry.
166
		// 7-> Conexiones
167
		// Los nombres son orientativos. Basta saber que puede haber hasta X
168
		// tipos distintos de tramos, cada uno
169
		// con su velocidad. Esa velocidad se fijar? en la funci?n
170
		// FijaVelocidades. OJO, empezar siempre desde el 0
171

  
172
		double distance, cost;
173
		short arcType;
174
		int direction;
175
		int i;
176
		int idNodo1, idNodo2, nodeCount, edgeCount;
177
		short sentidoDigit; // => 1 en esa direcci?n. 0=> Al contrario. SOLO
178
		// SE UTILIZA PARA LOS CALCULOS POR IDTRAMO Y
179
		// PORCENTAJE
180
		// PARA SABER SI EST? M?S CERCA DE UN NODO O DEL OTRO.
181
		Hashtable nodeHash = null;
182
		if(snapTolerance != 0d)
183
			nodeHash = new SnappingCoordinateMap(snapTolerance);
184
		else
185
			nodeHash = new Hashtable();
186
		ArrayList nodes = new ArrayList();
187

  
188
		try {
189
			if (lyr.getShapeType() != FShape.LINE) {
190
				return;
191
			}
192
			RandomAccessFile file = new RandomAccessFile(redFile.getPath(),
193
					"rw");
194
			FileImageOutputStream output = new FileImageOutputStream(file);
195
//			FileChannel channel = file.getChannel();
196
//			MappedByteBuffer buf = channel.map(MapMode.READ_WRITE, 0,
197
//					16 * 1024);
198
//			buf.order(ByteOrder.LITTLE_ENDIAN);
199
			output.setByteOrder(ByteOrder.LITTLE_ENDIAN);
200

  
201
			nodeCount = 0;
202
			VectorialAdapter adapter = (VectorialAdapter) lyr.getSource();
203
			int numTramos;
204
			
205
			ICoordTrans ct = lyr.getCoordTrans();
206

  
207
			numTramos = adapter.getShapeCount();
208
			// Cambiamos otra vez: Escribimos primero el n? de tramos. Luego va
209
			// el n? de arcos y el de nodos.
210
			// buf.putInt(numTramos);
211
			output.writeInt(numTramos);
212
			// /////// Cambiamos el formato: primero van los arcos y luego los
213
			// nodos
214
			// file.writeInt(0);
215
			output.writeInt(0);
216
			// OJO: El numero de arcos todav?a no lo sabemos, habr? que volver
217
			// luego y escribir el numero correcto. Es por lo de los sentidos.
218
			// Metemos 2 arcos si es doble sentido, y uno si es de un solo
219
			// sentido
220

  
221
			// Guardamos un long. Luego volveremos aqu? y grabaremos el n? de
222
			// nodos
223
			// file.writeInt(0);
224
			output.writeInt(numTramos);
225
			// AHORA METEMOS LOS NOMBRES DE LOS CAMPOS. EN EL CARGA RED LOS
226
			// USAREMOS PARA LEER DEL DBF.
227

  
228
			edgeCount = 0;
229

  
230
			SelectableDataSource sds = lyr.getRecordset();
231
			int senseFieldIndex = -1;
232
			int distFieldIndex = -1;
233
			int typeFieldIndex = -1;
234
			int costFieldIndex = -1;
235
			
236
			if (fieldSense != null)
237
				senseFieldIndex = sds.getFieldIndexByName(fieldSense);
238
			if (fieldDist != null)
239
				distFieldIndex = sds.getFieldIndexByName(fieldDist);
240
			if (fieldType != null)
241
				typeFieldIndex = sds.getFieldIndexByName(fieldType);
242
			if (fieldCost != null)
243
				costFieldIndex = sds.getFieldIndexByName(fieldCost);
244

  
245
	        DriverAttributes attr = adapter.getDriverAttributes();
246
	        boolean bMustClone = false;
247
	        if (attr != null)
248
	        {
249
	            if (attr.isLoadedInMemory())
250
	            {
251
	                bMustClone = attr.isLoadedInMemory();               
252
	            }
253
	        }
254

  
255
			
256
			NumericValue valAux = null;
257
			for (i = 0; i < numTramos; i++) {
258
				IGeometry geom = adapter.getShape(i);
259
				if (ct != null)
260
				{
261
	                if (bMustClone)
262
	                    geom = geom.cloneGeometry();
263
	                geom.reProject(ct);
264

  
265
				}
266
				Geometry jtsGeom = geom.toJTSGeometry();
267
				Coordinate[] coords = jtsGeom.getCoordinates();
268
				Coordinate c1 = coords[0];
269
				Coordinate c2 = coords[coords.length - 1];
270
				
271
				NodeGv nodeAux;
272
				if (!nodeHash.containsKey(c1)) // No est?.
273
				{
274
					idNodo1 = nodeCount++;
275
					nodeAux = new NodeGv(c1, idNodo1);
276
					nodeHash.put(c1, nodeAux);
277
					nodes.add(nodeAux);
278
				} else {
279
					nodeAux = (NodeGv) nodeHash.get(c1);
280
				}
281
				idNodo1 = nodeAux.getId().intValue();
282

  
283
				if (!nodeHash.containsKey(c2)) // No est?.
284
				{
285
					idNodo2 = nodeCount++;
286
					nodeAux = new NodeGv(c2, idNodo2);
287
					nodeHash.put(c2, nodeAux);
288
					nodes.add(nodeAux);
289

  
290
				} else {
291
					nodeAux = (NodeGv) nodeHash.get(c2);
292
				}
293
				idNodo2 = nodeAux.getId().intValue();
294

  
295
				if (typeFieldIndex != -1)
296
					valAux = (NumericValue) sds.getFieldValue(i, typeFieldIndex);
297
				else
298
					valAux = ValueFactory.createValue(0); // no hay tipo
299
				arcType = valAux.shortValue();
300
				// TipoTramo = DBFReadIntegerAttribute(hDBF, i, indiceCampo1);
301
				
302
				if (distFieldIndex != -1)
303
					valAux = (NumericValue) sds.getFieldValue(i, distFieldIndex);
304
				else
305
					valAux = ValueFactory.createValue(jtsGeom.getLength());
306
				distance = valAux.floatValue();
307
				// Distancia = (float) DBFReadDoubleAttribute(hDBF, i,
308
				// indiceCampo2);
309
				if (costFieldIndex != -1)
310
				{
311
					valAux = (NumericValue) sds.getFieldValue(i, costFieldIndex);
312
					cost = valAux.doubleValue();
313
				}
314
				else
315
					cost = distance;
316
				
317
				
318

  
319
				direction = -1;
320

  
321
				if (senseFieldIndex == -1)
322
					direction = 3; // 3-> Doble sentido, 1-> seg?n viene, 2 ->
323
				// al rev?s, cualquier otro valor-> No hay
324
				// arco
325
				else {
326
					valAux = (NumericValue) sds.getFieldValue(i,
327
							senseFieldIndex);
328
					direction = valAux.shortValue();
329
				}
330

  
331
				if (direction == 3) {
332
					sentidoDigit = 1; // En esa direcci?n
333
					writeEdge(output, i, sentidoDigit, idNodo1, idNodo2, arcType,
334
							distance, cost);
335
					edgeCount++;
336

  
337
					sentidoDigit = 0;
338
					writeEdge(output, i, sentidoDigit, idNodo2, idNodo1, arcType,
339
							distance, cost);
340
					edgeCount++;
341

  
342
				}
343
				if (direction == 1) {
344
					sentidoDigit = 1; // En esa direcci?n
345
					writeEdge(output, i, sentidoDigit, idNodo1, idNodo2, arcType,
346
							distance, cost);
347
					edgeCount++;
348
				}
349
				if (direction == 2) {
350
					sentidoDigit = 0;
351
					writeEdge(output, i, sentidoDigit, idNodo2, idNodo1, arcType,
352
							distance, cost);
353
					edgeCount++;
354

  
355
				}
356
				
357
				if(cancel != null){
358
					cancel.reportStep();
359
					
360
				}
361
			}//for
362

  
363

  
364
			for (int j=0; j < nodes.size(); j++) {
365
				NodeGv node = (NodeGv) nodes.get(j);
366
				output.writeInt(node.getId().intValue());
367
				output.writeDouble(node.getCoordinate().x);
368
				output.writeDouble(node.getCoordinate().y);
369
			}
370

  
371
			output.seek(0);
372
			// buf.position(0);
373
			output.writeInt(numTramos);
374
			output.writeInt(edgeCount);
375
			output.writeInt(nodes.size());
376

  
377
			// buf.force();
378
			output.close();
379
			file.close();
380
			
381
			cancel.setCurrentStep(cancel.getFinalStep());
382

  
383
			return ;
384
		} catch (DriverIOException e) {
385
			e.printStackTrace();
386
		} catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
387
			e.printStackTrace();
388
			throw new EditionException(e);
389
		} catch (FileNotFoundException e) {
390
			e.printStackTrace();
391
			throw new EditionException(e);
392
		} catch (IOException e) {
393
			e.printStackTrace();
394
			throw new EditionException(e);
395
		} catch (DriverException e) {		
396
			e.printStackTrace();
397
			throw new EditionException(e);
398
		}
399
	}
400

  
401

  
402
	public void setCancellableMonitorable(CancellableMonitorable cancel) {
403
		this.cancel = cancel;
404
		
405
	}
406

  
407
	public void setRedFile(File redFile) {
408
		this.redFile = redFile;
409
		
410
	}
411

  
412
	private void writeEdge(FileImageOutputStream output, int id, short sense,
413
			int idNodeOrig, int idNodeEnd, short tipoTramo, double dist, double cost)
414
			throws IOException {
415
		output.writeInt(id);
416
		output.writeInt(sense);
417

  
418
		output.writeInt(idNodeOrig);
419
		output.writeInt(idNodeEnd);
420
		output.writeInt(tipoTramo);
421
		output.writeDouble(dist);
422
		output.writeDouble(cost);
423

  
424
	}
425

  
426
	public void setSnapTolerance(double snapTolerance) {
427
		this.snapTolerance = snapTolerance;
428
	}
429

  
430
}
0 431

  
branches/v10/extensions/extGraph_predes/src/com/iver/cit/gvsig/project/documents/view/legend/gui/FThemeManagerWindow.java
1
package com.iver.cit.gvsig.project.documents.view.legend.gui;
2

  
3
import java.awt.BorderLayout;
4
import java.awt.Component;
5
import java.awt.event.ActionEvent;
6
import java.awt.event.ActionListener;
7
import java.io.File;
8
import java.io.FileNotFoundException;
9
import java.io.FileReader;
10
import java.io.FileWriter;
11
import java.text.NumberFormat;
12
import java.text.ParseException;
13

  
14
import javax.swing.JButton;
15
import javax.swing.JDialog;
16
import javax.swing.JFileChooser;
17
import javax.swing.JOptionPane;
18
import javax.swing.JPanel;
19
import javax.swing.JTabbedPane;
20

  
21
import org.exolab.castor.xml.MarshalException;
22
import org.exolab.castor.xml.Marshaller;
23
import org.exolab.castor.xml.ValidationException;
24

  
25
import com.hardcode.gdbms.engine.data.DataSource;
26
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
27
import com.iver.andami.PluginServices;
28
import com.iver.andami.messages.NotificationManager;
29
import com.iver.andami.ui.mdiManager.IWindow;
30
import com.iver.andami.ui.mdiManager.WindowInfo;
31
import com.iver.cit.gvsig.fmap.DriverException;
32
import com.iver.cit.gvsig.fmap.MapContext;
33
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
34
import com.iver.cit.gvsig.fmap.layers.FLayer;
35
import com.iver.cit.gvsig.fmap.layers.FLayers;
36
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
37
import com.iver.cit.gvsig.fmap.layers.XMLException;
38
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
39
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
40
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegend;
41
import com.iver.cit.gvsig.fmap.rendering.Legend;
42
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
43
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
44
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
45
import com.iver.cit.gvsig.gui.panels.LinkPanel;
46
import com.iver.cit.gvsig.project.documents.view.IProjectView;
47
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
48
import com.iver.cit.gvsig.project.documents.view.legend.scale.gui.FPanelScaleManager;
49
import com.iver.utiles.GenericFileFilter;
50
import com.iver.utiles.XMLEntity;
51
import com.iver.utiles.swing.threads.IMonitorableTask;
52
import com.iver.utiles.xmlEntity.generate.XmlTag;
53

  
54
/**
55
 * @author jmorell (jose.morell@gmail.com)
56
 * @version 24-ene-2005
57
 */
58
public final class FThemeManagerWindow extends AbstractPanel implements IWindow {
59
	private MapContext mapContext;
60
	private FLayer layer;
61
    private Legend renderer; // Le asignaremos la leyenda del primer tema activo.
62
	private FPanelScaleManager fPanelScaleManager;
63
    private FPanelLegendManager fPanelLegendManager;
64
    private LinkPanel linkPanel;
65
    private JTabbedPane organizador = new JTabbedPane();  //  @jve:decl-index=0:
66
    private ComandosListener m_actionListener = new ComandosListener(this);
67
	//private ProjectView view;
68
	private NumberFormat nf = NumberFormat.getInstance();
69

  
70
    /**
71
     * Creates new form JPanel
72
     */
73
    public FThemeManagerWindow() {
74
        initialize();
75
		this.setSize(650, 420);
76
    }
77

  
78
    /**
79
     * Sobrecarga del constructor. Este se utiliza cuando se llama a este
80
     * di?logo desde la barra de comandos.
81
     *
82
     */
83
    public FThemeManagerWindow(FLayer l, MapContext fMap) {
84
    	initialize();
85
    	layer = l;
86
    	mapContext = fMap;
87
		try {
88
			ClassifiableVectorial aux = (ClassifiableVectorial) layer;
89
			renderer = (Legend) aux.getLegend().cloneLegend();
90
			fPanelScaleManager.setMapContext(mapContext);
91
			fPanelLegendManager.setMapContext(mapContext);
92
		} catch (XMLException e) {
93
			// TODO Auto-generated catch block
94
			e.printStackTrace();
95
		} catch (DriverException e1) {
96
			// TODO Auto-generated catch block
97
			e1.printStackTrace();
98
		}
99

  
100
        fPanelScaleManager.setLayer(layer, renderer);
101
        fPanelLegendManager.setLayer(layer, renderer);
102

  
103
        organizador.setSelectedIndex(0);
104

  
105
		this.setSize(650, 420);
106
    }
107

  
108
	/**
109
	 * This method initializes this
110
	 *
111
	 * @return void
112
	 */
113
	private  void initialize() {
114

  
115
		fPanelScaleManager = new FPanelScaleManager();
116
		fPanelLegendManager = new FPanelLegendManager();
117

  
118
		organizador.addTab(PluginServices.getText(this,"General"), fPanelScaleManager);
119
		organizador.addTab(PluginServices.getText(this,"Simbologia"), fPanelLegendManager);
120

  
121
        JPanel panelButtons = new JPanel();
122

  
123
        JButton btnAceptar = new JButton(PluginServices.getText(this,"Aceptar"));
124
        btnAceptar.setActionCommand("OK");
125
        btnAceptar.addActionListener(m_actionListener);
126

  
127
        JButton btnApply = new JButton(PluginServices.getText(this,"Aplicar"));
128
        btnApply.setActionCommand("APPLY");
129
        btnApply.addActionListener(m_actionListener);
130

  
131
        JButton btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
132
        btnSaveLegend.setActionCommand("SAVE_LEGEND");
133
        btnSaveLegend.addActionListener(m_actionListener);
134

  
135
        JButton btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
136
        btnLoadLegend.setActionCommand("LOAD_LEGEND");
137
        btnLoadLegend.addActionListener(m_actionListener);
138

  
139
        JButton btnCancelar = new JButton(PluginServices.getText(this,"Cerrar"));
140
        btnCancelar.setActionCommand("CANCEL");
141
        btnCancelar.addActionListener(m_actionListener);
142

  
143
        panelButtons.add(btnApply, null);
144

  
145
		setLayout(new BorderLayout());
146
		panelButtons.setLayout(null);
147
		organizador.setPreferredSize(new java.awt.Dimension(640,390));
148
		btnAceptar.setBounds(9, 5, 89, 23);
149
		btnApply.setBounds(107, 5, 89, 23);
150
		btnSaveLegend.setBounds(205, 5, 159, 23);
151
		btnLoadLegend.setBounds(373, 5, 159, 23);
152
		btnCancelar.setBounds(541, 5, 89, 23);
153
		panelButtons.setPreferredSize(new java.awt.Dimension(493,33));
154
		add(organizador, java.awt.BorderLayout.NORTH);
155
		panelButtons.add(btnAceptar, null);
156
		add(panelButtons, java.awt.BorderLayout.SOUTH);
157
		panelButtons.add(btnSaveLegend, null);
158
		panelButtons.add(btnLoadLegend, null);
159
		panelButtons.add(btnCancelar, null);
160
	}
161

  
162

  
163

  
164
    /**
165
     * En esta funci?n se coge el primer tema activo del TOC y se usa su
166
     * renderer para inicializar. Hay que llamarla SIEMPRE que se abra el
167
     * cuadro de di?logo, en el  openLegendManager() de la vista.
168
     *
169
     * @param mapContext TOC que abre este cuadro de di?logo.
170
     * @throws DriverException
171
     */
172
    public void setMapContext(MapContext mapContext) throws DriverException {
173
        this.mapContext = mapContext;
174
        layer = getFirstActiveLayerVect(mapContext.getLayers());
175
		try {
176
			ClassifiableVectorial aux = (ClassifiableVectorial) layer;
177
			renderer = (Legend) aux.getLegend().cloneLegend();
178
		} catch (XMLException e) {
179
			// TODO Auto-generated catch block
180
			e.printStackTrace();
181
		}
182
		fPanelScaleManager.setMapContext(mapContext);
183
		fPanelLegendManager.setMapContext(mapContext);
184
        actualizar();
185
    }
186

  
187
    /**
188
     * DOCUMENT ME!
189
     */
190
    private void actualizar() {
191
    	FLayer lyrSelected = getFirstActiveLayerVect(mapContext.getLayers());
192

  
193
        fPanelScaleManager.setLayer(lyrSelected, renderer);
194
        fPanelLegendManager.setLayer(lyrSelected, renderer);
195

  
196
        organizador.setSelectedIndex(0);
197
    }
198

  
199
    private void btnApply_actionPerformed(ActionEvent evt) {
200
       // ClassifiableVectorial aux = (ClassifiableVectorial) layer;
201

  
202
    	switch (fPanelLegendManager.getVisibleCard()) {
203
        case 0: // default symbol
204
            renderer = fPanelLegendManager.getM_defaultLegendPanel().getLegend();
205
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + PluginServices.getText(this,"_(Simbolo_unico)"));
206
            break;
207
        case 1: // Unique Values
208
            renderer = fPanelLegendManager.getM_valuesLegendPanel().getLegend();
209
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Valores_unicos)");
210
            break;
211
        case 2:// break values
212
           	renderer = fPanelLegendManager.getM_breaksLegendPanel().getLegend();
213
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Intervalos)");
214
           	break;
215
        case 3://text
216
        	fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Etiquetas_estandar)");
217
        case 4://
218
        	renderer = fPanelLegendManager.getPanelDotDensityLegend().getLegend();
219
        	break;
220
        }
221
        // System.out.println("Color punto 1 " + renderer.getDefaultSymbol().getColor().toString());
222
    	// fPanelLegendManager.getM_labelsLegendPanel().setFSymbol(renderer.getDefaultSymbol());
223
    	// boolean bShapesVisibles = renderer.getDefaultSymbol().isShapeVisible();
224
    	fPanelLegendManager.getM_labelsLegendPanel().updateValuesFromControls((VectorialLegend)renderer);
225
    	// renderer.getDefaultSymbol().setShapeVisible(bShapesVisibles);
226
        // System.out.println("Color punto 2 " + renderer.getDefaultSymbol().getColor().toString());
227
        try {
228
			// Intentamos aplicar la leyenda a todas
229
            // las capas activas a las que se les pueda aplicar
230
            FLayer[] activeLyrs =  mapContext.getLayers().getActives();
231
            for (int i=0; i < activeLyrs.length; i++)
232
            {
233
            	FLayer laux=activeLyrs[i];
234
            	if (activeLyrs[i] instanceof FLayers){
235
            		laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
236
            	}
237
                if (laux instanceof ClassifiableVectorial)
238
                {
239
                    ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
240
                    if (renderer instanceof ClassifiedLegend)
241
                    {
242
                        // Es una leyenda que necesita un recordset con un
243
                        // nombre de campo. Comprobamos que ese recordset
244
                        // tiene ese nombre de campo y es del tipo esperado
245
                        ClassifiedLegend cl = (ClassifiedLegend) renderer;
246
                        if (aux2 instanceof AlphanumericData)
247
                        {
248
                            DataSource rs = ((AlphanumericData) aux2).getRecordset();
249
                            if (cl.getValues().length==0) {
250
                            	JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
251
                            	return;
252
                            }
253
                            int idField = rs.getFieldIndexByName(cl.getFieldName());
254
                            if (idField != -1)
255
                            {
256
                                //TODO: Aqu? deber?amos comprobar si el tipo de campo
257
                                // es el tipo de campo esperado.
258
                            	/*if (renderer instanceof VectorialUniqueValueLegend){
259
                            		((VectorialUniqueValueLegend)renderer).setLabelHeightField(null);
260
                            		((VectorialUniqueValueLegend)renderer).setLabelRotationField(null);
261
                            	}
262
                            	*/
263
                                aux2.setLegend((VectorialLegend) renderer);
264
                            }
265

  
266
                        }
267
                    }
268
                    else if (renderer instanceof SingleSymbolLegend)
269
                        aux2.setLegend((VectorialLegend) renderer);
270
                }
271

  
272
            }
273
			// aux.setLegend((VectorialLegend) m_Renderer);
274

  
275
		} catch (FieldNotFoundException e) {
276
			// TODO Auto-generated catch block
277
			e.printStackTrace();
278
		} catch (DriverException e) {
279
			// TODO Auto-generated catch block
280
			e.printStackTrace();
281
		} catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
282
            // TODO Auto-generated catch block
283
            e.printStackTrace();
284
        }
285

  
286
		if (fPanelScaleManager.getJRadioButton1().isSelected()) {
287
			try
288
			{
289
				layer.setMinScale((nf.parse(fPanelScaleManager.getJTextField1().getText())).doubleValue());
290
			}
291
			catch (ParseException ex)
292
			{
293
			    if (fPanelScaleManager.getJTextField1().getText().compareTo("") == 0)
294
			        layer.setMinScale(-1);
295
			    else
296
			        System.err.print(ex.getLocalizedMessage());
297
			}
298
			try
299
			{
300
			    layer.setMaxScale((nf.parse(fPanelScaleManager.getJTextField2().getText())).doubleValue());
301
			}
302
			catch (ParseException ex)
303
			{
304
			    if (fPanelScaleManager.getJTextField2().getText().compareTo("") == 0)
305
			        layer.setMaxScale(-1);
306
			    else
307
			        System.err.print(ex.getLocalizedMessage());
308
			}
309

  
310
		} else {
311
	        layer.setMinScale(-1);
312
	        layer.setMaxScale(-1);
313
		}
314
		if (!fPanelScaleManager.getLayerName().equals(layer.getName())){
315
			layer.setName(fPanelScaleManager.getLayerName());
316
		}
317
        if (layer instanceof FLyrVect)
318
        {
319
            FLyrVect lyrVect = (FLyrVect) layer;
320
            if (fPanelScaleManager.isSpatialIndexSelected())
321
            {
322
//                if (lyrVect.getSpatialIndex() == null)
323
            	if(lyrVect.getISpatialIndex() == null)
324
                {
325
                	//AZABALA
326
                	try {
327
						PluginServices.
328
							cancelableBackgroundExecution(getCreateSpatialIndexTask());
329
					} catch (DriverIOException e) {
330
						// TODO Auto-generated catch block
331
						e.printStackTrace();
332
					} catch (DriverException e) {
333
						// TODO Auto-generated catch block
334
						e.printStackTrace();
335
					}
336
//                    lyrVect.createSpatialIndex();
337
                }
338
            }
339
            //AZABALA
340
            /*
341
             * If we unselect the spatial index checkbox...Must we delete
342
             * spatial index file, or we only have to put Spatial Index
343
             * reference to null?. I have followed the second choice
344
             */
345
            else{
346
                lyrVect.deleteSpatialIndex();
347
            }
348

  
349

  
350
        }
351
		//layer.getFMap().invalidate();
352
		layer.getMapContext().callLegendChanged();
353
    }
354

  
355

  
356
    /**
357
     * Instanciates a ITask (@see com.iver.utiles.swing.threads.ITask)
358
     * to create a spatial index for the selected layer in background.
359
     * This task also allow to monitor process evolution, and to cancel
360
     * this process.
361
     * @throws DriverException
362
     * @throws DriverIOException
363
     */
364
    public IMonitorableTask getCreateSpatialIndexTask() throws DriverIOException,
365
    															DriverException{
366

  
367
//    	  FIXME REVISAR ESTO (Quizas lanzar TaskException)
368
			return new CreateSpatialIndexMonitorableTask((FLyrVect)layer);
369
    }
370

  
371
    /**
372
     * DOCUMENT ME!
373
     *
374
     * @author Fernando Gonz?lez Cort?s
375
     */
376
    private class ComandosListener implements ActionListener {
377
        private FThemeManagerWindow fLayerPropertiesWindow;
378

  
379
        /**
380
         * Creates a new ComandosListener object.
381
         *
382
         * @param lg DOCUMENT ME!
383
         */
384
        public ComandosListener(FThemeManagerWindow fLayerPropertiesWindow) {
385
        	this.fLayerPropertiesWindow = fLayerPropertiesWindow;
386
        }
387

  
388
        /* (non-Javadoc)
389
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
390
         */
391
        public void actionPerformed(ActionEvent e) {
392
            if (e.getActionCommand() == "OK") {
393
                // Implementaci?n para hacer funcionar el hyperlink ...
394
                //com.iver.cit.gvsig.gui.View theView = (com.iver.cit.gvsig.gui.View)PluginServices.getMDIManager().getActiveView();
395
                //ProjectView view = theView.getModel();
396
            	if (PluginServices.getMainFrame() != null)
397
            	{
398
            		IProjectView view = fPanelScaleManager.getView();
399
            		view.setTypeLink(fPanelScaleManager.getLinkType());
400
            		if (fPanelScaleManager.getSelectedLinkField()!=null)
401
            		{
402
            			view.setSelectedField(fPanelScaleManager.getSelectedLinkField().toString().trim());
403
            			view.setExtLink(fPanelScaleManager.getExtensionLink());
404
            		}
405
            	}
406
                //
407
                fLayerPropertiesWindow.btnApply_actionPerformed(e);
408
            	if (PluginServices.getMainFrame() == null)
409
            		((JDialog) (getParent().getParent().getParent().getParent())).dispose();
410
            	else
411
            		PluginServices.getMDIManager().closeWindow(FThemeManagerWindow.this);
412
                System.out.println("Ok");
413
            } else if (e.getActionCommand() == "CANCEL") {
414
            	if (PluginServices.getMainFrame() == null)
415
            		((JDialog) (getParent().getParent().getParent().getParent())).dispose();
416
            	else
417
            		PluginServices.getMDIManager().closeWindow(FThemeManagerWindow.this);
418
                System.out.println("CANCEL");
419
            } else if (e.getActionCommand() == "APPLY") {
420
                fLayerPropertiesWindow.btnApply_actionPerformed(e);
421
                System.out.println("APPLY");
422
            } else if (e.getActionCommand() == "LOAD_LEGEND") {
423
	        	JFileChooser jfc = new JFileChooser();
424
	    		jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
425
	    				PluginServices.getText(this, "tipo_de_leyenda")));
426
	    		//jfc.addChoosableFileFilter(new GenericFileFilter("sld","sld"));
427

  
428
	    		if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
429
	    			File file=jfc.getSelectedFile();
430
	    			if (!(file.getPath().endsWith(".gvl") || file.getPath().endsWith(".GVL")))
431
	    			{
432
	    				file=new File(file.getPath()+".gvl");
433
	    			}
434
	    			readLegend(file);
435
	    			fPanelLegendManager.setRenderer(renderer);
436
	    			fPanelLegendManager.actualizar();
437
	    		}
438
            } else if (e.getActionCommand() == "SAVE_LEGEND") {
439
				fLayerPropertiesWindow.btnApply_actionPerformed(e);
440
				JFileChooser jfc = new JFileChooser();
441
				jfc.addChoosableFileFilter(new GenericFileFilter("sld","*.sld"));
442
				jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
443
						PluginServices.getText(this, "tipo_de_leyenda")));
444

  
445

  
446
				if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION)
447
				{
448
					File file=jfc.getSelectedFile();
449
					if (jfc.getFileFilter().accept(new File("dummy.sld")))
450
					{
451
						if (!(file.getPath().toLowerCase().endsWith(".sld"))){
452
							file=new File(file.getPath()+".sld");
453
						}
454
						export2SLD(file);
455
					}
456
					else{
457
						if (!(file.getPath().toLowerCase().endsWith(".gvl"))){
458
							file=new File(file.getPath()+".gvl");
459
						}
460
						writeLegend(file);
461
					}
462
				}
463
            } else {}
464
        }
465
    }
466

  
467
    private void export2SLD(File file) {
468
		try {
469
			FileWriter writer = new FileWriter(file.getAbsolutePath());
470
			writer.write( renderer.getSLDString(layer.getName()));
471
			writer.close();
472

  
473
//			Marshaller m = new Marshaller(writer);
474
//			m.setEncoding("ISO-8859-1");
475
//			m.marshal(renderer.getSLDString());
476
		} catch (Exception e) {
477
			NotificationManager.addError(PluginServices.getText(this, "Error_exportando_SLD"), e);
478
		}
479
	}
480

  
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff