Statistics
| Revision:

root / trunk / libraries / libRaster / src / org / gvsig / raster / dataset / io / rmf / RmfBlocksManager.java @ 21799

History | View | Annotate | Download (7.27 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 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.raster.dataset.io.rmf;
20

    
21
import java.io.BufferedReader;
22
import java.io.File;
23
import java.io.FileInputStream;
24
import java.io.FileNotFoundException;
25
import java.io.FileWriter;
26
import java.io.IOException;
27
import java.io.InputStreamReader;
28
import java.util.ArrayList;
29

    
30
import org.gvsig.raster.util.RasterUtilities;
31
/**
32
 * Gestor para la escritura de bloques XML en el fichero RMF. Cada cliente que quiere
33
 * escribir en el se registrar? a traves de ClientRegister y esta clase ser? la encargada
34
 * de gestionar la lectura y escritura de bloques.
35
 *
36
 * 21-abr-2007
37
 * @author Nacho Brodin (nachobrodin@gmail.com)
38
 */
39
public class RmfBlocksManager extends ClientRegister implements IRmfBlock {
40
        private final String MAIN_TAG = "RasterMetaFile";
41
        private String path = null;
42

    
43
        /**
44
         * Constructor. Asigna la ruta del fichero.
45
         * @param path
46
         */
47
        public RmfBlocksManager(String path) {
48
                setPath(path);
49
        }
50

    
51
        /**
52
         * Asigna la ruta del fichero
53
         * @param path
54
         */
55
        public void setPath(String path) {
56
                this.path = path;
57
        }
58

    
59
        /**
60
         * Obtiene la ruta del fichero
61
         * @return path
62
         */
63
        public String getPath() {
64
                return path;
65
        }
66

    
67
        /*
68
         *  (non-Javadoc)
69
         * @see org.gvsig.raster.dataset.io.rmf.IRmfBlock#read(java.lang.String)
70
         */
71
        public void read(String xml) throws ParsingException {
72
                File file = new File(getPath());
73
                ArrayList lines = new ArrayList();
74

    
75
                BufferedReader inGrf = null;
76
                try {
77
                        inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
78
                        String str = inGrf.readLine();
79
                        while (str != null) {
80
                                for (int i = 0; i < clients.size(); i++) {
81
                                        IRmfBlock block = ((IRmfBlock) clients.get(i));
82
                                        String main = block.getMainTag();
83
                                        if (str.startsWith("<" + main)) {
84
                                                lines.clear();
85
                                                while (str.compareTo("</" + main + ">") != 0) {
86
                                                        lines.add(str);
87
                                                        str = inGrf.readLine();
88
                                                }
89
                                                lines.add(str);
90
                                                StringBuffer buf = new StringBuffer();
91
                                                for (int j = 0; j < lines.size(); j++)
92
                                                        buf.append((String) lines.get(j));
93
                                                block.read(buf.toString());
94
                                                break;
95
                                        }
96
                                }
97

    
98
                                str = inGrf.readLine();
99
                        }
100
                        inGrf.close();
101
                } catch (FileNotFoundException e) {
102
                        throw new ParsingException("File Input error: creating BufferedReader");
103
                } catch (IOException ex) {
104
                        throw new ParsingException("File Input error: reading lines");
105
                }
106
        }
107

    
108
        /**
109
         * Creaci?n de nuevo fichero RMF. A?ade la cabecera y vuelca el contenido de
110
         * todos los IRmfBlock.
111
         * @param file Fichero
112
         * @return true si el fichero no existia y se ha creado nuevo
113
         * @throws IOException
114
         */
115
        private boolean create(File file) throws IOException {
116
                if (!file.exists()) {
117
                        file.createNewFile();
118
                        FileWriter writer = new FileWriter(file);
119
                        writer.write("<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n");
120
                        writer.write("<RasterMetaFile>\n");
121
                        for (int i = 0; i < clients.size(); i++) {
122
                                IRmfBlock block = ((IRmfBlock) clients.get(i));
123
                                writer.write(block.write());
124
                        }
125
                        writer.write("</RasterMetaFile>\n");
126
                        writer.close();
127
                        return true;
128
                }
129
                return false;
130
        }
131

    
132
        /*
133
         *  (non-Javadoc)
134
         * @see org.gvsig.raster.dataset.io.rmf.IRmfBlock#write()
135
         */
136
        public String write() throws IOException {
137
                File file = new File(getPath());
138
                ArrayList lines = new ArrayList();
139

    
140
                // Si no existe a?n el rmf se crea, se a?ade las cabeceras y se vuelca el
141
                // contenido de los bloques
142
                if (create(file))
143
                        return null;
144

    
145
                // A?adir bloques al fichero.
146
                BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
147
                String str = inGrf.readLine();
148
                while (str != null) {
149
                        lines.add(str);
150
                        str = inGrf.readLine();
151
                }
152

    
153
                // Obtenemos el primer tag de un bloque. Para cada uno recorremos todo el
154
                // rmf actual buscando ese tag. Si existe se a?ade el nuevo bloque y se
155
                // borra el viejo. Si no existe lo a?ade al final antes de la etiqueta de
156
                // cierre </RasterMetaFile>
157
                for (int i = 0; i < clients.size(); i++) {
158
                        IRmfBlock block = ((IRmfBlock) clients.get(i));
159
                        String tag = block.getMainTag();
160

    
161
                        for (int line = 0; line < lines.size(); line++) {
162
                                str = (String) lines.get(line);
163
                                if (str.compareTo("</" + getMainTag() + ">") == 0 || str.startsWith("<" + tag)) {
164
                                        String xmlBlock = block.write();
165
                                        if (line != 0)
166
                                                lines.add(line, xmlBlock);
167
                                        if (str.startsWith("<" + tag)) {
168
                                                while (((String) lines.get(line + 1)).compareTo("</" + tag + ">") != 0)
169
                                                        lines.remove(line + 1);
170
                                                lines.remove(line + 1);
171
                                        }
172
                                        break;
173
                                }
174
                        }
175
                }
176
                inGrf.close();
177

    
178
                // Escribir fichero de salida.
179
                file.delete();
180
                file.createNewFile();
181
                FileWriter writer = new FileWriter(file);
182

    
183
                for (int i = 0; i < lines.size(); i++) {
184
                        if (((String) lines.get(i)).length() == 0)
185
                                continue;
186
                        if (!((String) lines.get(i)).endsWith("\n"))
187
                                writer.write((String) lines.get(i) + "\n");
188
                        else
189
                                writer.write((String) lines.get(i));
190
                }
191
                writer.close();
192

    
193
                return null;
194
        }
195

    
196
        /**
197
         * Obtiene un bloque XML que representa a las propiedades del objeto a
198
         * serializar. Antes de la operaci?n hace una copia de seguridad del fichero
199
         * RMF.
200
         * @param rmfBackup Especifica si debe hacer la copia de seguridad.
201
         * @return Texto XML que representa el objeto.
202
         */
203
        public String write(boolean rmfBackup) throws IOException, FileNotFoundException {
204
                if (rmfBackup)
205
                        RasterUtilities.copyFile(getPath(), getPath() + "~");
206

    
207
                return write();
208
        }
209

    
210
        /**
211
         * M?todo que checkea si el fichero pasado es valido para ser rmf. Si existe
212
         * el fichero ser? valido si se puede escribir en el y no est? vacio y no es
213
         * un directorio y contiene los caracteres de cabecera de comienzo de XML (<?xml
214
         * .... >). En caso de que el fichero no exista tambi?n es valido ya que se
215
         * crear? de cero.
216
         * @return true si es un rmf valido y false si no lo es
217
         */
218
        public boolean checkRmf() {
219
                File f = new File(getPath());
220
                if (f.exists()) {
221
                        if (!f.canWrite() || f.length() == 0 || f.isDirectory())
222
                                return false;
223
                        BufferedReader inGrf;
224
                        try {
225
                                inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
226
                                String str = inGrf.readLine();
227
                                if (!str.startsWith("<?xml"))
228
                                        return false;
229
                        } catch (FileNotFoundException e) {
230
                                return false;
231
                        } catch (IOException e) {
232
                                return false;
233
                        }
234
                }
235
                return true;
236
        }
237

    
238
        /*
239
         * (non-Javadoc)
240
         * @see org.gvsig.raster.dataset.io.rmf.IRmfBlock#getMainTag()
241
         */
242
        public String getMainTag() {
243
                return MAIN_TAG;
244
        }
245

    
246
        /*
247
         * (non-Javadoc)
248
         * @see org.gvsig.raster.dataset.io.rmf.IRmfBlock#getResult()
249
         */
250
        public Object getResult() {
251
                return null;
252
        }
253
}