Statistics
| Revision:

root / trunk / extensions / extGraph_predes / src / com / iver / cit / gvsig / graph / core / writers / NetworkFileRedWriter.java @ 8487

History | View | Annotate | Download (11.6 KB)

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 com.hardcode.gdbms.engine.values.NumericValue;
55
import com.hardcode.gdbms.engine.values.ValueFactory;
56
import com.iver.cit.gvsig.fmap.DriverException;
57
import com.iver.cit.gvsig.fmap.core.FShape;
58
import com.iver.cit.gvsig.fmap.core.IGeometry;
59
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
60
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
61
import com.iver.cit.gvsig.fmap.edition.EditionException;
62
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
63
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
64
import com.iver.cit.gvsig.fmap.layers.VectorialAdapter;
65
import com.iver.cit.gvsig.graph.core.NodeGv;
66
import com.iver.utiles.swing.threads.CancellableMonitorable;
67
import com.vividsolutions.jts.geom.Coordinate;
68
import com.vividsolutions.jts.geom.Geometry;
69

    
70
/**
71
 * @author fjp
72
 *
73
 * 
74
 */
75
public class NetworkFileRedWriter extends AbstractNetworkWriter {
76
        File redFile;
77
        CancellableMonitorable cancel;
78
        public NetworkFileRedWriter() {
79
                
80
                // Set up fields for table nodes
81
                nodeFields = new FieldDescription[3];
82
                FieldDescription fieldNodeId = new FieldDescription();
83
                fieldNodeId.setFieldName("NODEID");
84
                fieldNodeId.setFieldType(Types.INTEGER);
85

    
86
                FieldDescription fieldX = new FieldDescription();
87
                fieldX.setFieldName("X");
88
                fieldX.setFieldType(Types.DOUBLE);
89
                fieldX.setFieldDecimalCount(2);
90

    
91
                FieldDescription fieldY = new FieldDescription();
92
                fieldY.setFieldName("Y");
93
                fieldY.setFieldType(Types.DOUBLE);
94
                fieldY.setFieldDecimalCount(2);
95
                
96
                nodeFields[0] = fieldNodeId;
97
                nodeFields[1] = fieldX;
98
                nodeFields[2] = fieldY;
99

    
100
                
101
                // Set up fields for table edges
102
                edgeFields = new FieldDescription[7];
103

    
104
                // ID_TRAMO ORIGINAL!!!
105
                FieldDescription fieldArcID = new FieldDescription();
106
                fieldArcID.setFieldName("ArcID");
107
                fieldArcID.setFieldType(Types.INTEGER);
108

    
109
                FieldDescription fieldDirection = new FieldDescription();
110
                fieldDirection.setFieldName("Direction");
111
                fieldDirection.setFieldType(Types.SMALLINT);
112
                
113
                FieldDescription fieldNodeOrigin = new FieldDescription();
114
                fieldNodeOrigin.setFieldName("NodeOrigin");
115
                fieldNodeOrigin.setFieldType(Types.INTEGER);
116
                FieldDescription fieldNodeEnd = new FieldDescription();
117
                fieldNodeEnd.setFieldName("NodeEnd");
118
                fieldNodeEnd.setFieldType(Types.INTEGER);
119

    
120
                FieldDescription fieldType = new FieldDescription();
121
                fieldType.setFieldName("Type");
122
                fieldType.setFieldType(Types.SMALLINT);
123

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

    
141
        /* (non-Javadoc)
142
         * @see com.iver.cit.gvsig.graph.core.INetworkWriter#writeNetwork(boolean)
143
         */
144
        public void writeNetwork() throws EditionException {
145
                // PRIMERO VAN EL NUMERO DE TRAMOS, LUEGO EL NUMERO DE ARCOS Y LUEGO
146
                // EL NUMERO DE NODOS, DESPUES
147
                // IDTRAMO-SENTIDO_DIGITALIZACION-IDNODOORIGEN-IDNODODESTINO-TIPOTRAMO-DISTANCIA
148
                // Y POR FIN
149
                // IDNODO-XLONG-YLONG
150

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

    
167
                double distance, cost;
168
                short arcType;
169
                int direction;
170
                int i;
171
                int idNodo1, idNodo2, nodeCount, edgeCount;
172
                short sentidoDigit; // => 1 en esa direcci?n. 0=> Al contrario. SOLO
173
                // SE UTILIZA PARA LOS CALCULOS POR IDTRAMO Y
174
                // PORCENTAJE
175
                // PARA SABER SI EST? M?S CERCA DE UN NODO O DEL OTRO.
176

    
177
                Hashtable nodeHash = new Hashtable();
178
                ArrayList nodes = new ArrayList();
179

    
180
                try {
181
                        if (lyr.getShapeType() != FShape.LINE) {
182
                                return;
183
                        }
184
                        RandomAccessFile file = new RandomAccessFile(redFile.getPath(),
185
                                        "rw");
186
                        FileImageOutputStream output = new FileImageOutputStream(file);
187
//                        FileChannel channel = file.getChannel();
188
//                        MappedByteBuffer buf = channel.map(MapMode.READ_WRITE, 0,
189
//                                        16 * 1024);
190
//                        buf.order(ByteOrder.LITTLE_ENDIAN);
191
                        output.setByteOrder(ByteOrder.LITTLE_ENDIAN);
192

    
193
                        nodeCount = 0;
194
                        VectorialAdapter adapter = (VectorialAdapter) lyr.getSource();
195
                        int numTramos;
196

    
197
                        numTramos = adapter.getShapeCount();
198
                        // Cambiamos otra vez: Escribimos primero el n? de tramos. Luego va
199
                        // el n? de arcos y el de nodos.
200
                        // buf.putInt(numTramos);
201
                        output.writeInt(numTramos);
202
                        // /////// Cambiamos el formato: primero van los arcos y luego los
203
                        // nodos
204
                        // file.writeInt(0);
205
                        output.writeInt(0);
206
                        // OJO: El numero de arcos todav?a no lo sabemos, habr? que volver
207
                        // luego y escribir el numero correcto. Es por lo de los sentidos.
208
                        // Metemos 2 arcos si es doble sentido, y uno si es de un solo
209
                        // sentido
210

    
211
                        // Guardamos un long. Luego volveremos aqu? y grabaremos el n? de
212
                        // nodos
213
                        // file.writeInt(0);
214
                        output.writeInt(numTramos);
215
                        // AHORA METEMOS LOS NOMBRES DE LOS CAMPOS. EN EL CARGA RED LOS
216
                        // USAREMOS PARA LEER DEL DBF.
217

    
218
                        edgeCount = 0;
219

    
220
                        SelectableDataSource sds = lyr.getRecordset();
221
                        int senseFieldIndex = -1;
222
                        int distFieldIndex = -1;
223
                        int typeFieldIndex = -1;
224
                        int costFieldIndex = -1;
225
                        
226
                        if (fieldSense != null)
227
                                senseFieldIndex = sds.getFieldIndexByName(fieldSense);
228
                        if (fieldDist != null)
229
                                distFieldIndex = sds.getFieldIndexByName(fieldDist);
230
                        if (fieldType != null)
231
                                typeFieldIndex = sds.getFieldIndexByName(fieldType);
232
                        if (fieldCost != null)
233
                                costFieldIndex = sds.getFieldIndexByName(fieldCost);
234

    
235
                        NumericValue valAux = null;
236
                        for (i = 0; i < numTramos; i++) {
237
                                IGeometry geom = adapter.getShape(i);
238
                                Geometry jtsGeom = geom.toJTSGeometry();
239
                                Coordinate[] coords = jtsGeom.getCoordinates();
240
                                Coordinate c1 = coords[0];
241
                                Coordinate c2 = coords[coords.length - 1];
242
                                
243
                                if(cancel != null)
244
                                        cancel.reportStep();
245

    
246
                                NodeGv nodeAux;
247
                                if (!nodeHash.containsKey(c1)) // No est?.
248
                                {
249
                                        idNodo1 = nodeCount++;
250
                                        nodeAux = new NodeGv(c1, idNodo1);
251
                                        nodeHash.put(c1, nodeAux);
252
                                        nodes.add(nodeAux);
253
                                } else {
254
                                        nodeAux = (NodeGv) nodeHash.get(c1);
255
                                }
256
                                idNodo1 = nodeAux.getId().intValue();
257

    
258
                                if (!nodeHash.containsKey(c2)) // No est?.
259
                                {
260
                                        idNodo2 = nodeCount++;
261
                                        nodeAux = new NodeGv(c2, idNodo2);
262
                                        nodeHash.put(c2, nodeAux);
263
                                        nodes.add(nodeAux);
264

    
265
                                } else {
266
                                        nodeAux = (NodeGv) nodeHash.get(c2);
267
                                }
268
                                idNodo2 = nodeAux.getId().intValue();
269

    
270
                                if (typeFieldIndex != -1)
271
                                        valAux = (NumericValue) sds.getFieldValue(i, typeFieldIndex);
272
                                else
273
                                        valAux = ValueFactory.createValue(0); // no hay tipo
274
                                arcType = valAux.shortValue();
275
                                // TipoTramo = DBFReadIntegerAttribute(hDBF, i, indiceCampo1);
276
                                
277
                                if (distFieldIndex != -1)
278
                                        valAux = (NumericValue) sds.getFieldValue(i, distFieldIndex);
279
                                else
280
                                        valAux = ValueFactory.createValue(jtsGeom.getLength());
281
                                distance = valAux.floatValue();
282
                                // Distancia = (float) DBFReadDoubleAttribute(hDBF, i,
283
                                // indiceCampo2);
284
                                if (costFieldIndex != -1)
285
                                {
286
                                        valAux = (NumericValue) sds.getFieldValue(i, costFieldIndex);
287
                                        cost = valAux.doubleValue();
288
                                }
289
                                else
290
                                        cost = distance;
291
                                
292
                                
293

    
294
                                direction = -1;
295

    
296
                                if (senseFieldIndex == -1)
297
                                        direction = 3; // 3-> Doble sentido, 1-> seg?n viene, 2 ->
298
                                // al rev?s, cualquier otro valor-> No hay
299
                                // arco
300
                                else {
301
                                        valAux = (NumericValue) sds.getFieldValue(i,
302
                                                        senseFieldIndex);
303
                                        direction = valAux.shortValue();
304
                                }
305

    
306
                                if (direction == 3) {
307
                                        sentidoDigit = 1; // En esa direcci?n
308
                                        writeEdge(output, i, sentidoDigit, idNodo1, idNodo2, arcType,
309
                                                        distance, cost);
310
                                        edgeCount++;
311

    
312
                                        sentidoDigit = 0;
313
                                        writeEdge(output, i, sentidoDigit, idNodo2, idNodo1, arcType,
314
                                                        distance, cost);
315
                                        edgeCount++;
316

    
317
                                }
318
                                if (direction == 1) {
319
                                        sentidoDigit = 1; // En esa direcci?n
320
                                        writeEdge(output, i, sentidoDigit, idNodo1, idNodo2, arcType,
321
                                                        distance, cost);
322
                                        edgeCount++;
323
                                }
324
                                if (direction == 2) {
325
                                        sentidoDigit = 0;
326
                                        writeEdge(output, i, sentidoDigit, idNodo2, idNodo1, arcType,
327
                                                        distance, cost);
328
                                        edgeCount++;
329

    
330
                                }
331
                                
332
                                if(cancel != null){
333
                                        cancel.reportStep();
334
                                        
335
                                }
336
                        }//for
337

    
338

    
339
                        for (int j=0; j < nodes.size(); j++) {
340
                                NodeGv node = (NodeGv) nodes.get(j);
341
                                output.writeInt(node.getId().intValue());
342
                                output.writeFloat((float) node.getCoordinate().x);
343
                                output.writeFloat((float) node.getCoordinate().y);
344
                        }
345

    
346
                        output.seek(0);
347
                        // buf.position(0);
348
                        output.writeInt(numTramos);
349
                        output.writeInt(edgeCount);
350
                        output.writeInt(nodes.size());
351

    
352
                        // buf.force();
353
                        output.close();
354
                        file.close();
355

    
356
                        return ;
357
                } catch (DriverIOException e) {
358
                        e.printStackTrace();
359
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
360
                        e.printStackTrace();
361
                        throw new EditionException(e);
362
                } catch (FileNotFoundException e) {
363
                        e.printStackTrace();
364
                        throw new EditionException(e);
365
                } catch (IOException e) {
366
                        e.printStackTrace();
367
                        throw new EditionException(e);
368
                } catch (DriverException e) {                
369
                        e.printStackTrace();
370
                        throw new EditionException(e);
371
                }
372
        }
373

    
374

    
375
        public void setCancellableMonitorable(CancellableMonitorable cancel) {
376
                this.cancel = cancel;
377
                
378
        }
379

    
380
        public void setRedFile(File redFile) {
381
                this.redFile = redFile;
382
                
383
        }
384

    
385
        private void writeEdge(FileImageOutputStream output, int id, short sense,
386
                        int idNodeOrig, int idNodeEnd, short tipoTramo, double dist, double cost)
387
                        throws IOException {
388
                output.writeInt(id);
389
                output.writeInt(sense);
390

    
391
                output.writeInt(idNodeOrig);
392
                output.writeInt(idNodeEnd);
393
                output.writeInt(tipoTramo);
394
                output.writeDouble(dist);
395
                output.writeDouble(cost);
396

    
397
        }
398

    
399
}