Statistics
| Revision:

root / trunk / libraries / libRemoteServices / src / org / gvsig / remoteClient / wms / WMSProtocolHandlerFactory.java @ 3785

History | View | Annotate | Download (8.09 KB)

1

    
2
package org.gvsig.remoteClient.wms;
3

    
4
import java.io.DataInputStream;
5
import java.io.IOException;
6
import java.io.StringReader;
7
import java.net.ConnectException;
8
import java.net.URL;
9
import java.util.ArrayList;
10
import java.util.Iterator;
11

    
12
import org.gvsig.remoteClient.utils.CapabilitiesTags;
13
import org.kxml2.io.KXmlParser;
14
import org.xmlpull.v1.XmlPullParserException;
15

    
16
/**
17
 * <p></p>
18
 * 
19
 */
20
public class WMSProtocolHandlerFactory {
21
/**
22
 * <p></p>
23
 * 
24
 */
25
    public org.gvsig.remoteClient.wms.WMSProtocolHandler wMSProtocolHandler;
26

    
27
    private static ArrayList supportedVersions = new ArrayList();
28

    
29
    static {
30
        /*
31
         * Se meten en el array versions las distintas versiones
32
         * del protocolo en orden descendente
33
         */
34
            //versions.add(WMSProtocolHandler1_3_0.class);
35
        //versions.add(WMSProtocolHandler1_1_1.class);
36
            supportedVersions.add("1.3.0");
37
            supportedVersions.add("1.1.1");
38
            supportedVersions.add("1.1.0");
39
     }
40

    
41
    /**
42
     * M?todo que dada una respuesta de getCapabilities y un iterador sobre una
43
     * coleccion de WMSClient's ordenada descendentemente devuelve el cliente
44
     * cuya version es igual o inmediatamente inferior
45
     *
46
     * @param caps Capabilities con la respuesta del servidor
47
     * @param clients Iterador de conjunto ordenado descendientemente
48
     *
49
     * @return cliente cuya version es igual o inmediatamente inferior
50
     * @throws IllegalAccessException
51
     * @throws InstantiationException
52
     * 
53
     */
54
    private static String getDriverVersion(String version, Iterator clients) throws InstantiationException, IllegalAccessException {
55
        while (clients.hasNext()) {
56
            String clientVersion = (String)clients.next();
57
            int ret = version.compareTo(clientVersion);
58

    
59
            if (ret >= 0) {
60
                return clientVersion;
61
            }
62
        }
63
        return null;
64
    }
65

    
66
    /**
67
     * Establece la versi?n con la que se comunicar? con el servidor y devuelve
68
     * el objeto Capabilities obtenido con dicha versi?n
69
     *
70
     * @param host maquina con la que se negocia
71
     *
72
     * @return instancia de un cliente capaz de negociar con el host que se
73
     *         pasa como par?metro
74
     */
75
     public static WMSProtocolHandler negotiate(String host) throws ConnectException {
76

    
77
        if (supportedVersions.size() == 0) 
78
        {
79
                return null;
80
        }
81

    
82
        try
83
        {                
84
                String highestVersionSupportedByServer  = getSuitableWMSVersion(host,"");
85
                if (supportedVersions.contains(highestVersionSupportedByServer))
86
                {
87
                        //we support the highest version supported by the server
88
                        // this is the best case 
89
                        return createVersionDriver(highestVersionSupportedByServer);
90
                }
91
                else
92
                {
93
                        // in case we dont support the highest version from the server
94
                        // we start the negotiation process in which we have to get the higest version
95
                        // the WMS supports and we are able to read.
96
                        Iterator iVersion = supportedVersions.iterator();
97
                        String wmsVersion;
98
                        String gvSIGVersion;
99
                
100
                        while (iVersion.hasNext()) { 
101
                                gvSIGVersion = (String)iVersion.next();
102
                                wmsVersion = getSuitableWMSVersion(host,gvSIGVersion);
103
                                //TODO:
104
                                //compare with the version returned by the WMS!!!!!
105
                                // send GetCapabilities and read the version to compare.
106
                                int res = wmsVersion.compareTo(gvSIGVersion);
107
                
108
                                if (res == 0) { //Si es la misma que nuestra version                
109
                                    return createVersionDriver(gvSIGVersion);
110
                                } else if (res > 0) { //Si es mayor que nuestra version
111
                                    throw new Exception("Server Version too high: " + wmsVersion);
112
                                } else { //Si es menor que nuestra version
113
                                         //Obtenemos la primera version menor o igual que tengamos
114
                                    String lowerVersion = WMSProtocolHandlerFactory.getDriverVersion(wmsVersion, iVersion);
115
                
116
                                    if (lowerVersion == null) { //Si no hay ninguna
117
                                        throw new Exception("Lowest server version is " + wmsVersion);
118
                                    } else {
119
                                        if (lowerVersion.equals(wmsVersion)) { 
120
                                            return createVersionDriver(lowerVersion);
121
                                        } else { //Si hay una version menor que la que retorno el servidor
122
                                            //iV = lower;
123
                                        }
124
                                    }
125
                                }
126
                        }
127
                }//case we had to start the negotiation process.
128
                return null; // if it did not find any suitable version.        
129
        }
130
        catch(ConnectException conEx)
131
        {
132
                throw conEx;
133
        }
134
        catch(Exception e)
135
        {
136
                e.printStackTrace();
137
                return null;
138
        }
139
    }
140
    
141
     /**
142
      * Sends a GetCapabilities to the WMS server to get the version
143
      * if the version parameter is null, the WMS will return the highest version supported
144
      * if not it will return the lower highest version than the one requested.
145
      * @param host
146
      * @param version
147
      * @return suitable version supported by the server 
148
      */
149
     private static String getSuitableWMSVersion(String host, String _version) throws ConnectException, IOException 
150
     {             
151
            String request = WMSProtocolHandler.buildCapabilitiesSuitableVersionRequest(host, _version);
152
            String version = new String(); 
153
            StringReader reader = null;
154
            //InputStreamReader reader;
155
            //InputStream is = null;
156
            DataInputStream dis = null;
157
                try
158
                {           
159
                        URL url = new URL(request);
160
            byte[] buffer = new byte[512];//new byte[1024*256];
161
//            is = url.openStream();            
162
//            reader = new InputStreamReader(is);            
163
            //int numberOfBytes = is.read(buffer);            
164
            //String readed = new String(buffer);
165
            dis = new DataInputStream(url.openStream()); 
166
            dis.readFully(buffer);
167
       
168
            reader = new StringReader(new String(buffer));
169
                    KXmlParser kxmlParser = null;
170
                    kxmlParser = new KXmlParser();
171
                    kxmlParser.setInput(reader);                
172
                        kxmlParser.nextTag();
173
                    if ( kxmlParser.getEventType() != KXmlParser.END_DOCUMENT ) 
174
                    {                    
175
                            if ((kxmlParser.getName().compareTo(CapabilitiesTags.CAPABILITIES_ROOT1_1_0)==0)
176
                                    ||(kxmlParser.getName().compareTo(CapabilitiesTags.CAPABILITIES_ROOT1_1_1)==0)
177
                                    ||(kxmlParser.getName().compareTo(CapabilitiesTags.CAPABILITIES_ROOT1_3_0)==0))
178
                            {
179
                                    version = kxmlParser.getAttributeValue("", CapabilitiesTags.VERSION);
180
                            }
181
                    }
182
                    // do not forget to close the Stream.                    
183
                    reader.close();                    
184
                    dis.close();
185
                        return version;                
186
                }
187
                catch(ConnectException conEx)
188
                {
189
                        throw new ConnectException(conEx.getMessage());                         
190
                }
191
                catch(IOException ioEx)
192
                {
193
                        throw new IOException(ioEx.getMessage());         
194
                }
195
                catch(XmlPullParserException xmlEx)
196
                {
197
                        xmlEx.printStackTrace();
198
                        return "";
199
                }
200
                finally{                
201
                        if (reader != null)
202
                        {
203
                                try{
204
                                        reader.close();
205
                                }catch(Exception ex){
206
                                        ex.printStackTrace(); 
207
                                }
208
                        }
209
                        if (dis != null)
210
                        {
211
                                try{
212
                                        dis.close();
213
                                }catch(Exception ex){
214
                                        ex.printStackTrace(); 
215
                                }
216
                        }
217
                }             
218
     }
219
     
220
     /**
221
      * It creates an instance of a WMSDriver class.
222
      *
223
      * @param String, with the version of the driver to be created
224
      * @return WMSDriver.
225
      */
226
       private static WMSProtocolHandler createVersionDriver(String version)             
227
       {               
228
         try
229
         {
230
           Class driver;
231
           version = version.replace('.', '_');
232
           driver = Class.forName("org.gvsig.remoteClient.wms.wms_"+version+".WMSProtocolHandler" + version);
233
           return (WMSProtocolHandler)driver.newInstance();
234
         }
235
         catch (Exception e)
236
         {
237
                 e.printStackTrace();
238
           //throw new Exception("WMSDriverFactory. Unknown driver version " + e);
239
                 return null;
240
         }
241
       }     
242
  
243
 }