Statistics
| Revision:

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

History | View | Annotate | Download (31.3 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.io.data.RasterMetaFileTags;
45
import org.gvsig.georeferencing.GeoreferencingToolsModule;
46
import org.gvsig.georeferencing.gui.dialog.GeoreferencingDialog;
47
import org.gvsig.georeferencing.gui.panels.ZoomControlPanel;
48
import org.w3c.dom.Document;
49
import org.w3c.dom.Element;
50
import org.w3c.dom.Node;
51
import org.w3c.dom.NodeList;
52
import org.xml.sax.SAXException;
53

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

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

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

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

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

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

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

    
125
                                }
126
                        }
127
                }
128

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

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

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

    
155
                createXMLFLyrGeoRasterNode(lyrPoints.getLyrGeoRaster());
156

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

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

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

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

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

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

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

    
226
                                        GeoreferencingToolsModule.setEnabled(true);
227

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
541
        //****************************************************
542

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

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

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

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

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

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

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

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

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

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

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

    
656
        //****************************************************
657

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

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

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

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

    
708
                }catch(IOException exc){
709

    
710
                }
711
        }
712

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

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

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

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

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

    
755
                }
756

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

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

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

    
775
                }catch(FileNotFoundException exc){
776

    
777
                }catch(IOException exc){
778

    
779
                }
780
        }
781

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

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

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

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