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 / datastruct / persistence / DefaultColorTableLibrary.java @ 162

History | View | Annotate | Download (18.1 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.datastruct.persistence;
23

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

    
38
import org.gvsig.fmap.dal.coverage.datastruct.ColorItem;
39
import org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary;
40
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
41
import org.gvsig.raster.impl.datastruct.ColorItemImpl;
42
import org.gvsig.raster.impl.store.properties.DataStoreColorTable;
43
import org.kxml2.io.KXmlParser;
44
import org.kxml2.io.KXmlSerializer;
45
import org.xmlpull.v1.XmlPullParserException;
46
/**
47
 * La clase ColorTableLibraryPersistence sirve para controlar las tablas de color
48
 * genericas, como si fuera una libreria de tablas de color. Aqu? se comprueban
49
 * los cambios de versi?n.
50
 *
51
 * @version 02/07/2007
52
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
53
 */
54
public class DefaultColorTableLibrary implements ColorTableLibrary {
55
        private static DefaultColorTableLibrary  instance = null;
56
        
57
        /**
58
         * Gets the ColorTableLibrary
59
         * @return
60
         */
61
        public static ColorTableLibrary getInstance() {
62
                if(instance == null)
63
                        instance = new DefaultColorTableLibrary();
64
                return instance;
65
        }
66
        
67
    /*
68
     * (non-Javadoc)
69
     * @see org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary#createColorTable()
70
     */
71
    public ColorTable createColorTable() {
72
            return new DataStoreColorTable();
73
    }
74
    
75
        /**
76
         * Devuelve la lista de ficheros de paletas, si no existe el fichero devolvera
77
         * una lista vacia
78
         * @param palettesBasePath
79
         * @return
80
         */
81
        private ArrayList<String> getPaletteFileListDisc(String palettesBasePath) {
82
                updateVersion(palettesBasePath);
83

    
84
                File paletteFiles = new File(palettesBasePath);
85

    
86
                ArrayList<String> fileList = new ArrayList<String>();
87

    
88
                if (paletteFiles.exists()) {
89
                        File[] list = paletteFiles.listFiles();
90
                        for (int i = 0; i < list.length; i++)
91
                                fileList.add(list[i].getName());
92
                }
93

    
94
                return fileList;
95
        }
96

    
97
        /*
98
         * (non-Javadoc)
99
         * @see org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary#getPaletteFileList(java.lang.String)
100
         */
101
        public ArrayList<String> getPaletteFileList(String palettesBasePath) {
102
                return getPaletteFileList(palettesBasePath, true);
103
        }
104

    
105
        /**
106
         * Devuelve la lista de ficheros de paletas, en caso de que no exista la
107
         * paleta y se especifique forceCreate a true, se creara la paleta por defecto.
108
         * @param palettesBasePath
109
         * @param forceCreate
110
         * @return
111
         */
112
        public ArrayList<String> getPaletteFileList(String palettesBasePath, boolean forceCreate) {
113
                ArrayList <String>fileList = getPaletteFileListDisc(palettesBasePath);
114

    
115
                if (forceCreate && (fileList.size() == 0)) {
116
                        DefaultColorTableLibrary persistence = new DefaultColorTableLibrary();
117
                        createVersionFromXML(palettesBasePath, persistence.getDefaultPaletteXML());
118
                        fileList = getPaletteFileListDisc(palettesBasePath);
119
                }
120

    
121
                return fileList;
122
        }
123

    
124
        /**
125
         * Devuelve el XML de una paleta por defecto
126
         * @return
127
         */
128
        public String getDefaultPaletteXML() {
129
                URL url = getClass().getResource("xml/palettes.xml");
130
                StringBuffer contents = new StringBuffer();
131
                try {
132
                        InputStream inputStream = url.openStream();
133

    
134
                        int i;
135
                        while (true) {
136
                                i = inputStream.read();
137
                                if (i == -1) break;
138
                                char c = (char) i;
139
                                contents.append(c);
140
                        }
141
                        inputStream.close();
142
                } catch (IOException e) {
143
                        e.printStackTrace();
144
                }
145

    
146
                return contents.toString();
147
        }
148

    
149
        /**
150
         * Crea los ficheros que forman la paleta de color de la version 1.1 a traves
151
         * de un XML que se le pasa por parametro
152
         * @param palettesPath
153
         */
154
        private void createVersionFromXML(String palettesBasePath, String xml) {
155
                new File(palettesBasePath).mkdir();
156
                KXmlParser parser = new KXmlParser();
157
                StringReader reader = new StringReader(xml);
158
                try {
159
                        parser.setInput(reader);
160
                        int tag = parser.nextTag();
161

    
162
                        parser.require(KXmlParser.START_TAG, null, "palettes");
163
                        tag = parser.nextTag();
164
                        parser.require(KXmlParser.START_TAG, null, "palette_list");
165
                        parser.skipSubTree();
166
                        parser.require(KXmlParser.END_TAG, null, "palette_list");
167
                        tag = parser.nextTag();
168

    
169
                        while (tag == KXmlParser.START_TAG) {
170
                                parser.require(KXmlParser.START_TAG, null, "palette");
171
                                if (parser.getAttributeCount() == 2) {
172
                                        // Generar nuevo fichero
173
                                        KXmlSerializer parserOutput = new KXmlSerializer();
174
                                        FileOutputStream fileOutputStream = new FileOutputStream(palettesBasePath + File.separator + parser.getAttributeValue(0) + ".xml");
175

    
176
                                        parserOutput.setOutput(fileOutputStream, null);
177
                                        parserOutput.startDocument("UTF-8", null);
178
                                        parserOutput.startTag(null, "ColorTable");
179
                                        parserOutput.attribute(null, "name", parser.getAttributeValue(0));
180
                                        parserOutput.attribute(null, "version", "1.1");
181

    
182
                                        tag = parser.nextTag();
183
                                        parser.require(KXmlParser.START_TAG, null, "table");
184
                                        tag = parser.nextTag();
185

    
186
                                        parserOutput.text("\n");
187
                                        ArrayList<ColorItem> items = new ArrayList<ColorItem>();
188
                                        while (tag == KXmlParser.START_TAG) {
189
                                                parser.require(KXmlParser.START_TAG, null, "entry");
190
                                                if (parser.getAttributeCount() == 3) {
191
                                                        String rgb = parser.getAttributeValue(1).substring(parser.getAttributeValue(1).indexOf(",") + 1, parser.getAttributeValue(1).length());
192

    
193
                                                        int a = Integer.valueOf(parser.getAttributeValue(1).substring(0, parser.getAttributeValue(1).indexOf(","))).intValue();
194
                                                        int r = Integer.valueOf(rgb.substring(0, rgb.indexOf(","))).intValue();
195
                                                        int g = Integer.valueOf(rgb.substring(rgb.indexOf(",") + 1, rgb.lastIndexOf(","))).intValue();
196
                                                        int b = Integer.valueOf(rgb.substring(rgb.lastIndexOf(",") + 1, rgb.length())).intValue();
197

    
198
                                                        ColorItem colorItem = new ColorItemImpl();
199
                                                        colorItem.setColor(new Color(r, g, b, a));
200
                                                        colorItem.setInterpolated(50);
201
                                                        colorItem.setNameClass(parser.getAttributeValue(0));
202
                                                        colorItem.setValue(Double.parseDouble(parser.getAttributeValue(2)));
203
                                                        items.add(colorItem);
204
                                                }
205
                                                tag = parser.nextTag();
206
                                                parser.require(KXmlParser.END_TAG, null, "entry");
207
                                                tag = parser.nextTag();
208
                                        }
209
                                        parser.require(KXmlParser.END_TAG, null, "table");
210
                                        tag = parser.nextTag();
211

    
212
                                        ColorTable colorTable = new DataStoreColorTable();
213
                                        colorTable.createPaletteFromColorItems(items, true);
214
                                        items = colorTable.getColorItems();
215
                                        for (int i = 0; i < items.size(); i++) {
216
                                                ColorItem colorItem = (ColorItem) items.get(i);
217
                                                parserOutput.startTag(null, "Color");
218
                                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
219
                                                parserOutput.attribute(null, "name", String.valueOf(colorItem.getNameClass()));
220
                                                Color color = colorItem.getColor();
221
                                                parserOutput.attribute(null, "rgb", String.valueOf(color.getRed() + "," + color.getGreen() + "," + color.getBlue()));
222
                                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
223
                                                parserOutput.endTag(null, "Color");
224
                                                parserOutput.text("\n");
225
                                        }
226

    
227
                                        for (int i = 0; i < items.size(); i++) {
228
                                                ColorItem colorItem = (ColorItem) items.get(i);
229
                                                parserOutput.startTag(null, "Alpha");
230
                                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
231
                                                parserOutput.attribute(null, "alpha", String.valueOf(colorItem.getColor().getAlpha()));
232
                                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
233
                                                parserOutput.endTag(null, "Alpha");
234
                                                parserOutput.text("\n");
235
                                        }
236

    
237
                                        parserOutput.endTag(null, "ColorTable");
238
                                        parserOutput.text("\n");
239
                                        parserOutput.endDocument();
240
                                        // Cerrar nuevo fichero
241
                                        fileOutputStream.close();
242
                                }
243
                                parser.require(KXmlParser.END_TAG, null, "palette");
244
                                tag = parser.nextTag();
245
                        }
246
                        parser.require(KXmlParser.END_TAG, null, "palettes");
247
                } catch (XmlPullParserException xmlEx) {
248
                        System.out.println("El fichero de paletas predeterminadas no tiene la estructura correcta:\n        " + xmlEx.getMessage());
249
                } catch (IOException e) {
250
                }
251
        }
252

    
253
        /**
254
         * Si existe la version de paleta 1.1, no lo actualizar?, en caso contrario,
255
         * buscara la version 1.0 y si lo encuentra lo subir? a la 1.1
256
         * @param palettesPath
257
         */
258
        public void updateVersion_1_0_to_1_1(String palettesBasePath) {
259
                // Si no existe la paleta antigua, pero si que existe la copia de seguridad,
260
                // la restauramos
261
                File palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
262
                if (!palettesFile.exists()) {
263
                        // Cambiar nombre a antiguo fichero
264
                        File oldFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml~");
265
                        if (oldFile.exists()) {
266
                                oldFile.renameTo(new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml"));
267
                        } else {
268
                                DefaultColorTableLibrary ctlp = new DefaultColorTableLibrary();
269
                                String text = ctlp.getDefaultPaletteXML();
270
                                palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
271
                                try {
272
                                        FileWriter writer = new FileWriter(palettesFile);
273
                                        writer.write(text);
274
                                        writer.close();
275
                                } catch (IOException e) {
276
                                }
277
                        }
278
                }
279

    
280
                // Si existe el directorio de la version 1.1 no hacemos la migraci?n
281
                File directoryFile = new File(palettesBasePath);
282
                if (directoryFile.exists())
283
                        return;
284

    
285
                // Si no encontramos la paleta antigua, nos olvidamos de continuar
286
                palettesFile = new File(new File(palettesBasePath).getParent().toString() + File.separator + "palettes.xml");
287
                if (!palettesFile.exists())
288
                        return;
289

    
290
                // Paleta antigua encontrada, podemos migrar a la versi?n nueva
291
                try {
292
                        FileInputStream inputStream = new FileInputStream(palettesFile);
293

    
294
                        StringBuffer contents = new StringBuffer();
295
                        try {
296

    
297
                                int i;
298
                                while (true) {
299
                                        i = inputStream.read();
300
                                        if (i == -1) break;
301
                                        char c = (char) i;
302
                                        contents.append(c);
303
                                }
304
                        } catch (IOException e) {
305
                                e.printStackTrace();
306
                        }
307

    
308
                        createVersionFromXML(palettesBasePath, contents.toString());
309

    
310
                        inputStream.close();
311

    
312
                } catch (FileNotFoundException fnfEx) {
313
                        fnfEx.printStackTrace();
314
                } catch (IOException e) {
315
                        e.printStackTrace();
316
                }
317
        }
318

    
319
        /**
320
         * Si existe la version de paleta 1.0, la actualizara a la 1.1 y renombrar? la
321
         * antigua version.
322
         * @param palettesBasePath
323
         * @param colorTable
324
         */
325
        public void save_to_1_1(String palettesBasePath, ColorTable colorTable) {
326
                try {
327
                        // Generar nuevo fichero
328
                        KXmlSerializer parserOutput = new KXmlSerializer();
329
                        FileOutputStream out = new FileOutputStream(palettesBasePath + File.separator + colorTable.getName() + ".xml");
330
                        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");
331
                        parserOutput.setOutput(writer);
332
                        parserOutput.startDocument("UTF-8", null);
333
                        parserOutput.startTag(null, "ColorTable");
334
                        parserOutput.attribute(null, "name", colorTable.getName());
335
                        parserOutput.attribute(null, "version", "1.1");
336
                        parserOutput.text("\n");
337

    
338
                        ArrayList<ColorItem> items = colorTable.getColorItems();
339
                        for (int i = 0; i < items.size(); i++) {
340
                                ColorItem colorItem = (ColorItem) items.get(i);
341
                                parserOutput.startTag(null, "Color");
342
                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
343
                                if (colorItem.getNameClass() != null)
344
                                        parserOutput.attribute(null, "name", String.valueOf(colorItem.getNameClass()));
345
                                else
346
                                        parserOutput.attribute(null, "name", "");
347
                                Color color = colorItem.getColor();
348
                                parserOutput.attribute(null, "rgb", String.valueOf(color.getRed() + "," + color.getGreen() + "," + color.getBlue()));
349
                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
350
                                parserOutput.endTag(null, "Color");
351
                                parserOutput.text("\n");
352
                        }
353

    
354
                        for (int i = 0; i < items.size(); i++) {
355
                                ColorItem colorItem = (ColorItem) items.get(i);
356
                                parserOutput.startTag(null, "Alpha");
357
                                parserOutput.attribute(null, "value", String.valueOf(colorItem.getValue()));
358
                                parserOutput.attribute(null, "alpha", String.valueOf(colorItem.getColor().getAlpha()));
359
                                parserOutput.attribute(null, "interpolated", String.valueOf(colorItem.getInterpolated()));
360
                                parserOutput.endTag(null, "Alpha");
361
                                parserOutput.text("\n");
362
                        }
363

    
364
                        parserOutput.endTag(null, "ColorTable");
365
                        parserOutput.text("\n");
366
                        parserOutput.endDocument();
367
                        // Cerrar nuevo fichero
368
                        writer.close();
369
                } catch (FileNotFoundException e) {
370
                        e.printStackTrace();
371
                } catch (IOException e) {
372
                        e.printStackTrace();
373
                }
374
        }
375

    
376
        /**
377
         * Invocar? todos los metodos de actualizaciones de version
378
         * @param palettesBasePath
379
         */
380
        public void updateVersion(String palettesBasePath) {
381
                updateVersion_1_0_to_1_1(palettesBasePath);
382
                //updateVersion_1_1_to_1_2(palettesBasePath);
383
        }
384

    
385
        /**
386
         * Devuelve el color si lo encuentra en el arraylist y lo elimina, en caso
387
         * contrario devuelve null
388
         * @param list
389
         * @param value
390
         * @return
391
         */
392
        public ColorItem getColorItem(ArrayList<ColorItem> list, double value) {
393
                for (int i = 0; i < list.size(); i++) {
394
                        if (((ColorItem) list.get(i)).getValue() == value) {
395
                                return (ColorItem) list.remove(i);
396
                        }
397
                }
398
                return null;
399
        }
400

    
401
        /*
402
         * (non-Javadoc)
403
         * @see org.gvsig.fmap.dal.coverage.datastruct.ColorTableLibrary#loadPalette(java.lang.String, java.lang.String, java.util.ArrayList)
404
         */
405
        public String loadPalette(String palettesBasePath, String paletteFileName, ArrayList<ColorItem> items) {
406
                updateVersion(palettesBasePath);
407

    
408
                items.clear();
409

    
410
                File palettesFile = new File(palettesBasePath + File.separator + paletteFileName);
411
                if (!palettesFile.exists())
412
                        return null;
413

    
414
                try {
415
                        String paletteName = "";
416
                        ArrayList<ColorItem> rows = new ArrayList<ColorItem>();
417

    
418
                        KXmlParser parser = new KXmlParser();
419
                        FileInputStream in = new FileInputStream(palettesBasePath + File.separator + paletteFileName);
420

    
421
                        InputStreamReader reader = new InputStreamReader(in, "UTF8");
422
                        parser.setInput(reader);
423
                        int tag = parser.nextTag();
424

    
425
                        parser.require(KXmlParser.START_TAG, null, "ColorTable");
426
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
427
                                if (parser.getAttributeName(i).equals("name")) {
428
                                        paletteName = parser.getAttributeValue(i);
429
                                }
430
                        }
431
                        tag = parser.nextTag();
432

    
433
                        while (!((tag == KXmlParser.END_TAG) && (parser.getName().equals("ColorTable")))) {
434
                                try {
435
                                        if (tag == KXmlParser.START_TAG) {
436
                                                if (parser.getName().equals("Color")) {
437
                                                        ColorItem colorItem = new ColorItemImpl();
438
                                                        int a = 255;
439
                                                        for (int i = 0; i < parser.getAttributeCount(); i++) {
440
                                                                if (parser.getAttributeName(i).equals("value")) {
441
                                                                        colorItem.setValue(Double.parseDouble((String) parser.getAttributeValue(i)));
442
                                                                        ColorItem aux = getColorItem(rows, Double.parseDouble((String) parser.getAttributeValue(i)));
443
                                                                        if (aux != null)
444
                                                                                a = aux.getColor().getAlpha();
445
                                                                }
446
                                                                if (parser.getAttributeName(i).equals("name")) {
447
                                                                        colorItem.setNameClass((String) parser.getAttributeValue(i));
448
                                                                }
449
                                                                if (parser.getAttributeName(i).equals("rgb")) {
450
                                                                        String rgb = parser.getAttributeValue(i);
451
                                                                        int r = Integer.valueOf(rgb.substring(0, rgb.indexOf(","))).intValue();
452
                                                                        int g = Integer.valueOf(rgb.substring(rgb.indexOf(",") + 1, rgb.lastIndexOf(","))).intValue();
453
                                                                        int b = Integer.valueOf(rgb.substring(rgb.lastIndexOf(",") + 1, rgb.length())).intValue();
454

    
455
                                                                        colorItem.setColor(new Color(r, g, b, 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
                                                if (parser.getName().equals("Alpha")) {
466
                                                        ColorItem colorItem = new ColorItemImpl();
467
                                                        for (int i = 0; i < parser.getAttributeCount(); i++) {
468
                                                                if (parser.getAttributeName(i).equals("value")) {
469
                                                                        colorItem.setValue(Double.parseDouble((String) parser.getAttributeValue(i)));
470
                                                                        ColorItem aux = getColorItem(rows, Double.parseDouble((String) parser.getAttributeValue(i)));
471
                                                                        if (aux != null) {
472
                                                                                colorItem.setNameClass(aux.getNameClass());
473
                                                                                colorItem.setInterpolated(aux.getInterpolated());
474
                                                                                colorItem.setColor(new Color(aux.getColor().getRed(), aux.getColor().getGreen(), aux.getColor().getBlue(), colorItem.getColor().getAlpha()));
475
                                                                        }
476
                                                                }
477
                                                                if (parser.getAttributeName(i).equals("alpha")) {
478
                                                                        int a = Integer.parseInt(parser.getAttributeValue(i));
479

    
480
                                                                        colorItem.setColor(new Color(colorItem.getColor().getRed(), colorItem.getColor().getGreen(), colorItem.getColor().getBlue(), a));
481
                                                                }
482
                                                                if (parser.getAttributeName(i).equals("interpolated")) {
483
                                                                        colorItem.setInterpolated(Double.parseDouble((String) parser.getAttributeValue(i)));
484
                                                                }
485
                                                        }
486

    
487
                                                        rows.add(colorItem);
488
                                                        continue;
489
                                                }
490
                                        }
491
                                } finally {
492
                                        tag = parser.nextTag();
493
                                }
494
                        }
495

    
496
                        for (int i = 0; i < rows.size(); i++)
497
                                items.add(rows.get(i));
498

    
499
                        reader.close();
500
                        return paletteName;
501
                } catch (FileNotFoundException fnfEx) {
502
                        fnfEx.printStackTrace();
503
                } catch (XmlPullParserException xmlEx) {
504
                        System.out.println("El fichero de paletas predeterminadas no tiene la estructura correcta:\n        " + xmlEx.getMessage());
505
                } catch (IOException e) {
506
                }
507
                return null;
508
        }
509
}