Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appCatalogYNomenclatorClient / src / es / gva / cit / catalogClient / metadataXML / XMLTree.java @ 3613

History | View | Annotate | Download (10.6 KB)

1

    
2
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
3
*
4
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
19
*
20
* For more information, contact:
21
*
22
*  Generalitat Valenciana
23
*   Conselleria d'Infraestructures i Transport
24
*   Av. Blasco Ib??ez, 50
25
*   46010 VALENCIA
26
*   SPAIN
27
*
28
*      +34 963862235
29
*   gvsig@gva.es
30
*      www.gvsig.gva.es
31
*
32
*    or
33
*
34
*   IVER T.I. S.A
35
*   Salamanca 50
36
*   46005 Valencia
37
*   Spain
38
*
39
*   +34 963163400
40
*   dac@iver.es
41
*/
42
package es.gva.cit.catalogClient.metadataXML;
43
import java.io.File;
44
import java.io.FileWriter;
45
import java.io.IOException;
46
import java.io.InputStream;
47
import java.io.StringWriter;
48
import java.util.StringTokenizer;
49
import java.util.Vector;
50
import org.apache.xml.serialize.OutputFormat;
51
import org.apache.xml.serialize.XMLSerializer;
52
import org.w3c.dom.Document;
53
/*
54
 * Created on 15-abr-2005
55
 *
56
 * TODO To change the template for this generated file go to
57
 * Window - Preferences - Java - Code Style - Code Templates
58
 */
59

    
60
/**
61
 * Utils to parse XML trees using DOM
62
 * 
63
 * 
64
 * @author Jorge Piera Llodra (piera_jor@gva.es)
65
 */
66
public class XMLTree {
67

    
68
/**
69
 * Create a XML node from a File
70
 * 
71
 * 
72
 * @return XML node
73
 * @param file File name
74
 */
75
    public static XMLNode xmlToTree(File file) {        
76
        try {
77
            return new XMLNode(file);
78
        } catch (Exception e) {
79
            // TODO Auto-generated catch block
80
            e.printStackTrace();
81
            return null;
82
        }
83
    } 
84

    
85
/**
86
 * Create a XML node from a InputStream
87
 * 
88
 * 
89
 * @return XML node
90
 * @param stream InputStream
91
 */
92
    public static XMLNode xmlToTree(InputStream stream) {        
93
        try {
94
            return new XMLNode(stream);
95
        } catch (Exception e) {
96
            // TODO Auto-generated catch block
97
            //e.printStackTrace();
98
            return null;
99
        }
100
    } 
101

    
102
/**
103
 * Devuelve un fichero que crea a partir de un arbol XML
104
 * 
105
 * 
106
 * @return Devuelve el fichero escrito
107
 * @param dom Documento en XML
108
 * @param nombreFichero Nombre del fichero.
109
 */
110
    public static File treeToXML(Document dom, String nombreFichero) {        
111
        OutputFormat format = null;
112
        StringWriter stringOut = null;
113
        XMLSerializer serial = null;
114
        FileWriter file = null;
115
        //Creamos un fichero para almacenar la respuesta
116
        File file_answer = new File(nombreFichero);
117
        format = new OutputFormat(dom);
118
        format.setEncoding("ISO-8859-1");
119
        format.setIndent(5);
120
        stringOut = new StringWriter();
121
        serial = new XMLSerializer(stringOut, format);
122
        try {
123
            serial.asDOMSerializer();
124
            serial.serialize(dom);
125
            file = new FileWriter(file_answer);
126
            file.write(stringOut.toString());
127
            file.close();
128
        } catch (IOException e) {
129
            // TODO Auto-generated catch block
130
            e.printStackTrace();
131
            return null;
132
        }
133
        return file_answer;
134
    } 
135

    
136
/**
137
 * Busca un Nodo dado una ruta de nodo del tipo "nodoRaiz:nodoPrimerNivel:...:nodoNivelN":
138
 * 
139
 * 
140
 * @return Devuelve el Nodo que corresponde a la ruta correcta o 'null' si no
141
 * lo encuentra
142
 * @param nodoRaiz Nodo a partir del cual se quiere hacer la b?squeda
143
 * @param etiqueta Ruta del campo que queremos buscar, separando los niveles por ':'
144
 */
145
    public static XMLNode searchNode(XMLNode nodoRaiz, String etiqueta) {        
146
        XMLNode[] nodes = searchMultipleNode(nodoRaiz, etiqueta);
147
        if ((nodes != null) && (nodes.length > 0)) {
148
            return nodes[0];
149
        } else {
150
            return null;
151
        }
152
    } 
153

    
154
/**
155
 * Busca el padre de un Nodo dado una ruta de nodo del tipo "nodoRaiz:nodoPrimerNivel:...:nodoNivelN":
156
 * 
157
 * @param nodoRaiz Nodo a partir del cual se quiere hacer la b?squeda
158
 * @param etiqueta Ruta del campo que queremos buscar, separando los niveles por ':'
159
 * 
160
 * @return Devuelve el Nodo padre que corresponde a la ruta correcta o 'null' si no
161
 * lo encuentra
162
 * @param rootNode 
163
 * @param label 
164
 */
165
    public static XMLNode searchParentNode(XMLNode rootNode, String label) {        
166
        StringTokenizer sti = new StringTokenizer(label, "->");
167
        if (rootNode == null) {
168
            return null;
169
        }
170
        
171
        XMLNode currentNode = rootNode.getSubNode(0);
172
        XMLNode parentNode = rootNode;
173
        
174
        //A cuantos niveles est? el TOKEN
175
        int niveles = sti.countTokens();
176
        String nombreNodo = sti.nextToken();
177
        int nivelActual = 1;
178
        int i = 0;
179
        while (i < parentNode.getNumSubNodes()) {
180
            if (nombreNodo.equals(currentNode.getName())) {
181
                if (niveles == nivelActual) {
182
                    return parentNode;
183
                }
184
                parentNode = currentNode;
185
                currentNode = currentNode.getSubNode(0);
186
                nombreNodo = sti.nextToken();
187
                nivelActual++;
188
                i = 0;
189
            } else {
190
                currentNode = currentNode.getSubNode(i);
191
                i ++;
192
            }
193
        }
194
        return null;
195
    } 
196

    
197
/**
198
 * Hace una busqueda de un atributo de un nodo
199
 * 
200
 * @param nodo Nodo del que se quiere buscar el atributo
201
 * @param nombreAtributo Nombre del atributo
202
 * 
203
 * @return Valor del atributo, o null si no lo ha encontrado
204
 * @param node 
205
 * @param attributeName 
206
 */
207
    public static String searchAtribute(XMLNode node, String attributeName) {        
208
        return node.getAttribute(attributeName);
209
    } 
210

    
211
/**
212
 * Hace una busqueda de una etiqueta en un nodo y devuelve
213
 * su valor
214
 * 
215
 * @param nodo Nodo del que se quiere buscar el atributo
216
 * 
217
 * @return Valor de la etiqueta
218
 * @param node 
219
 * @param etiqueta Nombre de la etiqueta
220
 */
221
    public static String searchNodeValue(XMLNode node, String etiqueta) {        
222
        XMLNode nodoB = searchNode(node, etiqueta);
223
        if (nodoB == null)
224
            return null;
225
        return nodoB.getText();
226
        
227
    } 
228

    
229
/**
230
 * Hace una busqueda de una etiqueta en un nodo y devuelve
231
 * el valor del atributo correspondiente
232
 * 
233
 * @param nodo Nodo del que se quiere buscar el atributo
234
 * 
235
 * @return Valor del atributo de la etiqueta o null
236
 * @param node 
237
 * @param etiqueta Nombre de la etiqueta
238
 * @param atributo 
239
 */
240
    public static String searchNodeAtribute(XMLNode node, String etiqueta, String atributo) {        
241
        XMLNode nodoB = searchNode(node, etiqueta);
242
        if (nodoB == null) {
243
            return null;
244
        } else {
245
            return searchAtribute(nodoB, atributo);
246
        }
247
    } 
248

    
249
/**
250
 * Hace una busqueda de nodos que se llaman igual y devuleve el valor
251
 * 
252
 * @param parentLabel Ruta del campo que queremos buscar, separando los niveles por '->'
253
 * 
254
 * @return Un vector con valores de las etiquetas
255
 * @param rootNode Nodo a partir del cual se quiere hacer la b?squeda
256
 * @param label Node label
257
 */
258
    public static String[] searchMultipleNodeValue(XMLNode rootNode, String label) {        
259
        XMLNode[] nodes = searchMultipleNode(rootNode, label);
260
        if ((nodes == null) || (nodes.length == 0)) {
261
            return null;
262
        }
263
        String[] values = new String[nodes.length];
264
        for (int i = 0; i < nodes.length; i++)
265
            //if (nodes[i].getFirstChild() != null) {
266
                values[i] = nodes[i].getText();
267
            //}
268
        return values;
269
    } 
270

    
271
/**
272
 * Hace una busqueda de nodos que se llaman igual desde uno dado(sin recursividad)
273
 * 
274
 * @param etiqueta Ruta del campo que queremos buscar, separando los niveles por ':'
275
 * 
276
 * @return Un vector con los nodos que ha encontrado
277
 * @param nodoRaiz Nodo a partir del cual se quiere hacer la b?squeda
278
 * @param label 
279
 */
280
    public static XMLNode[] searchMultipleNode(XMLNode nodoRaiz, String label) {        
281
        Vector rootNodes = new Vector();
282
        Vector leafNodes = new Vector();
283
        String firstLabel = null;
284
        leafNodes.add(nodoRaiz);
285
        int level = getLevelNumber(label);
286
        int k = 1;
287
        while (k <= level) {
288
            firstLabel = getParentLabel(label);
289
            label = getChildLabel(label);
290
            rootNodes = new Vector(leafNodes);
291
            leafNodes.clear();
292
            for (int i = 0; i < rootNodes.size(); i++) {
293
                XMLNode root = (XMLNode) rootNodes.get(i);
294
                if (root != null) {
295
                    XMLNode[] nodes = root.getSubnodes();
296
                    for (int j = 0; j < nodes.length; j++) {
297
                        if (nodes[j].getName().equals(firstLabel)) {
298
                            leafNodes.add(nodes[j]);
299
                        }
300
                    }
301
                }
302
            }
303
            k++;
304
        }
305
        XMLNode[] nodes = new XMLNode[leafNodes.size()];
306
       
307
        for (int i = 0; i < leafNodes.size(); i++)
308
            nodes[i] = (XMLNode) leafNodes.get(i);
309
        return nodes;
310
    } 
311

    
312
/**
313
 * Gets the parent node label
314
 * 
315
 * 
316
 * @return The parent node label
317
 * @param nodeLabel Node label
318
 */
319
    private static String getParentLabel(String nodeLabel) {        
320
          return separateParams(nodeLabel,"->")[0];
321
    } 
322

    
323
/**
324
 * It cuts an String in an array of Strings separated by a pattern
325
 * 
326
 * 
327
 * @return An array of Strings
328
 * @param text Text to cut
329
 * @param separator Pattent to find      *
330
 */
331
    private static String[] separateParams(String text, String separator) {        
332
       return text.split(separator);
333
        
334
    } 
335

    
336
/**
337
 * Gets the node label
338
 * 
339
 * 
340
 * @return The node label
341
 * @param nodeLabel Node label
342
 */
343
    private static String getChildLabel(String nodeLabel) {        
344
        String st = null;
345
        String[] labels = separateParams(nodeLabel,"->");
346
        
347
        if (labels.length  == 1){
348
            return labels[0];
349
        }
350
        
351
        st = labels[1];
352
        
353
        for (int i=2 ; i<labels.length ; i++)
354
            st = st + "->" + labels[i];
355
       
356
        return st;
357
    } 
358

    
359
/**
360
 * 
361
 * 
362
 * 
363
 * @return 
364
 * @param nodeLabel 
365
 */
366
    private static int getLevelNumber(String nodeLabel) {        
367
        String[] labels = separateParams(nodeLabel,"->");
368
        return labels.length;
369
    } 
370
 }