Statistics
| Revision:

gvsig-raster / org.gvsig.raster / trunk / org.gvsig.raster / org.gvsig.raster.lib / org.gvsig.raster.lib.impl / src / main / java / org / gvsig / raster / impl / store / rmf / RmfBlocksManager.java @ 2616

History | View | Annotate | Download (8.23 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.impl.store.rmf;
23

    
24
import java.io.BufferedReader;
25
import java.io.File;
26
import java.io.FileInputStream;
27
import java.io.FileNotFoundException;
28
import java.io.FileWriter;
29
import java.io.IOException;
30
import java.io.InputStreamReader;
31
import java.util.ArrayList;
32

    
33
import org.gvsig.fmap.dal.coverage.RasterLocator;
34
import org.gvsig.fmap.dal.coverage.exception.ParsingException;
35
/**
36
 * Gestor para la escritura de bloques XML en el fichero RMF. Cada cliente que quiere
37
 * escribir en el se registrar? a traves de ClientRegister y esta clase ser? la encargada
38
 * de gestionar la lectura y escritura de bloques.
39
 *
40
 * @author Nacho Brodin (nachobrodin@gmail.com)
41
 */
42
public class RmfBlocksManager extends ClientRegister implements IRmfBlock {
43
        private final String MAIN_TAG = "RasterMetaFile";
44
        private String       version  = "1.0";
45
        
46
        private String path = null;
47

    
48
        /**
49
         * Constructor. Asigna la ruta del fichero.
50
         * @param path
51
         */
52
        public RmfBlocksManager(String path) {
53
                setPath(path);
54
        }
55

    
56
        /**
57
         * Asigna la ruta del fichero
58
         * @param path
59
         */
60
        public void setPath(String path) {
61
                this.path = path;
62
        }
63

    
64
        /**
65
         * Obtiene la ruta del fichero
66
         * @return path
67
         */
68
        public String getPath() {
69
                return path;
70
        }
71
        
72
        /**
73
         * Genera una copia de seguridad del fichero del rmf
74
         * @throws IOException
75
         */
76
        public void fileBackup() throws IOException {
77
                RasterLocator.getManager().getFileUtils().copyFile(getPath(), getPath() + "~");
78
        }
79

    
80
        public void read(String xml) throws ParsingException {
81
                File file = new File(getPath());
82
                ArrayList<String> lines = new ArrayList<String>();
83

    
84
                BufferedReader inGrf = null;
85
                try {
86
                        inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
87
                        String str = inGrf.readLine();
88
                        while (str != null) {
89
                                for (int i = 0; i < clients.size(); i++) {
90
                                        IRmfBlock block = ((IRmfBlock) clients.get(i));
91
                                        String main = block.getMainTag();
92
                                        if (str.startsWith("<" + main)) {
93
                                                lines.clear();
94
                                                while (str.compareTo("</" + main + ">") != 0) {
95
                                                        lines.add(str);
96
                                                        str = inGrf.readLine();
97
                                                        if(str == null) {
98
                                                                inGrf.close();
99
                                                                return;
100
                                                        }
101
                                                }
102
                                                lines.add(str);
103
                                                StringBuffer buf = new StringBuffer();
104
                                                for (int j = 0; j < lines.size(); j++)
105
                                                        buf.append((String) lines.get(j));
106
                                                block.read(buf.toString());
107

    
108
                                        }
109
                                }
110

    
111
                                str = inGrf.readLine();
112
                        }
113
                        inGrf.close();
114
                } catch (FileNotFoundException e) {
115
                        throw new ParsingException("File Input error: creating BufferedReader");
116
                } catch (IOException ex) {
117
                        throw new ParsingException("File Input error: reading lines");
118
                }
119
        }
120

    
121
        /**
122
         * Creaci?n de nuevo fichero RMF. A?ade la cabecera y vuelca el contenido de
123
         * todos los IRmfBlock.
124
         * @param file Fichero
125
         * @return true si el fichero no existia y se ha creado nuevo
126
         * @throws IOException 
127
         * @throws IOException
128
         */
129
        private void create(File file) throws IOException {
130
                file.createNewFile();
131
                FileWriter writer = new FileWriter(file);
132
                writer.write("<?xml version=\"1.0\" encoding=\"ISO-8859-15\"?>\n");
133
                writer.write("<" + getMainTag() + " version=\"" + version + "\">\n");
134
                for (int i = 0; i < clients.size(); i++) {
135
                        IRmfBlock block = ((IRmfBlock) clients.get(i));
136
                        String xmlBlock = block.write();
137
                        if(xmlBlock != null)
138
                                writer.write(xmlBlock);
139
                }
140
                writer.write("</" + getMainTag() + ">\n");
141
                writer.close();
142
        }
143

    
144
        public String write() throws IOException {
145
                File file = new File(getPath());
146
                ArrayList<String> lines = new ArrayList<String>();
147

    
148
                // Si no existe a?n el rmf se crea, se a?ade las cabeceras y se vuelca el
149
                // contenido de los bloques
150
                if (!file.exists())
151
                        create(file);
152

    
153
                // A?adir bloques al fichero.
154
                BufferedReader inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
155
                String str = inGrf.readLine();
156
                while (str != null) {
157
                        lines.add(str);
158
                        str = inGrf.readLine();
159
                }
160

    
161
                // Obtenemos el primer tag de un bloque. Para cada uno recorremos todo el
162
                // rmf actual buscando ese tag. Si existe se a?ade el nuevo bloque y se
163
                // borra el viejo. Si no existe lo a?ade al final antes de la etiqueta de
164
                // cierre </RasterMetaFile>
165
                for (int i = 0; i < clients.size(); i++) {
166
                        IRmfBlock block = ((IRmfBlock) clients.get(i));
167
                        String tag = block.getMainTag();
168

    
169
                        for (int nLine = 0; nLine < lines.size(); nLine++) {
170
                                String line = (String) lines.get(nLine);
171
                                if (line != null && (line.compareTo("</" + getMainTag() + ">") == 0 || line.startsWith("<" + tag))) {
172
                                        String xmlBlock = block.write();
173
                                        if(xmlBlock != null) { //Sustituci?n de bloque
174
                                                if (nLine != 0)
175
                                                        lines.add(nLine, xmlBlock);
176
                                                if (line.startsWith("<" + tag)) {
177
                                                        while (((String) lines.get(nLine + 1)).compareTo("</" + tag + ">") != 0)
178
                                                                lines.remove(nLine + 1);
179
                                                        lines.remove(nLine + 1);
180
                                                }
181
                                        } else { //Eliminado de bloque
182
                                                if (line.startsWith("<" + tag)) {
183
                                                        while (((String) lines.get(nLine)).compareTo("</" + tag + ">") != 0)
184
                                                                lines.remove(nLine);
185
                                                        lines.remove(nLine);
186
                                                }
187
                                        }
188
                                        break;
189
                                }
190
                        }
191
                }
192
                inGrf.close();
193

    
194
                // Escribir fichero de salida.
195
                file.delete();
196
                file.createNewFile();
197
                FileWriter writer = new FileWriter(file);
198

    
199
                for (int i = 0; i < lines.size(); i++) {
200
                        if (((String) lines.get(i)).length() == 0)
201
                                continue;
202
                        if (!((String) lines.get(i)).endsWith("\n"))
203
                                writer.write((String) lines.get(i) + "\n");
204
                        else
205
                                writer.write((String) lines.get(i));
206
                }
207
                writer.close();
208

    
209
                return null;
210
        }
211

    
212
        /**
213
         * Obtiene un bloque XML que representa a las propiedades del objeto a
214
         * serializar. Antes de la operaci?n hace una copia de seguridad del fichero
215
         * RMF.
216
         * @param rmfBackup Especifica si debe hacer la copia de seguridad.
217
         * @return Texto XML que representa el objeto.
218
         */
219
        public String write(boolean rmfBackup) throws IOException, FileNotFoundException {
220
                if (rmfBackup && new File(getPath()).exists())
221
                        RasterLocator.getManager().getFileUtils().copyFile(getPath(), getPath() + "~");
222

    
223
                return write();
224
        }
225

    
226
        /**
227
         * M?todo que checkea si el fichero pasado es valido para ser rmf. Si existe
228
         * el fichero ser? valido si se puede escribir en el y no est? vacio y no es
229
         * un directorio y contiene los caracteres de cabecera de comienzo de XML (<?xml
230
         * .... >). En caso de que el fichero no exista tambi?n es valido ya que se
231
         * crear? de cero.
232
         * @return true si es un rmf valido y false si no lo es
233
         */
234
        public boolean checkRmf() {
235
                File f = new File(getPath());
236
                if (f.exists()) {
237
                        if (!f.canWrite() || f.length() == 0 || f.isDirectory())
238
                                return false;
239
                        BufferedReader inGrf;
240
                        try {
241
                                inGrf = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
242
                                String str = inGrf.readLine();
243
                                if (!str.startsWith("<?xml")) {
244
                                        inGrf.close();
245
                                        return false;
246
                                }
247
                                while (str != null) {
248
                                        if (str.startsWith("<" + getMainTag())) {
249
                                                inGrf.close();
250
                                                if(str.contains("version=\"")) {
251
                                                        String versionNbr = str.substring(str.indexOf("version=\"") + 9);
252
                                                        versionNbr = versionNbr.substring(0, versionNbr.indexOf("\""));
253
                                                        if(!versionNbr.equals(version)) {
254
                                                                return false;
255
                                                        }
256
                                                } 
257
                                                return true;
258
                                        }
259
                                        str = inGrf.readLine();
260
                                }
261
                                inGrf.close();
262
                        } catch (FileNotFoundException e) {
263
                                return false;
264
                        } catch (IOException e) {
265
                                return false;
266
                        }
267
                }
268
                return true;
269
        }
270

    
271
        public String getMainTag() {
272
                return MAIN_TAG;
273
        }
274

    
275
        public Object getResult() {
276
                return null;
277
        }
278
}