Statistics
| Revision:

root / trunk / applications / appCatalogYNomenclatorClient / src / es / gva / cit / catalogClient / protocols / Z3950Protocol.java @ 3031

History | View | Annotate | Download (11.2 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 es.gva.cit.catalogClient.protocols;
42

    
43
import com.k_int.IR.IRQuery;
44
import com.k_int.IR.InformationFragment;
45
import com.k_int.IR.InformationFragmentSource;
46
import com.k_int.IR.PresentException;
47
import com.k_int.IR.RecordFormatSpecification;
48
import com.k_int.IR.SearchException;
49
import com.k_int.IR.SearchTask;
50
import com.k_int.IR.Searchable;
51
import com.k_int.IR.TimeoutExceededException;
52

    
53
import com.k_int.gen.Z39_50_APDU_1995.InitializeResponse_type;
54

    
55
import es.gva.cit.catalogClient.metadataXML.XMLTree;
56
import es.gva.cit.catalogClient.metadataXML.XMLTreeNumberOfRecordsAnswer;
57
import es.gva.cit.catalogClient.utils.Strings;
58

    
59
import org.w3c.dom.Document;
60
import org.w3c.dom.Node;
61

    
62
import java.io.ByteArrayInputStream;
63
import java.io.InputStream;
64

    
65
import java.net.URL;
66

    
67
import java.util.Properties;
68
import java.util.StringTokenizer;
69
import java.util.Vector;
70

    
71

    
72
/**
73
 * This class implements the z39.50 protocol communication client.
74
 * 
75
 * @see http://www.loc.gov/z3950/agency/
76
 * @author Jorge Piera Llodra (piera_jor@gva.es)
77
 */
78
public class Z3950Protocol extends Z3950OriginBean implements IProtocols {
79
    public static final char ISO2709_RS = 035;
80
    public static final char ISO2709_FS = 036;
81
    public static final char ISO2709_IDFS = 037;
82
    private static final String PREFIX_QUERY_TYPE = "PREFIX";
83
    private static final String CCL_QUERY_TYPE = "CCL";
84
    private int auth_type = 0; // 0=none, 1=anonymous, 2=open, 3=idpass
85
    private String principal = null;
86
    private String group = null;
87
    private String credentials = null;
88

    
89
    public Node[] doQuery(URL url, Object object, int firstRecord) {
90
        String message = (String) object;
91
        Node[] nodes;
92

    
93
        //Search properties
94
        Properties props = new Properties();
95
        props.setProperty("ServiceHost", url.getHost());
96
        props.setProperty("ServicePort", String.valueOf(url.getPort()));
97

    
98
        //props.setProperty("service_short_name","");
99
        //props.setProperty("service_long_name","");
100
        //props.setProperty("default_record_syntax","xml");
101
        //props.setProperty("service_user_principal","");
102
        //props.setProperty("service_user_group","");
103
        //props.setProperty("service_user_credentials","");
104
        //Search Object
105
        Searchable zServer = new com.k_int.z3950.IRClient.Z3950Origin();
106
        zServer.init(props);
107

    
108
        //Create the query object
109
        IRQuery e = new IRQuery();
110
        e.collections = new Vector();
111
        e.collections.add(getDatabase(url));
112
        e.query = new com.k_int.IR.QueryModels.PrefixString(new String(message));
113

    
114
        //create the search task
115
        SearchTask st = (SearchTask) zServer.createTask(e, null);
116

    
117
        try {
118
            // time to wait
119
            st.evaluate(1000000);
120

    
121
            RecordFormatSpecification spec = new RecordFormatSpecification("xml",
122
                    null, "f");
123
            InformationFragmentSource ifs = st.getTaskResultSet();
124
            InformationFragment frag = null;
125
            Document[] doms = new Document[ifs.getFragmentCount()];
126

    
127
            int lastRecord;
128

    
129
            if (ifs.getFragmentCount() > 10) {
130
                nodes = new Node[11];
131

    
132
                if ((ifs.getFragmentCount() - firstRecord) < 10) {
133
                    lastRecord = ifs.getFragmentCount();
134
                } else {
135
                    lastRecord = firstRecord + 9;
136
                }
137
            } else {
138
                nodes = new Node[ifs.getFragmentCount() + 1];
139
                lastRecord = ifs.getFragmentCount();
140
            }
141

    
142
            nodes[0] = XMLTreeNumberOfRecordsAnswer.getNode(ifs.getFragmentCount(),
143
                    firstRecord, lastRecord);
144

    
145
            int index = 1;
146

    
147
            for (int i = firstRecord; i <= lastRecord; i++) {
148
                //Fragment
149
                frag = ifs.getFragment(i, spec);
150

    
151
                String cadena = frag.toString();
152

    
153
                //This is a strange character
154
                cadena = Strings.replace(cadena, "?", "");
155

    
156
                //Change the format.
157
                cadena = Strings.replace(cadena,
158
                        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
159
                        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
160

    
161
                //System.out.println(cadena);
162
                InputStream buffer = new ByteArrayInputStream(cadena.getBytes());
163
                nodes[index] = XMLTree.XMLToTree(buffer);
164
                index++;
165
            }
166
        } catch (TimeoutExceededException e1) {
167
            // TODO Auto-generated catch block
168
            e1.printStackTrace();
169

    
170
            return null;
171
        } catch (SearchException e1) {
172
            // TODO Auto-generated catch block
173
            e1.printStackTrace();
174

    
175
            return null;
176
        } catch (PresentException e1) {
177
            e1.printStackTrace();
178
            
179
            return null;
180
        } 
181
        zServer.destroy();
182
        zServer = null;
183

    
184
        this.disconnect();
185
        
186
        return nodes;
187
    }
188

    
189
    public String getDatabase(URL url) {
190
        StringTokenizer sti = new StringTokenizer(url.getPath(), "/");
191

    
192
        if (sti.countTokens() == 0) {
193
            return "Default";
194
        } else {
195
            return sti.nextToken();
196
        }
197
    }
198

    
199
    public String openConnection(URL url) {
200
        String hostname = url.getHost();
201
        String port = String.valueOf(url.getPort());
202
        String cadena = "";
203

    
204
        try {
205
            InitializeResponse_type resp = connect(hostname, port, auth_type,
206
                    principal, group, credentials);
207

    
208
            if (resp.result.booleanValue() == true) {
209
                if (resp.referenceId != null) {
210
                    cadena = "Reference ID : " + new String(resp.referenceId) +
211
                        "\n";
212
                }
213

    
214
                cadena = cadena + "Implementation ID : " +
215
                    resp.implementationId + "\n";
216
                cadena = cadena + "Implementation Name : " +
217
                    resp.implementationName + "\n";
218
                cadena = cadena + "Implementation Version : " +
219
                    resp.implementationVersion + "\n";
220
            } else {
221
                System.out.println(" Failed to establish association");
222

    
223
                return null;
224
            }
225
        } catch (Exception e) {
226
            e.printStackTrace();
227

    
228
            return null;
229
        }
230

    
231
        return cadena;
232
    }
233

    
234
    public boolean isProtocolSupported(URL url) {
235
        try {
236
            //Search properties
237
            Properties props = new Properties();
238
            props.setProperty("ServiceHost", url.getHost());
239
            props.setProperty("ServicePort", String.valueOf(url.getPort()));
240

    
241
            //Search Object
242
            Searchable zServer = new com.k_int.z3950.IRClient.Z3950Origin();
243
            zServer.init(props);
244

    
245
            //Create the query object
246
            IRQuery e = new IRQuery();
247
            e.collections = new Vector();
248
            e.collections.add(url.getHost() + ":" +
249
                String.valueOf(url.getPort()));
250
            e.query = new com.k_int.IR.QueryModels.PrefixString(
251
                    "@attrset geo @attr 1=4 @attr 4=6 @attr 2=3 \"a\"");
252

    
253
            //create the search task
254
            SearchTask st = (SearchTask) zServer.createTask(e, null);
255

    
256
            st.evaluate(10000);
257
        } catch (Exception e) {
258
            System.err.println(e.toString());
259

    
260
            return false;
261
        }
262
        
263
        this.disconnect();
264
        return true;
265
    }
266

    
267
    private void DisplayISO2709(byte[] octets) {
268
        String orig = new String(octets);
269

    
270
        int record_length = Integer.parseInt(orig.substring(0, 5)); // Positions 0-4 are length of record
271
        char record_status = orig.charAt(5);
272
        char type_of_record = orig.charAt(6);
273
        int indicator_length = 2; // Default indicator length
274
        int subfield_code_length = 2; // Default indicator length
275
        char character_coding_scheme = orig.charAt(9);
276
        int base_address = Integer.parseInt(orig.substring(12, 17)); //
277

    
278
        int length_field_length = Character.digit(orig.charAt(20), 10);
279
        int length_entry = Character.digit(orig.charAt(21), 10);
280

    
281
        if (Character.isDigit(orig.charAt(10))) {
282
            indicator_length = Character.digit(orig.charAt(10), 10);
283
        }
284

    
285
        if (Character.isDigit(orig.charAt(11))) {
286
            subfield_code_length = Character.digit(orig.charAt(11), 10);
287
        }
288

    
289
        int offset = 24;
290

    
291
        while (orig.charAt(offset) != ISO2709_FS) {
292
            // int tag = Integer.parseInt(orig.substring(offset, offset+3));
293
            String tag = orig.substring(offset, offset + 3);
294
            System.out.print(tag + " ");
295
            offset += 3;
296

    
297
            int data_length = Integer.parseInt(orig.substring(offset,
298
                        offset + length_field_length));
299
            offset += length_field_length;
300

    
301
            int data_offset = Integer.parseInt(orig.substring(offset,
302
                        offset + length_entry));
303
            offset += length_entry;
304

    
305
            String this_tag = orig.substring(base_address + data_offset + 2,
306
                    base_address + data_offset + data_length);
307

    
308
            StringTokenizer st = new StringTokenizer(this_tag,
309
                    "" + ISO2709_RS + ISO2709_FS + ISO2709_IDFS, true);
310

    
311
            String subfield = null;
312

    
313
            while (st.hasMoreTokens()) {
314
                subfield = st.nextToken();
315

    
316
                if (subfield.charAt(0) == ISO2709_RS) {
317
                    // System.err.print("Record sep ");
318
                } else if (subfield.charAt(0) == ISO2709_FS) {
319
                    // System.err.print("Field sep ");
320
                } else if (subfield.charAt(0) == ISO2709_IDFS) {
321
                    subfield = st.nextToken();
322
                    System.out.print("$" + subfield.charAt(0) + " " +
323
                        subfield.substring(1, subfield.length()));
324
                } else {
325
                    System.out.print(subfield);
326
                }
327
            }
328

    
329
            System.out.println("");
330
        }
331
    }
332

    
333
    private void displayGRS(Vector v) {
334
        com.k_int.IR.Syntaxes.GRS1 grs_rec = new com.k_int.IR.Syntaxes.GRS1("Repository",
335
                "Coll", "", v, null);
336
        System.out.println(grs_rec.toString());
337
    }
338
}