Statistics
| Revision:

root / trunk / libraries / libRaster / src / org / gvsig / raster / datastruct / serializer / ColorTableLibraryPersistence.java @ 20866

History | View | Annotate | Download (17.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 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.datastruct.serializer;
20

    
21
import java.awt.Color;
22
import java.io.File;
23
import java.io.FileInputStream;
24
import java.io.FileNotFoundException;
25
import java.io.FileOutputStream;
26
import java.io.FileWriter;
27
import java.io.IOException;
28
import java.io.InputStream;
29
import java.io.InputStreamReader;
30
import java.io.OutputStreamWriter;
31
import java.io.StringReader;
32
import java.net.URL;
33
import java.util.ArrayList;
34

    
35
import org.gvsig.raster.datastruct.ColorItem;
36
import org.gvsig.raster.datastruct.ColorTable;
37
import org.kxml2.io.KXmlParser;
38
import org.kxml2.io.KXmlSerializer;
39
import org.xmlpull.v1.XmlPullParserException;
40
/**
41
 * @version 02/07/2007
42
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
43
 */
44
public class ColorTableLibraryPersistence {
45

    
46
        /**
47
         * Devuelve la lista de ficheros de paletas, si no existe el fichero devolvera
48
         * una lista vacia
49
         * @param palettesBasePath
50
         * @return
51
         */
52
        private static ArrayList getPaletteFileListDisc(String palettesBasePath) {
53
                updateVersion(palettesBasePath);
54

    
55
                File paletteFiles = new File(palettesBasePath);
56

    
57
                ArrayList fileList = new ArrayList();
58

    
59
                if (paletteFiles.exists()) {
60
                        File[] list = paletteFiles.listFiles();
61
                        for (int i = 0; i < list.length; i++)
62
                                fileList.add(list[i].getName());
63
                }
64

    
65
                return fileList;
66
        }
67

    
68
        /**
69
         * Devuelve la lista de ficheros de paletas, si no existe el fichero creara
70
         * una paleta por defecto y la devolvera.
71
         * @param palettesBasePath
72
         * @return
73
         */
74
        public static ArrayList getPaletteFileList(String palettesBasePath) {
75
                return getPaletteFileList(palettesBasePath, true);
76
        }
77

    
78
        /**
79
         * Devuelve la lista de ficheros de paletas, en caso de que no exista la
80
         * paleta y se especifique forceCreate a true, se creara la paleta por defecto.
81
         * @param palettesBasePath
82
         * @param forceCreate
83
         * @return
84
         */
85
        public static ArrayList getPaletteFileList(String palettesBasePath, boolean forceCreate) {
86
                ArrayList fileList = getPaletteFileListDisc(palettesBasePath);
87

    
88
                if (forceCreate && (fileList.size() == 0)) {
89
                        ColorTableLibraryPersistence persistence = new ColorTableLibraryPersistence();
90
                        createVersionFromXML(palettesBasePath, persistence.getDefaultPaletteXML());
91
                        fileList = getPaletteFileListDisc(palettesBasePath);
92
                }
93

    
94
                return fileList;
95
        }
96

    
97
        /**
98
         * Devuelve el XML de una paleta por defecto
99
         * @return
100
         */
101
        public String getDefaultPaletteXML() {
102
                URL url = getClass().getResource("xml/palettes.xml");
103
                StringBuffer contents = new StringBuffer();
104
                try {
105
                        InputStream inputStream = url.openStream();
106

    
107
                        int i;
108
                        while (true) {
109
                                i = inputStream.read();
110
                                if (i == -1) break;
111
                                char c = (char) i;
112
                                contents.append(c);
113
                        }
114
                        inputStream.close();
115
                } catch (IOException e) {
116
                        e.printStackTrace();
117
                }
118

    
119
                return contents.toString();
120
        }
121

    
122
        /**
123
         * Crea los ficheros que forman la paleta de color de la version 1.1 a traves
124
         * de un XML que se le pasa por parametro
125
         * @param palettesPath
126
         */
127
        private static void createVersionFromXML(String palettesBasePath, String xml) {
128
                new File(palettesBasePath).mkdir();
129
                KXmlParser parser = new KXmlParser();
130
                StringReader reader = new StringReader(xml);
131
                try {
132
                        parser.setInput(reader);
133
                        int tag = parser.nextTag();
134

    
135
                        parser.require(KXmlParser.START_TAG, null, "palettes");
136
                        tag = parser.nextTag();
137
                        parser.require(KXmlParser.START_TAG, null, "palette_list");
138
                        parser.skipSubTree();
139
                        parser.require(KXmlParser.END_TAG, null, "palette_list");
140
                        tag = parser.nextTag();
141

    
142
                        while (tag == KXmlParser.START_TAG) {
143
                                parser.require(KXmlParser.START_TAG, null, "palette");
144
                                if (parser.getAttributeCount() == 2) {
145
                                        // Generar nuevo fichero
146
                                        KXmlSerializer parserOutput = new KXmlSerializer();
147
                                        FileOutputStream fileOutputStream = new FileOutputStream(palettesBasePath + File.separator + parser.getAttributeValue(0) + ".xml");
148

    
149
                                        parserOutput.setOutput(fileOutputStream, null);
150
                                        parserOutput.startDocument("UTF-8", null);
151
                                        parserOutput.startTag(null, "ColorTable");
152
                                        parserOutput.attribute(null, "name", parser.getAttributeValue(0));
153
                                        parserOutput.attribute(null, "version", "1.1");
154

    
155
                                        tag = parser.nextTag();
156
                                        parser.require(KXmlParser.START_TAG, null, "table");
157
                                        tag = parser.nextTag();
158

    
159
                                        parserOutput.text("\n");
160
                                        ArrayList items = new ArrayList();
161
                                        while (tag == KXmlParser.START_TAG) {
162
                                                parser.require(KXmlParser.START_TAG, null, "entry");
163
                                                if (parser.getAttributeCount() == 3) {
164
                                                        String rgb = parser.getAttributeValue(1).substring(parser.getAttributeValue(1).indexOf(",") + 1, parser.getAttributeValue(1).length());
165

    
166
                                                        int a = Integer.valueOf(parser.getAttributeValue(1).substring(0, parser.getAttributeValue(1).indexOf(","))).intValue();
167
                                                        int r = Integer.valueOf(rgb.substring(0, rgb.indexOf(","))).intValue();
168
                                                        int g = Integer.valueOf(rgb.substring(rgb.indexOf(",") + 1, rgb.lastIndexOf(","))).intValue();
169
                                                        int b = Integer.valueOf(rgb.substring(rgb.lastIndexOf(",") + 1, rgb.length())).intValue();
170

    
171
                                                        ColorItem colorItem = new ColorItem();
172
                                                        colorItem.setColor(new Color(r, g, b, a));
173
                                                        colorItem.setInterpolated(50);
174
                                                        colorItem.setNameClass(parser.getAttributeValue(0));
175
                                                        colorItem.setValue(Double.parseDouble(parser.getAttributeValue(2)));
176
                                                        items.add(colorItem);
177
                                                }
178
                                                tag = parser.nextTag();
179
                                                parser.require(KXmlParser.END_TAG, null, "entry");
180
                                                tag = parser.nextTag();
181
                                        }
182
                                        parser.require(KXmlParser.END_TAG, null, "table");
183
                                        tag = parser.nextTag();
184

    
185
                                        ColorTable colorTable = new ColorTable();
186
                                        colorTable.createPaletteFromColorItems(items, true);
187
                                        items = colorTable.getColorItems();
188
                                        for (int i = 0; i < items.size(); i++) {
189
                                                ColorItem colorItem = (ColorItem) items.get(i);
190
                                                parserOutput.startTag(null, "Color");
191
                                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
192
                                                parserOutput.attribute(null, "name", String.valueOf(colorItem.getNameClass()));
193
                                                Color color = colorItem.getColor();
194
                                                parserOutput.attribute(null, "rgb", String.valueOf(color.getRed() + "," + color.getGreen() + "," + color.getBlue()));
195
                                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
196
                                                parserOutput.endTag(null, "Color");
197
                                                parserOutput.text("\n");
198
                                        }
199

    
200
                                        for (int i = 0; i < items.size(); i++) {
201
                                                ColorItem colorItem = (ColorItem) items.get(i);
202
                                                parserOutput.startTag(null, "Alpha");
203
                                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
204
                                                parserOutput.attribute(null, "alpha", String.valueOf(colorItem.getColor().getAlpha()));
205
                                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
206
                                                parserOutput.endTag(null, "Alpha");
207
                                                parserOutput.text("\n");
208
                                        }
209

    
210
                                        parserOutput.endTag(null, "ColorTable");
211
                                        parserOutput.text("\n");
212
                                        parserOutput.endDocument();
213
                                        // Cerrar nuevo fichero
214
                                        fileOutputStream.close();
215
                                }
216
                                parser.require(KXmlParser.END_TAG, null, "palette");
217
                                tag = parser.nextTag();
218
                        }
219
                        parser.require(KXmlParser.END_TAG, null, "palettes");
220
                } catch (XmlPullParserException xmlEx) {
221
                        System.out.println("El fichero de paletas predeterminadas no tiene la estructura correcta:\n        " + xmlEx.getMessage());
222
                } catch (IOException e) {
223
                }
224
        }
225

    
226
        /**
227
         * Si existe la version de paleta 1.1, no lo actualizar?, en caso contrario,
228
         * buscara la version 1.0 y si lo encuentra lo subir? a la 1.1
229
         * @param palettesPath
230
         */
231
        public static void updateVersion_1_0_to_1_1(String palettesBasePath) {
232
                // Si no existe la paleta antigua, pero si que existe la copia de seguridad,
233
                // la restauramos
234
                File palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
235
                if (!palettesFile.exists()) {
236
                        // Cambiar nombre a antiguo fichero
237
                        File oldFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml~");
238
                        if (oldFile.exists()) {
239
                                oldFile.renameTo(new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml"));
240
                        } else {
241
                                ColorTableLibraryPersistence ctlp = new ColorTableLibraryPersistence();
242
                                String text = ctlp.getDefaultPaletteXML();
243
                                palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
244
                                try {
245
                                        FileWriter writer = new FileWriter(palettesFile);
246
                                        writer.write(text);
247
                                        writer.close();
248
                                } catch (IOException e) {
249
                                }
250
                        }
251
                }
252

    
253
                // Si existe el directorio de la version 1.1 no hacemos la migraci?n
254
                File directoryFile = new File(palettesBasePath);
255
                if (directoryFile.exists())
256
                        return;
257

    
258
                // Si no encontramos la paleta antigua, nos olvidamos de continuar
259
                palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
260
                if (!palettesFile.exists())
261
                        return;
262

    
263
                // Paleta antigua encontrada, podemos migrar a la versi?n nueva
264
                try {
265
                        FileInputStream inputStream = new FileInputStream(palettesFile);
266

    
267
                        StringBuffer contents = new StringBuffer();
268
                        try {
269

    
270
                                int i;
271
                                while (true) {
272
                                        i = inputStream.read();
273
                                        if (i == -1) break;
274
                                        char c = (char) i;
275
                                        contents.append(c);
276
                                }
277
                        } catch (IOException e) {
278
                                e.printStackTrace();
279
                        }
280

    
281
                        createVersionFromXML(palettesBasePath, contents.toString());
282

    
283
                        inputStream.close();
284

    
285
                } catch (FileNotFoundException fnfEx) {
286
                        fnfEx.printStackTrace();
287
                } catch (IOException e) {
288
                        e.printStackTrace();
289
                }
290
        }
291

    
292
        /**
293
         * Si existe la version de paleta 1.0, la actualizara a la 1.1 y renombrar? la
294
         * antigua version.
295
         * @param palettesBasePath
296
         * @param colorTable
297
         */
298
        public static void save_to_1_1(String palettesBasePath, ColorTable colorTable) {
299
                try {
300
                        // Generar nuevo fichero
301
                        KXmlSerializer parserOutput = new KXmlSerializer();
302
                        FileOutputStream out = new FileOutputStream(palettesBasePath + File.separator + colorTable.getName() + ".xml");
303
                        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");
304
                        parserOutput.setOutput(writer);
305
                        parserOutput.startDocument("UTF-8", null);
306
                        parserOutput.startTag(null, "ColorTable");
307
                        parserOutput.attribute(null, "name", colorTable.getName());
308
                        parserOutput.attribute(null, "version", "1.1");
309
                        parserOutput.text("\n");
310

    
311
                        ArrayList items = colorTable.getColorItems();
312
                        for (int i = 0; i < items.size(); i++) {
313
                                ColorItem colorItem = (ColorItem) items.get(i);
314
                                parserOutput.startTag(null, "Color");
315
                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
316
                                if (colorItem.getNameClass() != null)
317
                                        parserOutput.attribute(null, "name", String.valueOf(colorItem.getNameClass()));
318
                                else
319
                                        parserOutput.attribute(null, "name", "");
320
                                Color color = colorItem.getColor();
321
                                parserOutput.attribute(null, "rgb", String.valueOf(color.getRed() + "," + color.getGreen() + "," + color.getBlue()));
322
                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
323
                                parserOutput.endTag(null, "Color");
324
                                parserOutput.text("\n");
325
                        }
326

    
327
                        for (int i = 0; i < items.size(); i++) {
328
                                ColorItem colorItem = (ColorItem) items.get(i);
329
                                parserOutput.startTag(null, "Alpha");
330
                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
331
                                parserOutput.attribute(null, "alpha", String.valueOf(colorItem.getColor().getAlpha()));
332
                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
333
                                parserOutput.endTag(null, "Alpha");
334
                                parserOutput.text("\n");
335
                        }
336

    
337
                        parserOutput.endTag(null, "ColorTable");
338
                        parserOutput.text("\n");
339
                        parserOutput.endDocument();
340
                        // Cerrar nuevo fichero
341
                        writer.close();
342
                } catch (FileNotFoundException e) {
343
                        e.printStackTrace();
344
                } catch (IOException e) {
345
                        e.printStackTrace();
346
                }
347
        }
348

    
349
        /**
350
         * Invocar? todos los metodos de actualizaciones de version
351
         * @param palettesBasePath
352
         */
353
        public static void updateVersion(String palettesBasePath) {
354
                updateVersion_1_0_to_1_1(palettesBasePath);
355
                //updateVersion_1_1_to_1_2(palettesBasePath);
356
        }
357

    
358
        /**
359
         * Devuelve el color si lo encuentra en el arraylist y lo elimina, en caso
360
         * contrario devuelve null
361
         * @param list
362
         * @param value
363
         * @return
364
         */
365
        public static ColorItem getColorItem(ArrayList list, double value) {
366
                for (int i = 0; i < list.size(); i++) {
367
                        if (((ColorItem) list.get(i)).getValue() == value) {
368
                                return (ColorItem) list.remove(i);
369
                        }
370
                }
371
                return null;
372
        }
373

    
374
        /**
375
         * Lee una paleta del fichero xml de paletas y la carga en la tabla del panel.
376
         * @param palettesPath Camino al fichero de paletas predefinidas.
377
         * @param paletteName Nombre de paleta a cargar desde el fichero xml.
378
         * @return Nombre de la paleta
379
         */
380
        public static String loadPalette(String palettesBasePath, String paletteFileName, ArrayList items) {
381
                updateVersion(palettesBasePath);
382

    
383
                items.clear();
384

    
385
                File palettesFile = new File(palettesBasePath + File.separator + paletteFileName);
386
                if (!palettesFile.exists())
387
                        return null;
388

    
389
                try {
390
                        String paletteName = "";
391
                        ArrayList rows = new ArrayList();
392

    
393
                        KXmlParser parser = new KXmlParser();
394
                        FileInputStream in = new FileInputStream(palettesBasePath + File.separator + paletteFileName);
395

    
396
                        InputStreamReader reader = new InputStreamReader(in, "UTF8");
397
                        parser.setInput(reader);
398
                        int tag = parser.nextTag();
399

    
400
                        parser.require(KXmlParser.START_TAG, null, "ColorTable");
401
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
402
                                if (parser.getAttributeName(i).equals("name")) {
403
                                        paletteName = parser.getAttributeValue(i);
404
                                }
405
                        }
406
                        tag = parser.nextTag();
407

    
408
                        while (!((tag == KXmlParser.END_TAG) && (parser.getName().equals("ColorTable")))) {
409
                                try {
410
                                        if (tag == KXmlParser.START_TAG) {
411
                                                if (parser.getName().equals("Color")) {
412
                                                        ColorItem colorItem = new ColorItem();
413
                                                        int a = 255;
414
                                                        for (int i = 0; i < parser.getAttributeCount(); i++) {
415
                                                                if (parser.getAttributeName(i).equals("value")) {
416
                                                                        colorItem.setValue(Double.parseDouble((String) parser.getAttributeValue(i)));
417
                                                                        ColorItem aux = getColorItem(rows, Double.parseDouble((String) parser.getAttributeValue(i)));
418
                                                                        if (aux != null)
419
                                                                                a = aux.getColor().getAlpha();
420
                                                                }
421
                                                                if (parser.getAttributeName(i).equals("name")) {
422
                                                                        colorItem.setNameClass((String) parser.getAttributeValue(i));
423
                                                                }
424
                                                                if (parser.getAttributeName(i).equals("rgb")) {
425
                                                                        String rgb = parser.getAttributeValue(i);
426
                                                                        int r = Integer.valueOf(rgb.substring(0, rgb.indexOf(","))).intValue();
427
                                                                        int g = Integer.valueOf(rgb.substring(rgb.indexOf(",") + 1, rgb.lastIndexOf(","))).intValue();
428
                                                                        int b = Integer.valueOf(rgb.substring(rgb.lastIndexOf(",") + 1, rgb.length())).intValue();
429

    
430
                                                                        colorItem.setColor(new Color(r, g, b, a));
431
                                                                }
432
                                                                if (parser.getAttributeName(i).equals("interpolated")) {
433
                                                                        colorItem.setInterpolated(Double.parseDouble((String) parser.getAttributeValue(i)));
434
                                                                }
435
                                                        }
436

    
437
                                                        rows.add(colorItem);
438
                                                        continue;
439
                                                }
440
                                                if (parser.getName().equals("Alpha")) {
441
                                                        ColorItem colorItem = new ColorItem();
442
                                                        for (int i = 0; i < parser.getAttributeCount(); i++) {
443
                                                                if (parser.getAttributeName(i).equals("value")) {
444
                                                                        colorItem.setValue(Double.parseDouble((String) parser.getAttributeValue(i)));
445
                                                                        ColorItem aux = getColorItem(rows, Double.parseDouble((String) parser.getAttributeValue(i)));
446
                                                                        if (aux != null) {
447
                                                                                colorItem.setNameClass(aux.getNameClass());
448
                                                                                colorItem.setInterpolated(aux.getInterpolated());
449
                                                                                colorItem.setColor(new Color(aux.getColor().getRed(), aux.getColor().getGreen(), aux.getColor().getBlue(), colorItem.getColor().getAlpha()));
450
                                                                        }
451
                                                                }
452
                                                                if (parser.getAttributeName(i).equals("alpha")) {
453
                                                                        int a = Integer.parseInt(parser.getAttributeValue(i));
454

    
455
                                                                        colorItem.setColor(new Color(colorItem.getColor().getRed(), colorItem.getColor().getGreen(), colorItem.getColor().getBlue(), a));
456
                                                                }
457
                                                                if (parser.getAttributeName(i).equals("interpolated")) {
458
                                                                        colorItem.setInterpolated(Double.parseDouble((String) parser.getAttributeValue(i)));
459
                                                                }
460
                                                        }
461

    
462
                                                        rows.add(colorItem);
463
                                                        continue;
464
                                                }
465
                                        }
466
                                } finally {
467
                                        tag = parser.nextTag();
468
                                }
469
                        }
470

    
471
                        for (int i = 0; i < rows.size(); i++)
472
                                items.add(rows.get(i));
473

    
474
                        reader.close();
475
                        return paletteName;
476
                } catch (FileNotFoundException fnfEx) {
477
                        fnfEx.printStackTrace();
478
                } catch (XmlPullParserException xmlEx) {
479
                        System.out.println("El fichero de paletas predeterminadas no tiene la estructura correcta:\n        " + xmlEx.getMessage());
480
                } catch (IOException e) {
481
                }
482
                return null;
483
        }
484
}