Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / rendering / VectorialUniqueValueLegend.java @ 13032

History | View | Annotate | Download (18.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.rendering;
42

    
43
import java.sql.Types;
44
import java.text.ParseException;
45
import java.util.ArrayList;
46
import java.util.Comparator;
47
import java.util.TreeMap;
48

    
49
import org.apache.log4j.Logger;
50

    
51
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
52
import com.hardcode.gdbms.engine.data.DataSource;
53
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
54
import com.hardcode.gdbms.engine.instruction.IncompatibleTypesException;
55
import com.hardcode.gdbms.engine.instruction.SemanticException;
56
import com.hardcode.gdbms.engine.values.BooleanValue;
57
import com.hardcode.gdbms.engine.values.NullValue;
58
import com.hardcode.gdbms.engine.values.StringValue;
59
import com.hardcode.gdbms.engine.values.Value;
60
import com.hardcode.gdbms.engine.values.ValueFactory;
61
import com.iver.cit.gvsig.fmap.core.IFeature;
62
import com.iver.cit.gvsig.fmap.core.ISLDCompatible;
63
import com.iver.cit.gvsig.fmap.core.SLDTags;
64
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
65
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
66
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
67
import com.iver.cit.gvsig.fmap.layers.XMLException;
68
import com.iver.utiles.XMLEntity;
69

    
70
/**
71
 * Leyenda vectorial por valores ?nicos.
72
 * @author   Vicente Caballero Navarro
73
 */
74
//public class VectorialUniqueValueLegend implements IVectorialUniqueValueLegend {
75
public class VectorialUniqueValueLegend implements IVectorialUniqueValueLegend {
76
        private static final Logger log = Logger.getLogger(VectorialUniqueValueLegend.class);
77
        protected static int FIELD_ID;
78
        protected DataSource dataSource;
79

    
80
        private TreeMap symbols = new TreeMap(new Comparator() {
81
                public int compare(Object o1, Object o2) {
82
                        if ((o1 != null) && (o2 != null)) {
83
                                Value v2 = (Value) o2;
84
                                Value v1 = (Value) o1;
85
                                BooleanValue boolVal;
86

    
87
                                // TODO estas dos comprobaciones son por evitar un bug en el gdbms, cuando se solucione se puede eliminar.
88
                                if (v1 instanceof NullValue && v2 instanceof NullValue) {
89
                                        return 0;
90
                                }
91

    
92
                                if (v1 instanceof NullValue) {
93
                                        return -1;
94
                                }
95

    
96
                                if (v2 instanceof NullValue) {
97
                                        return 1;
98
                                }
99

    
100
                                try {
101
                                        boolVal = (BooleanValue) (v1.greater(v2));
102

    
103
                                        if (boolVal.getValue()) {
104
                                                return 1;
105
                                        }
106

    
107
                                        boolVal = (BooleanValue) (v1.less(v2));
108

    
109
                                        if (boolVal.getValue()) {
110
                                                return -1;
111
                                        }
112
                                } catch (IncompatibleTypesException e) {
113
                                        // TODO Auto-generated catch block
114
                                        //e.printStackTrace();
115
                                }
116

    
117
                                try {
118
                                        if (((BooleanValue) v1.equals(v2)).getValue()) {
119
                                                return 0;
120
                                        }
121
                                } catch (IncompatibleTypesException e) {
122
                                        // TODO Auto-generated catch block
123
                                        //e.printStackTrace();
124
                                }
125

    
126
                                if (v1 instanceof StringValue) {
127
                                        return -1;
128
                                }
129

    
130
                                if (v2 instanceof StringValue) {
131
                                        return 1;
132
                                }
133
                        }
134

    
135
                        return 0;
136
                }
137
        }); // Para poder ordenar
138
    private ArrayList keys = new ArrayList(); // En lugar de un HashSet, para tener acceso por ?ndice
139
    private String[] fieldNames;
140
//    protected int fieldId = -1;
141
    private String labelFieldName;
142
    private String labelFieldHeight;
143
    private String labelFieldRotation;
144
    private ISymbol defaultSymbol;
145
    private int shapeType;
146
    private String valueType = NullValue.class.getName();
147
    private boolean useDefaultSymbol = false;
148
        private ZSort zSort;
149

    
150

    
151
    /**
152
     * Crea un nuevo VectorialUniqueValueLegend.
153
     */
154
    public VectorialUniqueValueLegend() {
155
    }
156

    
157
    /**
158
     * Crea un nuevo VectorialUniqueValueLegend.
159
     *
160
     * @param shapeType Tipo de shape.
161
     */
162
    public VectorialUniqueValueLegend(int shapeType) {
163
        setShapeType(shapeType);
164
    }
165

    
166
     public void setShapeType(int shapeType) {
167
            if (this.shapeType != shapeType) {
168
                    defaultSymbol = SymbologyFactory.createDefaultSymbolByShapeType(shapeType);
169
                    this.shapeType = shapeType;
170
            }
171
    }
172

    
173
    public void setValueSymbolByID(int id, ISymbol symbol) {
174
        symbols.put(keys.get(id), symbol);
175
    }
176

    
177
    /**
178
     * Se usa en la tabla que muestra una leyenda.
179
     *        @deprecated use setValueSymbolByID(int id, ISymbol symbol);
180
     * @param id
181
     * @param symbol
182
     */
183
    public void setValueSymbol(int id, ISymbol symbol) {
184
        symbols.put(keys.get(id), symbol);
185
    }
186

    
187
    public Object[] getValues() {
188
        return symbols.keySet().toArray(new Object[0]);
189
    }
190

    
191
    public void addSymbol(Object key, ISymbol symbol) {
192
        Object resul;
193
        resul = symbols.put(key, symbol);
194

    
195
        if (resul != null) {
196
                log.error("Error: la clave " + key +
197
                " ya exist?a. Resul = " + resul);
198
            log.warn("symbol nuevo:" + symbol.getDescription() +
199
                " Sviejo= " + ((ISymbol) resul).getDescription());
200
        } else {
201
            keys.add(key);
202

    
203
            if (!key.getClass().equals(NullValue.class)) {
204
                valueType = key.getClass().getName();
205
            }
206
        }
207
    }
208

    
209
    public void clear() {
210
        keys.clear();
211
        symbols.clear();
212
    }
213

    
214
    public String[] getDescriptions() {
215
        String[] descriptions = new String[symbols.size()];
216
        ISymbol[] auxSym = getSymbols();
217

    
218
        for (int i = 0; i < descriptions.length; i++)
219
            descriptions[i] = auxSym[i].getDescription();
220

    
221
        return descriptions;
222
    }
223

    
224
     public ISymbol[] getSymbols() {
225
        return (ISymbol[]) symbols.values().toArray(new ISymbol[0]);
226
    }
227

    
228
     public String[] getFieldNames() {
229
             return fieldNames;
230
     }
231

    
232
     public void setFieldNames(String[] fNames) {
233
            fieldNames = fNames;
234
    }
235

    
236
    /*
237
     * @see com.iver.cit.gvsig.fmap.rendering.IVectorialLegend#getSymbol(int)
238
     */
239
    public ISymbol getSymbol(int recordIndex) throws ReadDriverException {
240
                Value val = dataSource.getFieldValue(recordIndex, FIELD_ID);
241
                ISymbol theSymbol = getSymbolByValue(val);
242

    
243
                return theSymbol;
244
        }
245

    
246
    /**
247
         * Devuelve un s?mbolo a partir de una IFeature. OJO!! Cuando usamos un
248
         * feature iterator de base de datos el ?nico campo que vendr? rellenado es
249
         * el de fieldID. Los dem?s vendr?n a nulos para ahorra tiempo de creaci?n.
250
         *
251
         * @param feat
252
         *            IFeature
253
         *
254
         * @return S?mbolo.
255
         */
256
    public ISymbol getSymbolByFeature(IFeature feat) {
257
        Value val = feat.getAttribute(FIELD_ID);
258
        // Value val = feat.getAttribute(0);
259
        ISymbol theSymbol = getSymbolByValue(val);
260

    
261
        if (theSymbol != null) {
262
                return theSymbol;
263

    
264
        } else {
265
                return getDefaultSymbol();
266
        }
267
    }
268

    
269
    public ISymbol getDefaultSymbol() {
270

    
271
            NullUniqueValue nuv=new NullUniqueValue();
272
            if (symbols.containsKey(nuv))
273
                    return (ISymbol)symbols.get(nuv);
274

    
275
            if(defaultSymbol==null)//mio
276
                    defaultSymbol=SymbologyFactory.createDefaultFillSymbol();//mio
277
        return defaultSymbol;
278
    }
279

    
280
        public String getSLDString(String name)        {
281
            try {
282

    
283
                        XmlBuilder xmlBuilder = new XmlBuilder();
284
                        xmlBuilder.writeHeader();
285
                        xmlBuilder.openTag(SLDTags.SLD_ROOT, SLDTags.VERSION_ATTR, SLDTags.VERSION_1_0_0);
286
                        xmlBuilder.openTag(SLDTags.NAMEDLAYER);
287
                        xmlBuilder.writeTag(SLDTags.NAME,name);
288
                        xmlBuilder.openTag(SLDTags.USERSTYLE);
289
                        xmlBuilder.openTag(SLDTags.FEATURETYPESTYLE);
290
                        //xmlBuilder.writeTag(SLDTags.FEATURETYPENAME,"fieldName");
291

    
292
                        ISymbol[] symbols = this.getSymbols();
293
                        Object[] values = this.getValues();
294
                        String valueStr = null;
295

    
296
                        for(int i = 0; i < symbols.length; i++ ){
297
                                valueStr = values[i].toString();
298
                                xmlBuilder.openTag(SLDTags.RULE);
299
                                xmlBuilder.writeTag(SLDTags.NAME, valueStr);
300
                                xmlBuilder.openTag(SLDTags.FILTER);
301
                                xmlBuilder.openTag(SLDTags.PROPERTYISEQUALTO);
302
                                xmlBuilder.writeTag(SLDTags.PROPERTYNAME, fieldNames[0]);
303
                                xmlBuilder.writeTag(SLDTags.LITERAL, valueStr);
304
                                xmlBuilder.closeTag();
305
                                xmlBuilder.closeTag();
306
                                if (symbols[i] instanceof ISLDCompatible) {
307
                                        ISLDCompatible symSLD = (ISLDCompatible) symbols[i];
308
                                        xmlBuilder.writeRaw(symSLD.toSLD());
309
                                } else
310
                                        throw new RuntimeException("Cannot convert Symbol " + i + " " + symbols[i].getDescription() + " to SLD");
311

    
312
                                xmlBuilder.closeTag();
313
                        }
314

    
315
                        xmlBuilder.closeTag();
316
                        xmlBuilder.closeTag();
317
                        xmlBuilder.closeTag();
318
                        xmlBuilder.closeTag();
319
                        return xmlBuilder.getXML();
320

    
321
            } catch (Exception e) {
322
                    e.printStackTrace();
323
                    return null;
324
            }
325
        }
326

    
327
    public XMLEntity getXMLEntity() {
328
        XMLEntity xml = new XMLEntity();
329
        xml.putProperty("className", this.getClass().getName());
330
        xml.putProperty("fieldNames", fieldNames[0]);
331
        xml.putProperty("labelfield", labelFieldName);
332
        xml.putProperty("labelFieldHeight", labelFieldHeight);
333
        xml.putProperty("labelFieldRotation", labelFieldRotation);
334

    
335
        xml.putProperty("useDefaultSymbol", useDefaultSymbol);
336
        xml.addChild(getDefaultSymbol().getXMLEntity());
337
        xml.putProperty("numKeys", keys.size());
338

    
339
        if (keys.size() > 0) {
340
            xml.putProperty("tipoValueKeys", valueType);
341

    
342
            String[] sk = new String[keys.size()];
343
            String[] sv = new String[keys.size()];
344
            int[] stk = new int[keys.size()];
345
            int[] stv = new int[keys.size()];
346
            ISymbol[] fsymbols = getSymbols();
347
            Object[] values = getValues();
348

    
349
            for (int i = 0; i < keys.size(); i++) {
350
                    if (((Value) keys.get(i)).toString().equals("")) {
351
                            sk[i] =" ";
352
                    }else {
353
                            sk[i] = ((Value) keys.get(i)).toString();
354
                    }
355
                    if (((Value) values[i]).toString().equals("")) {
356
                            sv[i] =" ";
357
                    }else {
358
                            sv[i] = ((Value) values[i]).toString();
359
                    }
360
                    stk[i]= ((Value)keys.get(i)).getSQLType();
361
                    stv[i]= ((Value)values[i]).getSQLType();
362
                xml.addChild(fsymbols[i].getXMLEntity());
363

    
364
                ///System.out.println("get-----------"+sk[i]+"--"+fsymbols[i].getDescription()+"---"+fsymbols[i].getColor());
365
            }
366

    
367
            xml.putProperty("keys", sk);
368
            xml.putProperty("values", sv);
369
            xml.putProperty("typeKeys",stk);
370
            xml.putProperty("typeValues",stv);
371
        }
372

    
373
        return xml;
374
    }
375

    
376
    public void setXMLEntity03(XMLEntity xml) {
377
        clear();
378
        setFieldNames(new String[] {xml.getStringProperty("fieldName")});
379

    
380
        int useDefaultSymbol = xml.getIntProperty("useDefaultSymbol");
381

    
382
        if (useDefaultSymbol == 1) {
383
            setDefaultSymbol(FSymbol.createFromXML03(xml.getChild(0)));
384
        } else {
385
            setDefaultSymbol(null);
386
        }
387

    
388
        int numKeys = xml.getIntProperty("numKeys");
389

    
390
        if (numKeys > 0) {
391
            String className = xml.getStringProperty("tipoValueKeys");
392
            String[] sk = xml.getStringArrayProperty("keys");
393
            String[] sv = xml.getStringArrayProperty("values");
394
            Value auxValue;
395
            Value auxValue2;
396

    
397
            for (int i = 0; i < numKeys; i++) {
398
                try {
399
                    auxValue = ValueFactory.createValue(sk[i], className);
400
                    auxValue2 = ValueFactory.createValue(sv[i], className);
401

    
402
                    ISymbol sym = FSymbol.createFromXML03(xml.getChild(i +
403
                                useDefaultSymbol));
404

    
405
                    symbols.put(auxValue2, sym);
406
                    keys.add(auxValue);
407

    
408
                } catch (SemanticException e) {
409
                        log.error("Exception", e);
410
                    e.printStackTrace();
411
                }
412
            }
413
        }
414
    }
415

    
416
    public void setXMLEntity(XMLEntity xml) {
417
        clear();
418
        if (xml.contains("fieldName"))
419
                setFieldNames(new String[] {xml.getStringProperty("fieldName")});
420
        else
421
                setFieldNames(xml.getStringArrayProperty("fieldNames"));
422

    
423
        useDefaultSymbol = xml.getBooleanProperty("useDefaultSymbol");
424
        setDefaultSymbol(SymbologyFactory.createSymbolFromXML(xml.getChild(0), null));
425

    
426
        int numKeys = xml.getIntProperty("numKeys");
427

    
428
        if (numKeys > 0) {
429
            String className = xml.getStringProperty("tipoValueKeys");
430
            String[] sk = xml.getStringArrayProperty("keys");
431
            String[] sv = xml.getStringArrayProperty("values");
432
            Value auxValue = null;
433
            Value auxValue2 = null;
434
            int[] stk=null;
435
            if (xml.contains("typeKeys")) {
436
                                stk = xml.getIntArrayProperty("typeKeys");
437
                                int[] stv = xml.getIntArrayProperty("typeValues");
438
                                for (int i = 0; i < numKeys; i++) {
439
                                        boolean isDefault = false;
440
                                        if (getValue(sk[i], stk[i]) == null) {
441
                                                isDefault = true;
442
                                        }
443

    
444
                                        if (className
445
                                                        .equals("com.hardcode.gdbms.engine.values.NullUniqueValue")
446
                                                        || isDefault) {
447
                                                auxValue = new NullUniqueValue();
448
                                                auxValue2 = ValueFactory.createNullValue();
449
                                        } else {
450
                                                auxValue = getValue(sk[i], stk[i]); // ValueFactory.createValue(sk[i],
451
                                                                                                                        // className);
452
                                                auxValue2 = getValue(sv[i], stv[i]); // ValueFactory.createValue(sv[i],
453
                                                                                                                                // className);
454
                                        }
455

    
456
                                        // (substituir la de baix per esta) ISymbol sym = SymbolFactory.createFromXML(xml.getChild(i + 1), null);
457
                                        ISymbol sym = SymbologyFactory.createSymbolFromXML(xml.getChild(i + 1), null);
458
                                        symbols.put(auxValue2, sym);
459
                                        keys.add(auxValue);
460
                                }
461
                        } else {
462
                                for (int i = 0; i < numKeys; i++) {
463
                                        boolean isDefault = false;
464
                                        if (getValue(sk[i]) == null) {
465
                                                isDefault = true;
466
                                        }
467
                                        if (className
468
                                                        .equals("com.hardcode.gdbms.engine.values.NullUniqueValue")
469
                                                        || isDefault) {
470
                                                auxValue = new NullUniqueValue();
471
                                                auxValue2 = ValueFactory.createNullValue();
472
                                        } else {
473
                                                auxValue = getValue(sk[i]); // ValueFactory.createValue(sk[i],
474
                                                                                                        // className);
475
                                                auxValue2 = getValue(sv[i]); // ValueFactory.createValue(sv[i],
476
                                                                                                                // className);
477
                                        }
478
                                        ISymbol sym = FSymbol.createFromXML(xml.getChild(i + 1));
479
                                        symbols.put(auxValue2, sym);
480
                                        keys.add(auxValue);
481
                                }
482
                        }
483
        }
484
    }
485

    
486
    public void setDefaultSymbol(ISymbol s) {
487
            if (s == null) throw new NullPointerException("Default symbol cannot be null");
488
        defaultSymbol = s;
489
    }
490
    /**
491
         * Devuelve el valor a partir de su valor en un string.
492
         *
493
         * @param s
494
         *            String con el valor.
495
         * @deprecated M?todo utilizado hasta la 1.0 alpha 855 Debes utilizar a partir de ahora getValue(String s,int type);
496
         * @return Value.
497
         */
498
    private Value getValue(String s) {
499
        Value val = new NullUniqueValue();
500
        if (s.equals("Resto de Valores"))return val;
501
        try {
502
            try {
503
                val = ValueFactory.createValueByType(s, Types.INTEGER);
504

    
505
                return val;
506
            } catch (NumberFormatException e) {
507
            }
508

    
509
            try {
510
                val = ValueFactory.createValueByType(s, Types.BIGINT);
511

    
512
                return val;
513
            } catch (NumberFormatException e) {
514
            }
515

    
516
            try {
517
                val = ValueFactory.createValueByType(s, Types.FLOAT);
518

    
519
                return val;
520
            } catch (NumberFormatException e) {
521
            }
522

    
523
            try {
524
                val = ValueFactory.createValueByType(s, Types.DOUBLE);
525

    
526
                return val;
527
            } catch (NumberFormatException e) {
528
            }
529

    
530
            val = ValueFactory.createValueByType(s, Types.LONGVARCHAR);
531

    
532
        } catch (ParseException e) {
533
           log.warn("parse exceptin", e);
534
        }
535

    
536
        return val;
537
    }
538

    
539
    /**
540
     * Devuelve el valor a partir de su valor en un string.
541
     *
542
     * @param s String con el valor.
543
     *
544
     * @return Value.
545
     */
546
    private Value getValue(String s,int type) {
547
        Value val = new NullUniqueValue();
548
        if (type==Types.OTHER)
549
                return val;
550
        try {
551
                val = ValueFactory.createValueByType(s, type);
552
        } catch (ParseException e) {
553
            e.printStackTrace();
554
        }
555
        return val;
556
    }
557

    
558
    public ILegend cloneLegend() throws XMLException {
559
        return LegendFactory.createFromXML(getXMLEntity());
560
    }
561

    
562

    
563
    /* (non-Javadoc)
564
     * @see com.iver.cit.gvsig.fmap.rendering.VectorialLegend#setDataSource(com.hardcode.gdbms.engine.data.DataSource)
565
     */
566
    public void setDataSource(DataSource ds) throws FieldNotFoundException,
567
                        ReadDriverException {
568
                dataSource = ds;
569
                ds.start();
570
                FIELD_ID = ds.getFieldIndexByName(fieldNames[0]);
571
                ds.stop();
572
        }
573

    
574
    /*
575
     * (non-Javadoc)
576
     *
577
     * @see com.iver.cit.gvsig.fmap.rendering.UniqueValueLegend#getSymbolByValue(com.hardcode.gdbms.engine.values.Value)
578
     */
579
    public ISymbol getSymbolByValue(Value key) {
580
            ISymbol symbol=(ISymbol) symbols.get(key);
581
            if (symbol!=null) {
582
                    return symbol;
583
            } else if (useDefaultSymbol) {
584
                    return getDefaultSymbol();
585
            }
586
            return null;
587

    
588
    }
589

    
590
    public int getShapeType() {
591
        return shapeType;
592
    }
593

    
594
    public void useDefaultSymbol(boolean b) {
595
        useDefaultSymbol = b;
596
    }
597

    
598
    /**
599
         * Devuelve si se utiliza o no el resto de valores para representarse.
600
         * @return  True si se utiliza el resto de valores.
601
         */
602
    public boolean isUseDefaultSymbol() {
603
        return useDefaultSymbol;
604
    }
605

    
606
    public void delSymbol(Object key) {
607
        keys.remove(key);
608
        symbols.remove(key);
609
    }
610

    
611
    public String[] getUsedFields() {
612
       return getFieldNames();
613

    
614
    }
615

    
616
        public ZSort getZSort() {
617
                return zSort;
618
        }
619

    
620
        public void setZSort(ZSort zSort) {
621
                this.zSort = zSort;
622
        }
623

    
624
        public String getClassName() {
625
                return getClass().getName();
626
        }
627
}