Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / extensions / extGeoreferencing / src / org / gvsig / georeferencing / utils / GeoPointPersistence.java @ 8745

History | View | Annotate | Download (31.4 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2006 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
package org.gvsig.georeferencing.utils;
20
import java.awt.Dimension;
21
import java.awt.geom.Point2D;
22
import java.awt.geom.Rectangle2D;
23
import java.io.BufferedOutputStream;
24
import java.io.BufferedReader;
25
import java.io.BufferedWriter;
26
import java.io.File;
27
import java.io.FileInputStream;
28
import java.io.FileNotFoundException;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.io.InputStreamReader;
32
import java.io.OutputStream;
33
import java.io.OutputStreamWriter;
34
import java.io.StringWriter;
35
import java.util.ArrayList;
36

    
37
import javax.xml.parsers.DocumentBuilder;
38
import javax.xml.parsers.DocumentBuilderFactory;
39
import javax.xml.parsers.ParserConfigurationException;
40

    
41
import org.apache.crimson.jaxp.DocumentBuilderFactoryImpl;
42
import org.apache.xml.serialize.OutputFormat;
43
import org.apache.xml.serialize.XMLSerializer;
44
import org.cresques.cts.ProjectionPool;
45
import org.cresques.io.data.RasterMetaFileTags;
46
import org.gvsig.georeferencing.GeoreferencingToolsModule;
47
import org.gvsig.georeferencing.gui.dialog.GeoreferencingDialog;
48
import org.gvsig.georeferencing.gui.panels.ZoomControlPanel;
49
import org.w3c.dom.Document;
50
import org.w3c.dom.Element;
51
import org.w3c.dom.Node;
52
import org.w3c.dom.NodeList;
53
import org.xml.sax.SAXException;
54

    
55
import com.iver.andami.PluginServices;
56
import com.iver.cit.gvsig.fmap.DriverException;
57
import com.iver.cit.gvsig.fmap.ViewPort;
58
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
59
import com.iver.cit.gvsig.fmap.layers.FLyrGeoRaster;
60
import com.iver.cit.gvsig.fmap.layers.FLyrPoints;
61
import com.iver.cit.gvsig.fmap.layers.GeoPoint;
62
import com.iver.cit.gvsig.fmap.layers.IPersistence;
63
import com.iver.cit.gvsig.gui.View;
64

    
65
/**
66
 * Clase que controla la persistencia de la capa de puntos.
67
 * @author Nacho Brodin (brodin_ign@gva.es)
68
 */
69
public class GeoPointPersistence implements IPersistence{
70
        //**********************Vars**********************************
71
        private ArrayList                 geoPointList = null;
72
        private Document                 xmlDoc = null;
73
        private Element                 generalTag = null;
74
        private FLyrPoints                 lyrPoints = null;
75
        private double[]                lastViewPort = null;
76
        //**********************End Vars******************************
77

    
78
        //**********************Methods*******************************
79
        /**
80
         * Constructor
81
         */
82
        public GeoPointPersistence(){}
83

    
84
        /**
85
         * Constructor
86
         * @param geoPointList        Lista de geopuntos
87
         */
88
        public GeoPointPersistence(FLyrPoints lyrPoints){
89
                this.geoPointList = lyrPoints.getListPoint();
90
                this.lyrPoints = lyrPoints;
91
        }
92

    
93
        /**
94
         * Carga la lista de puntos desde un fichero
95
         * @param file        Nombre del fichero
96
         * @return        Array con la lista de puntos
97
         */
98
        public void loadPointList(String file){
99
                try {
100
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
101
                DocumentBuilder db = dbf.newDocumentBuilder();
102
                File f = new File(file);
103
                Document doc = db.parse(f);
104

    
105
                if(doc.getDocumentElement().getTagName().equals(RasterMetaFileTags.MAIN_TAG)){
106
                        NodeList nodeListMain = doc.getDocumentElement().getChildNodes();
107
                        for(int j=0;j<nodeListMain.getLength();j++){
108
                                Node nodeMain = nodeListMain.item(j);
109
                                if(nodeMain.getNodeName().equals(RasterMetaFileTags.GEOPOINTS)){
110

    
111
                                        NodeList nodeListGeoPoints = nodeMain.getChildNodes();
112
                                    lyrPoints.clear();
113
                                    for(int i=0;i<nodeListGeoPoints.getLength();i++){
114
                                            Node node = nodeListGeoPoints.item(i);
115
                                            if(node.getNodeName().equals(RasterMetaFileTags.POINTS_LYR)){
116
                                                    NodeList nl = node.getChildNodes();
117
                                                    lastViewPort = processFlyrGeoRasterNodeValue(nl);
118
                                            }
119
                                            if(node.getNodeName().equals(RasterMetaFileTags.GEOPOINT)){
120
                                                    NodeList nl = node.getChildNodes();
121
                                                    processGeoPointNodeValue(nl);
122
                                            }
123
                                    }
124
                                    this.geoPointList = lyrPoints.getListPoint();
125

    
126
                                }
127
                        }
128
                }
129

    
130
            } catch (ParserConfigurationException e) {
131
                    return;
132
            } catch (SAXException e1) {
133
                    return;
134
            } catch (IOException e1) {
135
                    return;
136
            }
137
        }
138

    
139
        /**
140
         * Crea el XML con la lista de puntos y la salva a disco
141
         * @param file
142
         */
143
        public void savePointList(String file){
144
                this.geoPointList = lyrPoints.getListPoint();
145
                try {
146
                        DocumentBuilderFactory dbFactory = DocumentBuilderFactoryImpl.newInstance();
147
                    DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
148
                    xmlDoc = docBuilder.newDocument();
149
                } catch(Exception e) {
150
                      System.out.println(e);
151
                }
152

    
153
                generalTag = xmlDoc.createElement(RasterMetaFileTags.GEOPOINTS);
154
                xmlDoc.appendChild(generalTag);
155

    
156
                createXMLFLyrGeoRasterNode(lyrPoints.getLyrGeoRaster());
157

    
158
                for(int i=0;i<geoPointList.size();i++)
159
                        createXMLGeoPointNode((GeoPoint)(geoPointList.get(i)), i);
160

    
161
                XML2File(Document2Text(), file);
162
        }
163

    
164
        /**
165
         * Crea la lista de puntos a partir de un fichero CSV
166
         * @param file
167
         */
168
        public void loadCSVPointList(String file){
169
                try{
170
                        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
171
                        String line = in.readLine();
172
                        int nPoint = 0;
173
                        while(line != null){
174
                                if(nPoint == 0){
175
                                        if(!line.equals("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\",\"ErrX\",\"ErrY\",\"RMS\""))
176
                                                return;
177
                                }else{
178
                                        double x = 0D, y = 0D, xx = 0D, yy = 0D;
179
                                        String[] tokens = line.split(",");
180
                                    for(int tok=0; tok<tokens.length;tok++){
181
                                            try{
182
                                                    if(tok == 1)
183
                                                            x = Double.parseDouble(tokens[tok]);
184
                                                    if(tok == 2)
185
                                                            y = Double.parseDouble(tokens[tok]);
186
                                                    if(tok == 3)
187
                                                            xx = Double.parseDouble(tokens[tok]);
188
                                                    if(tok == 4)
189
                                                            yy = Double.parseDouble(tokens[tok]);
190
                                            }catch(NumberFormatException ex){
191
                                                    return;
192
                                            }
193
                                    }
194
                                        int pos = nPoint - 1;
195

    
196
                                        if(x == 0 && y == 0 && xx == 0 && yy == 0){
197
                                                line = in.readLine();
198
                                                continue;
199
                                        }
200

    
201
                                        lyrPoints.getPointManager().newEmptyPoint();
202
                                    Point2D p = new Point2D.Double();
203
                                        p.setLocation(x, y);
204
                                        Point2D m = new Point2D.Double();
205
                                        m.setLocation(xx, yy);
206

    
207
                                        Point2D leftCenter = new Point2D.Double();
208
                                        leftCenter.setLocation(lyrPoints.getLyrGeoRaster().img2World(p));
209
                                        Point2D rightCenter = new Point2D.Double();
210
                                        rightCenter.setLocation(m);
211

    
212
                                        View theView = null;
213
                                        ViewPort viewPort = null;
214
                                try{
215
                                        theView = (View) PluginServices.getMDIManager().getActiveWindow();
216
                                        viewPort = theView.getMapControl().getMapContext().getViewPort();
217
                                }catch(ClassCastException exc){
218
                                        return ;
219
                                }
220
                                        ViewPort leftViewPort = viewPort.cloneViewPort();
221
                                        leftViewPort.setImageSize(new java.awt.Dimension(ZoomControlPanel.WIDTH_MINIMG, ZoomControlPanel.HEIGHT_MINIMG));
222
                                        ViewPort rightViewPort = viewPort.cloneViewPort();
223
                                        rightViewPort.setImageSize(new java.awt.Dimension(ZoomControlPanel.WIDTH_MINIMG, ZoomControlPanel.HEIGHT_MINIMG));
224
                                        leftViewPort = lyrPoints.getPointManager().getDialog().getZoomControlLeft().getCanvas().initViewPort(viewPort, leftCenter, leftViewPort, 1);
225
                                        rightViewPort = lyrPoints.getPointManager().getDialog().getZoomControlLeft().getCanvas().initViewPort(viewPort, rightCenter, rightViewPort, 1);
226

    
227
                                        GeoreferencingToolsModule.setEnabled(true);
228

    
229
                                        lyrPoints.setPointActive(pos, true);
230
                                        lyrPoints.setLeftCenterPoint(pos,leftCenter);
231
                                        lyrPoints.setRightCenterPoint(pos, rightCenter);
232
                                        lyrPoints.setMiniExtent(pos, lyrPoints.getLyrGeoRaster().img2World(p), leftViewPort, false);
233
                                        lyrPoints.setMiniExtent(pos, m, rightViewPort, true);
234
                                        lyrPoints.getPointManager().updateData(pos + 1, p, m, lyrPoints.getPointManager().getDialog(), null);
235
                                        lyrPoints.setZoomLeft(pos, 1);
236
                                        lyrPoints.setZoomRight(pos, 1);
237
                                        if(lyrPoints.getCountPoints() > 0){
238
                                                GeoreferencingDialog grd = lyrPoints.getPointManager().getDialog();
239
                                                grd.getConectorPanel().getDataPointsTabPanel().getSelectPointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
240
                                                grd.getConectorPanel().getDataPointsTabPanel().getTablePointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
241
                                                lyrPoints.getPointManager().selectPoint(0, grd);
242
                                        }
243
                                }
244
                                nPoint++;
245
                                line = in.readLine();
246
                        }
247
                        in.close();
248
                }catch(FileNotFoundException ex){
249
                        //No salvamos el csv
250
                }catch(IOException ex){
251
                        //No salvamos el csv
252
                }
253
        }
254

    
255
        /**
256
         * Crea el fichero Ascii con la lista de puntos y la salva a disco
257
         * @param file
258
         */
259
        public void saveCSVPointList(String file){
260
                this.geoPointList = lyrPoints.getListPoint();
261
                try{
262
                        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
263
                        if(lyrPoints.getLyrGeoRaster().getGeoDialog().isErrorCSV())
264
                                out.write("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\",\"ErrX\",\"ErrY\",\"RMS\"\n");
265
                        else
266
                                out.write("\"Pt\",\"X\",\"Y\",\"X'\",\"Y'\"\n");
267

    
268
                        for(int i=0;i<geoPointList.size();i++){
269
                                GeoPoint geoPoint =  (GeoPoint)geoPointList.get(i);
270
                                String point = (i+1)+","+
271
                                                                geoPoint.pixelPoint.getX()+","+
272
                                                                geoPoint.pixelPoint.getY()+","+
273
                                                                geoPoint.mapPoint.getX()+","+
274
                                                                geoPoint.mapPoint.getY();
275
                                double[][] err = lyrPoints.getLyrGeoRaster().getGeoDialog().getErrors();
276
                                String error = "";
277
                                try{
278
                                        error = err[i][0]+","+err[i][1]+","+err[i][2];
279
                                        if(lyrPoints.getLyrGeoRaster().getGeoDialog().isErrorCSV())
280
                                                out.write(point+","+error+"\n");
281
                                        else
282
                                                out.write(point+"\n");
283
                                }catch(ArrayIndexOutOfBoundsException ex){
284
                                        out.write(point+"\n");
285
                                }
286
                        }
287
                        out.close();
288
                }catch(FileNotFoundException ex){
289
                        //No salvamos el csv
290
                }catch(IOException ex){
291
                        //No salvamos el csv
292
                }
293
        }
294
        //****************************************************
295

    
296
        /**
297
         * Aplica una transformaci?n al extent dependiendo de si el extent de la imagen
298
         * original ha cambiado o no. Si la capa FLyrGeoRaster cargada tiene un extent
299
         * distinto al que se ha salvado en el fichero de puntos esto significa que el
300
         * extent de la miniimagen que tiene los puntos relativos a las coordenadas de la
301
         * imagen en pixels ha de sufrir un desplazamiento. Este cambio puede producirse
302
         * cuando el usuario carga un proyecto con una capa a georreferenciar y la desplaza de
303
         * sitio con las herramientas. Posteriormente puede cargar los puntos del fichero .rmf
304
         * @param imgExtent Extent de la imagen
305
         * @param miniExtent ViewPor del miniextent a transformar
306
         * @return ViewPort        ViewPort del miniextent transformado
307
         */
308
        private ViewPort transformMiniExtent(Rectangle2D imgExtent, ViewPort miniExtent){
309
                if(        lastViewPort[0] != imgExtent.getMinX() ||
310
                        lastViewPort[1] != imgExtent.getMinY() ||
311
                        lastViewPort[2] != imgExtent.getWidth() ||
312
                        lastViewPort[3] != imgExtent.getHeight()){
313
                        Rectangle2D r = new Rectangle2D.Double();
314
                        r.setRect(         miniExtent.getExtent().getMinX() - (lastViewPort[0] - imgExtent.getMinX()),
315
                                                miniExtent.getExtent().getMinY() - (lastViewPort[1] - imgExtent.getMinY()),
316
                                                miniExtent.getExtent().getWidth(),
317
                                                miniExtent.getExtent().getHeight());
318
                        miniExtent.setExtent(r);
319
                }
320
                return miniExtent;
321
        }
322

    
323
        /**
324
         * Aplica una transformaci?n al centro del extent dependiendo de si el extent de la imagen
325
         * original ha cambiado o no.
326
         */
327
        private Point2D transformCenter(Rectangle2D imgExtent, Point2D center){
328
                if(        lastViewPort[0] != imgExtent.getMinX() ||
329
                        lastViewPort[1] != imgExtent.getMinY() ||
330
                        lastViewPort[2] != imgExtent.getWidth() ||
331
                        lastViewPort[3] != imgExtent.getHeight()){
332
                        Point2D c = new Point2D.Double();
333
                        c.setLocation(center.getX() - (lastViewPort[0] - imgExtent.getMinX()),
334
                                                  center.getY() - (lastViewPort[1] - imgExtent.getMinY()));
335
                        return c;
336
                }
337
                return center;
338
        }
339

    
340
        /**
341
         * Obtiene el valor del extent de la imagen obtenido desde un nodo
342
         * XML. A partir de este valor obtenido crea un punto en la capa.
343
         */
344
        private double[] processFlyrGeoRasterNodeValue(NodeList nl){
345
                double[] res = null;
346
                for(int j=0;j<nl.getLength();j++){
347
                        Node geoNode = nl.item(j);
348
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.POINTS_VP)){
349
                                res = new double[7];
350
                                NodeList vpChildNodes = geoNode.getChildNodes();
351
                                for(int i=0;i<vpChildNodes.getLength();i++){
352
                                        Node vpNode = vpChildNodes.item(i);
353
                                        if(vpNode.getNodeName().equals(RasterMetaFileTags.POINTS_BBOX)){
354
                                                NodeList extentChildNodes = vpNode.getChildNodes();
355
                                                for(int k=0;k<extentChildNodes.getLength();k++){
356
                                                        Node extentNode = extentChildNodes.item(k);
357
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_PX))
358
                                                                res[0] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
359
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_PY))
360
                                                                res[1] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
361
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_W))
362
                                                                res[2] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
363
                                                        if(extentNode.getNodeName().equals(RasterMetaFileTags.POINTS_H))
364
                                                                res[3] = Double.valueOf(extentNode.getFirstChild().getNodeValue()).doubleValue();
365
                                                }
366
                                        }
367
                                        if(vpNode.getNodeName().equals(RasterMetaFileTags.POINTS_DIM)){
368
                                                NodeList dimChildNodes = vpNode.getChildNodes();
369
                                                for(int k=0; k<dimChildNodes.getLength();k++){
370
                                                        Node dimNode = dimChildNodes.item(k);
371
                                                        if(dimNode.getNodeName().equals(RasterMetaFileTags.WIDTH))
372
                                                                res[4] = Double.valueOf(dimNode.getFirstChild().getNodeValue()).doubleValue();
373
                                                        if(dimNode.getNodeName().equals(RasterMetaFileTags.HEIGHT))
374
                                                                res[5] = Double.valueOf(dimNode.getFirstChild().getNodeValue()).doubleValue();
375
                                                }
376
                                                lyrPoints.getLyrGeoRaster().setImageDimension(res[4], res[5]);
377
                                        }
378
                                }
379
                        }
380
                }
381
                return res;
382
        }
383

    
384
        /**
385
         * Obtiene el valor de un punto georeferenciado obtenido desde un nodo
386
         * XML. A partir de este valor obtenido crea un punto en la capa.
387
         */
388
        private void processGeoPointNodeValue(NodeList nl){
389
                Point2D leftCenter = null, rightCenter = null;
390
                ViewPort leftViewPort = null, rightViewPort = null;
391
                double zoomLeft = 1, zoomRight = 1;
392
                double pX = 0D, pY = 0D, mX = 0D, mY = 0D;
393
                boolean active = false;
394
                for(int j=0;j<nl.getLength();j++){
395
                        Node geoNode = nl.item(j);
396
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_PX))
397
                                pX = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
398
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_PY))
399
                                pY = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
400
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_MAPX))
401
                                mX = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
402
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_MAPY))
403
                                mY = Double.valueOf(geoNode.getFirstChild().getNodeValue()).doubleValue();
404
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_ACTIVE))
405
                                active =  Boolean.valueOf(geoNode.getFirstChild().getNodeValue()).booleanValue();
406
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_LCENTER))
407
                                leftCenter = processCenterPoint(geoNode.getChildNodes());
408
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_RCENTER))
409
                                rightCenter = processCenterPoint(geoNode.getChildNodes());
410
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_LVP)){
411
                                Object[] obj = processViewPort(geoNode.getChildNodes());
412
                                leftViewPort = (ViewPort)obj[0];
413
                                zoomLeft = ((Double)obj[1]).doubleValue();
414
                        }
415
                        if(geoNode.getNodeName().equals(RasterMetaFileTags.GEOPOINT_RVP)){
416
                                Object[] obj = processViewPort(geoNode.getChildNodes());
417
                                rightViewPort = (ViewPort)obj[0];
418
                                zoomRight = ((Double)obj[1]).doubleValue();
419
                        }
420
                }
421

    
422
                Point2D p = new Point2D.Double();
423
                p.setLocation(pX, pY);
424
                Point2D m = new Point2D.Double();
425
                m.setLocation(mX, mY);
426

    
427
                lyrPoints.getPointManager().newEmptyPoint();
428
                GeoreferencingToolsModule.setEnabled(true);
429

    
430
                int pos = lyrPoints.getCountPoints() -1;
431
                try{
432
                        leftViewPort = transformMiniExtent(lyrPoints.getLyrGeoRaster().getFullExtent(), leftViewPort);
433
                        leftCenter = transformCenter(lyrPoints.getLyrGeoRaster().getFullExtent(), leftCenter);
434
                }catch(DriverException ex){}
435
                lyrPoints.setPointActive(pos, active);
436
                lyrPoints.setLeftCenterPoint(pos,leftCenter);
437
                lyrPoints.setRightCenterPoint(pos, rightCenter);
438
                lyrPoints.setMiniExtent(pos, lyrPoints.getLyrGeoRaster().img2World(p), leftViewPort, false);
439
                lyrPoints.setMiniExtent(pos, m, rightViewPort, true);
440
                lyrPoints.getPointManager().updateData(pos + 1, p, m, lyrPoints.getPointManager().getDialog(), null);
441
                lyrPoints.setZoomLeft(pos, zoomLeft);
442
                lyrPoints.setZoomRight(pos, zoomRight);
443
                if(lyrPoints.getCountPoints() > 0){
444
                        GeoreferencingDialog grd = lyrPoints.getPointManager().getDialog();
445
                        grd.getConectorPanel().getDataPointsTabPanel().
446
                                getSelectPointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
447
                        grd.getConectorPanel().getDataPointsTabPanel().
448
                                getTablePointsPanel().getTableControlerPanel().setNItems(lyrPoints.getCountPoints());
449
                        lyrPoints.getPointManager().selectPoint(0, grd);
450
                }
451
                //lyrPoints.addPoint(p, m);
452
        }
453

    
454
        /**
455
         * Procesa un nodo correspondiente a un extent
456
         * @param nodeList Lista de nodos
457
         * @return Rectangle2D
458
         */
459
        private Rectangle2D processExtent(NodeList nodeList){
460
                Rectangle2D r = new Rectangle2D.Double();
461
                double x = 0D, y = 0D, width = 0D, height = 0D;
462
                for(int j=0;j<nodeList.getLength();j++){
463
                        Node node = nodeList.item(j);
464
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PX))
465
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
466
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PY))
467
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
468
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_W))
469
                                width = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
470
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_H))
471
                                height = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
472
                }
473
                r.setRect(x, y, width, height);
474
                return r;
475
        }
476

    
477
        /**
478
         * Procesa un nodo correspondiente a la dimension de un viewPort
479
         * @param nodeList Lista de nodos
480
         * @return Rectangle2D
481
         */
482
        private Dimension processImageSize(NodeList nodeList){
483
                Dimension d = new Dimension();
484
                double x = 0D, y = 0D;
485
                for(int j=0;j<nodeList.getLength();j++){
486
                        Node node = nodeList.item(j);
487
                        if(node.getNodeName().equals(RasterMetaFileTags.WIDTH))
488
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
489
                        if(node.getNodeName().equals(RasterMetaFileTags.HEIGHT))
490
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
491
                }
492
                d.setSize(x, y);
493
                return d;
494
        }
495

    
496
        /**
497
         * Procesa el nodo correspondiente a un viewport de una mini imagen
498
         * @param nodeList Lista de nodos
499
         * @return ViewPort obtenido
500
         */
501
        private Object[] processViewPort(NodeList nodeList){
502
                Object[] obj = new Object[2];
503
                ViewPort vp = new ViewPort(null);
504
                Double zoom =  new Double(1);
505
                for(int j=0;j<nodeList.getLength();j++){
506
                        Node node = nodeList.item(j);
507
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_PROJ))
508
                                vp.setProjection(CRSFactory.getCRS(node.getFirstChild().getNodeValue()));
509
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_BBOX))
510
                                vp.setExtent(processExtent(node.getChildNodes()));
511
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_DIM))
512
                                vp.setImageSize(processImageSize(node.getChildNodes()));
513
                        if(node.getNodeName().equals(RasterMetaFileTags.POINTS_ZOOM))
514
                                zoom = new Double(node.getFirstChild().getNodeValue());
515
                }
516
                obj[0] = vp;
517
                obj[1] = zoom;
518
                vp.refreshExtent();
519
                return obj;
520
        }
521

    
522
        /**
523
         * Procesa un node correspondiente a un punto central de una
524
         * mini imagen
525
         * @param nodeList Lista de elementos del nodo centro
526
         * @return Punto obtenido
527
         */
528
        private Point2D processCenterPoint(NodeList nodeList){
529
                Point2D p = new Point2D.Double();
530
                double x = 0D, y = 0D;
531
                for(int j=0;j<nodeList.getLength();j++){
532
                        Node node = nodeList.item(j);
533
                        if(node.getNodeName().equals(RasterMetaFileTags.POSX))
534
                                x = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
535
                        if(node.getNodeName().equals(RasterMetaFileTags.POSY))
536
                                y = Double.valueOf(node.getFirstChild().getNodeValue()).doubleValue();
537
                }
538
                p.setLocation(x, y);
539
                return p;
540
        }
541

    
542
        //****************************************************
543

    
544
        /**
545
         * Crea un elemento simple xml de la forma <elem>texNode</elem>
546
         * a?adiendoselo al elemento padre pasado por par?metro
547
         * @param parent Elemento padre del XML
548
         * @param elem        tag
549
         * @param textNode        valor
550
         */
551
        private void createSimpleElement(Element parent, String elem, String textNode){
552
                Element itemlevel1 = null;
553
                itemlevel1 = xmlDoc.createElement(elem);
554
                itemlevel1.appendChild(xmlDoc.createTextNode(textNode));
555
                parent.appendChild(itemlevel1);
556
        }
557

    
558
        /**
559
         * Crear un bloque que representa un viewport
560
         * @param parent Elemento padre del XML
561
         * @param elem tag
562
         * @param values lista de valores
563
         */
564
        private void createViewPortNode(Element parent, String elem, String[] values){
565
                Element itemlevel1 = null;
566
                Element itemlevel2 = null;
567
                itemlevel1 = xmlDoc.createElement(elem);
568
                createSimpleElement(itemlevel1, RasterMetaFileTags.POINTS_PROJ, values[6]);
569
                itemlevel2 = xmlDoc.createElement(RasterMetaFileTags.POINTS_BBOX);
570
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_PX, values[0]);
571
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_PY, values[1]);
572
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_W, values[2]);
573
                createSimpleElement(itemlevel2, RasterMetaFileTags.POINTS_H, values[3]);
574
                itemlevel1.appendChild(itemlevel2);
575
                itemlevel2 = xmlDoc.createElement(RasterMetaFileTags.POINTS_DIM);
576
                createSimpleElement(itemlevel2, RasterMetaFileTags.WIDTH, values[4]);
577
                createSimpleElement(itemlevel2, RasterMetaFileTags.HEIGHT, values[5]);
578
                itemlevel1.appendChild(itemlevel2);
579
                if(values.length == 8)
580
                        createSimpleElement(itemlevel1, RasterMetaFileTags.POINTS_ZOOM, values[7]);
581
                parent.appendChild(itemlevel1);
582
        }
583

    
584
        /**
585
         * Convierte la capa a georreferenciar a un elemento XML que ser? a?adidoo al
586
         * documento.
587
         * @param lyrGeo Capa a georreferenciar
588
         */
589
        private void createXMLFLyrGeoRasterNode(FLyrGeoRaster lyrGeo) {
590
                Element xmlGeoPoint;
591
                xmlGeoPoint = xmlDoc.createElement(RasterMetaFileTags.POINTS_LYR);
592
                generalTag.appendChild(xmlGeoPoint);
593
                xmlGeoPoint.setAttribute("Name", lyrGeo.getName());
594
                String[] vpData = {String.valueOf(lyrGeo.getMinX()),
595
                                                        String.valueOf(lyrGeo.getMinY()),
596
                                                        String.valueOf(lyrGeo.getWidth()),
597
                                                        String.valueOf(lyrGeo.getHeight()),
598
                                                        String.valueOf(lyrGeo.getImageWidth()),
599
                                                        String.valueOf(lyrGeo.getImageHeight()),
600
                                                        lyrGeo.getProjection().getAbrev(),
601
                                                        };
602
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.POINTS_VP, vpData);
603
        }
604

    
605
        /**
606
         * Convierte un geopunto a un elemento XML que ser? a?adido al
607
         * documento.
608
         * @param geoPoint GeoPoint
609
         * @param i Posici?n del punto en la lista
610
         */
611
        private void createXMLGeoPointNode(GeoPoint geoPoint, int i) {
612
                Element xmlGeoPoint;
613
                Element itemlevel1;
614

    
615
                xmlGeoPoint = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT);
616
                xmlGeoPoint.setAttribute("n", String.valueOf(i));
617
                generalTag.appendChild(xmlGeoPoint);
618

    
619
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_PX, String.valueOf(geoPoint.pixelPoint.getX()));
620
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_PY, String.valueOf(geoPoint.pixelPoint.getY()));
621
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_MAPX, String.valueOf(geoPoint.mapPoint.getX()));
622
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_MAPY, String.valueOf(geoPoint.mapPoint.getY()));
623
                createSimpleElement(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_ACTIVE, String.valueOf(geoPoint.active));
624

    
625
                itemlevel1 = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT_LCENTER);
626
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSX, String.valueOf(geoPoint.leftCenterPoint.getX()));
627
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSY, String.valueOf(geoPoint.leftCenterPoint.getY()));
628
                xmlGeoPoint.appendChild(itemlevel1);
629

    
630
                itemlevel1 = xmlDoc.createElement(RasterMetaFileTags.GEOPOINT_RCENTER);
631
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSX, String.valueOf(geoPoint.rightCenterPoint.getX()));
632
                createSimpleElement(itemlevel1, RasterMetaFileTags.POSY, String.valueOf(geoPoint.rightCenterPoint.getY()));
633
                xmlGeoPoint.appendChild(itemlevel1);
634

    
635
                String[] values1 = {String.valueOf(geoPoint.leftViewPort.getExtent().getX()),
636
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getY()),
637
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getWidth()),
638
                                                        String.valueOf(geoPoint.leftViewPort.getExtent().getHeight()),
639
                                                        String.valueOf(geoPoint.leftViewPort.getImageWidth()),
640
                                                        String.valueOf(geoPoint.leftViewPort.getImageHeight()),
641
                                                        geoPoint.leftViewPort.getProjection().getAbrev(),
642
                                                        String.valueOf(geoPoint.zoomLeft)};
643
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_LVP, values1);
644

    
645
                String[] values2 = {String.valueOf(geoPoint.rightViewPort.getExtent().getX()),
646
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getY()),
647
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getWidth()),
648
                                                        String.valueOf(geoPoint.rightViewPort.getExtent().getHeight()),
649
                                                        String.valueOf(geoPoint.rightViewPort.getImageWidth()),
650
                                                        String.valueOf(geoPoint.rightViewPort.getImageHeight()),
651
                                                        geoPoint.rightViewPort.getProjection().getAbrev(),
652
                                                        String.valueOf(geoPoint.zoomRight)};
653

    
654
                createViewPortNode(xmlGeoPoint, RasterMetaFileTags.GEOPOINT_RVP, values2);
655
    }
656

    
657
        //****************************************************
658

    
659
        /**
660
         * escribe a disco el texto XML
661
         * @param textXML        Texto XML
662
         * @param fileName        Nombre del fichero
663
         */
664
        private void XML2File(String textXML, String fileName) {
665
            try {
666
              OutputStream fout= new FileOutputStream(fileName);
667
              OutputStream bout= new BufferedOutputStream(fout);
668
              OutputStreamWriter out = new OutputStreamWriter(bout);
669
              out.write(textXML);
670
              out.flush();
671
              out.close();
672
              File rmfFile = new File(fileName.substring(0, fileName.lastIndexOf("."))+".rmf");
673
              if(rmfFile.exists())
674
                      mergeFiles(fileName);
675
              else
676
                     newRmfFile(fileName, rmfFile);
677

    
678
            }catch (IOException e) {
679
              System.out.println(e.getMessage());
680
            }
681
        }
682

    
683
        /**
684
         * En el caso de que no exista ning?n fichero .rmf asociado a la imagen a georreferenciar lo creamos
685
         * con la cabecera rmf y los puntos que hemos salvado en el fichero temporal (.grf)
686
         * @param grfStr Nombre del fichero temporal .grf
687
         * @param rmf Fichero donde se salvaran los puntos .rmf
688
         */
689
        private void newRmfFile(String grfStr, File rmf){
690
                try{
691
                        File grf = new File(grfStr);
692
                        BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(grf)));
693
                        BufferedWriter outTmp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(rmf)));
694

    
695
                        outTmp.write("<?xml version=\"1.0\" encoding=\""+RasterMetaFileTags.ENCODING+"\"?>\n");
696
                        outTmp.write("<"+RasterMetaFileTags.MAIN_TAG+" "+"xmlns=\""+RasterMetaFileTags.NAMESPACE+"\">\n");
697
                        String str = inGrf.readLine();
698
                        str = inGrf.readLine();
699
                        while(str != null){
700
                                outTmp.write(str+"\n");
701
                               str = inGrf.readLine();
702
                    }
703
                        outTmp.write("</"+RasterMetaFileTags.MAIN_TAG+">\n");
704
                        grf.delete();
705
                        inGrf.close();
706
                        outTmp.close();
707
                }catch(FileNotFoundException exc){
708

    
709
                }catch(IOException exc){
710

    
711
                }
712
        }
713

    
714
        /**
715
         * En el caso de que ya exista un fichero .rmf asociado a la imagen habr? que mezclar este
716
         * con los puntos que hemos salvado en el fichero temporal .grf
717
         * @param fileName Nombre del fichero temporal
718
         */
719
        private void mergeFiles(String grfName){
720
                try{
721
                        File rmfFile = new File(grfName.substring(0, grfName.lastIndexOf("."))+".rmf");
722
                        File grfFile = new File(grfName);
723
                        File out = new File(rmfFile+"_tmpOutput");
724

    
725
                        BufferedReader inRmf = new BufferedReader(new InputStreamReader(new FileInputStream(rmfFile)));
726
                        BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(grfFile)));
727
                        BufferedWriter outTmp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)));
728

    
729
                        //Leemos el principio del .rmf
730
                String str = inRmf.readLine();
731
                while(!str.startsWith("</"+RasterMetaFileTags.LAYER) &&
732
                          !str.startsWith("<"+RasterMetaFileTags.GEOPOINTS)){
733
                        outTmp.write(str+"\n");
734
                        str = inRmf.readLine();
735
                }
736
                if(str.startsWith("</"+RasterMetaFileTags.LAYER))
737
                        outTmp.write(str+"\n");
738

    
739
                //Leemos la lista de puntos
740
                str = inGrf.readLine();
741
                while(str != null){
742
                        if(!str.startsWith("<?xml"))
743
                                outTmp.write(str+"\n");
744
                        str = inGrf.readLine();
745
                }
746

    
747
                //Saltamos los puntos que ya existian en el .rmf
748
                try{
749
                        str = inRmf.readLine();
750
                        while(str != null &&
751
                                  !str.startsWith("</"+RasterMetaFileTags.GEOPOINTS) &&
752
                                  !str.startsWith("</"+RasterMetaFileTags.MAIN_TAG))
753
                                str = inRmf.readLine();
754
                }catch(Exception exc){
755

    
756
                }
757

    
758
                //Leemos el resto del fichero .rmf
759
                if( !str.startsWith("</"+RasterMetaFileTags.MAIN_TAG))
760
                        str = inRmf.readLine();
761
                while(str != null){
762
                        if(!str.startsWith("<?xml"))
763
                                outTmp.write(str+"\n");
764
                        str = inRmf.readLine();
765
                }
766

    
767
                outTmp.close();
768
                inRmf.close();
769
                inGrf.close();
770

    
771
                //Eliminamos el antiguo .rmf y lo sustituimos
772
                rmfFile.delete();
773
                out.renameTo(rmfFile);
774
                grfFile.delete();
775

    
776
                }catch(FileNotFoundException exc){
777

    
778
                }catch(IOException exc){
779

    
780
                }
781
        }
782

    
783
        /**
784
         * Convierte el objeto Document que contiene el XML construido a
785
         * texto XML para que podamos salvarlo a disco.
786
         * @return Cadena de texto XML
787
         */
788
        private String Document2Text() {
789
            StringWriter strWriter = null;
790
            XMLSerializer xmlSerializer = null;
791
            OutputFormat outFormat = null;
792
            try {
793
                    xmlSerializer = new XMLSerializer();
794
                    strWriter = new StringWriter();
795
                    outFormat = new OutputFormat();
796

    
797
                    outFormat.setEncoding(RasterMetaFileTags.ENCODING);
798
                    outFormat.setIndenting(true);
799
                    outFormat.setIndent(4);
800

    
801
                    xmlSerializer.setOutputCharStream(strWriter);
802
                    xmlSerializer.setOutputFormat(outFormat);
803
                    xmlSerializer.serialize(xmlDoc);
804
                    strWriter.close();
805
                   } catch (IOException ioEx) {
806
                      System.out.println("Error : " + ioEx);
807
                   }
808
                    return strWriter.toString();
809
        }
810
        //**********************End Methods***************************
811

    
812
        //**********************Getters & Setters*********************
813
        /**
814
         * Asigna la capa de puntos
815
         * @param lyrPoints
816
         */
817
        public void setLyrPoints(FLyrPoints lyrPoints) {
818
                this.geoPointList = lyrPoints.getListPoint();
819
                this.lyrPoints = lyrPoints;
820
        }
821
        //**********************End Getters & Setters*****************
822
}