root/tools/routingservice/trunk/src/jp/co/orkney/restlet/util/Configuration.java

Revision 255, 17.5 KB (checked in by daniel, 22 months ago)

Removed example "css" and "localhost" parameters

Line 
1package jp.co.orkney.restlet.util;
2
3/**
4 * Copyright (c) 2007 Orkney, Inc. <http://www.orkney.co.jp/>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (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, see <http://www.gnu.org/licenses/>.
18 */
19
20import java.io.File;
21import java.io.IOException;
22import java.math.BigDecimal;
23import java.util.Iterator;
24import java.util.List;
25import java.util.StringTokenizer;
26import java.util.Vector;
27
28import org.jdom.Document;
29import org.jdom.Element;
30import org.jdom.JDOMException;
31import org.jdom.input.SAXBuilder;
32import org.jdom.output.XMLOutputter;
33
34/**
35 * <b>Configuration is a class which represents the webRouting Service's
36 * configuration.</b>
37 * <p>
38 * A configuration is characterized by the following information:
39 * <ul>
40 * <li>An URL to access on XML configuration file</li>
41 * <li>An port number</li>
42 * <li>A localhost IP address</li>
43 * <li>A vector containing all providers (see below)</li>
44 * <li>The provider specified by GET or POST request</li>
45 * <li>The service specified by GET or POST request</li>
46 * <li>The data input format specified by GET or POST request</li>
47 * <li>The data output format specified by GET or POST request</li>
48 * </ul>
49 * <br />
50 * Structure of the vector "providers":<br /> > Provider 1<br /> > > Service 1<br /> > > >
51 * Parameter 1<br /> > > > Parameter 2<br /> > > > ...<br /> > > > Parameter
52 * n<br /> > > > Format 1<br /> > > > Format 2<br /> > > > ...<br /> > > >
53 * Format n<br /> > Provider 2<br /> > > Service 2<br /> > > > ...<br /> >
54 * Provider n<br /> > > ...<br /> > > > ...<br />
55 * </p>
56 *
57 * @author Matthieu Bilbille - Orkney Inc.
58 * @version 1.0
59 */
60public class Configuration
61{
62    public static final String API_KEY = "api_key";
63
64    public static final String SIGNATURE = "signature";
65
66    public static final String CLIENT_ID = "id";
67
68    private String urlConfigurationFile = "./configuration.xml";
69
70    private String urlXMLTemplateQuery = "./pool.xml";
71
72    private String commandCapabilities = "capabilities";
73
74    private String versionNumber = "1.0.0";
75
76    private String port;
77
78    private String urlLog;
79
80    private int modeLog;
81
82    private String localhost;
83
84    private String urlCss;
85
86    public Vector<Provider> providers;
87
88    private int askCapabilities; // -1 by default, 0 host capabilities, 1
89
90    // provider "x" capabilities
91
92    private Provider provider;
93
94    private Service service;
95
96    private Format formatIn;
97
98    private Format formatOut;
99
100    private int iProvider = 0;
101
102    private int iService = 0;
103
104    private int iFormat = 0;
105
106    /**
107     * Constructor Format.
108     * <p>
109     * Creates a new format with empty data (port, urlLog,...);
110     * </p>
111     */
112    public Configuration()
113    {
114        port = "";
115        urlLog = "";
116        modeLog = 0;
117        localhost = "";
118        urlCss = "";
119        askCapabilities = -1;
120        providers = new Vector<Provider>();
121        /*
122         * provider = new Provider(); service = new Service(); formatIn = new
123         * Format(); formatOut = new Format();
124         */
125        provider = null;
126        service = null;
127        formatIn = null;
128        formatOut = null;
129    }
130
131    /**
132     * Parses the XML configuration file and puts all this data in a vector<Provider>.
133     *
134     */
135    @SuppressWarnings("unchecked")
136    public void parseXML()
137    {
138        SAXBuilder sxb = new SAXBuilder();
139        Document document = null;
140        try
141        {
142            document = sxb.build(new File(urlConfigurationFile));
143        }
144        catch (JDOMException e)
145        {
146            e.printStackTrace();
147        }
148        catch (IOException e)
149        {
150            e.printStackTrace();
151        }
152        Element root = document.getRootElement();
153
154        port = root.getChild("port").getText();
155        urlLog = root.getChild("log").getText();
156        modeLog = Integer.parseInt(root.getChild("log").getAttributeValue(
157                "mode"));
158        //localhost = root.getChild("localhost").getText();
159        //urlCss = root.getChild("css").getText();
160
161        List<Element> listProviders = root.getChild("providers").getChildren(
162                "provider");
163        Iterator<Element> itProvider = listProviders.iterator();
164
165        while (itProvider.hasNext())
166        {
167            Provider provider = new Provider();
168            Element currentProvider = (Element) itProvider.next();
169            provider.setName(currentProvider.getAttributeValue("name"));
170            List<Element> listServices = currentProvider.getChild("services")
171                    .getChildren("service");
172            Iterator<Element> itService = listServices.iterator();
173            Vector<Service> services = new Vector<Service>();
174
175            while (itService.hasNext())
176            {
177                Service service = new Service();
178                Element currentService = itService.next();
179                service.setName(currentService.getAttributeValue("name"));
180
181                service.setEnable(new Boolean(currentService
182                        .getAttributeValue("enable")));
183                service.setDatabaseConfiguration(new DatabaseConfiguration(
184                        currentService.getChild("connection")
185                                .getAttributeValue("driver"), currentService
186                                .getChild("connection").getChildText("url"),
187                        currentService.getChild("connection").getChildText(
188                                "user"), currentService.getChild("connection")
189                                .getChildText("password")));
190                service.setDataProjection(currentService.getChild("projection")
191                        .getAttributeValue("srid"));
192
193                // TODO read units from the configuration
194                // probably it is better to create Projection class
195
196                Limit limit = service.getLimit();
197                try
198                {
199
200                    limit.setDistance(Double.parseDouble(currentService
201                            .getChild("limit").getAttributeValue("distance")));
202                }
203                catch (NullPointerException e)
204                {
205                    // This service has no distance limitations.
206                    // Do nothing.
207                }
208                try
209                {
210                    limit.setExtent(parseExtent(currentService
211                            .getChild("limit").getAttributeValue("extent")));
212                }
213                catch (NullPointerException ee)
214                {
215                    // This service has no extent limitations.
216                    // Do nothing.
217                }
218
219                //service.setLimit(limit);
220
221                List<Element> listSQL = currentService.getChild("sql")
222                        .getChildren("query");
223                Iterator<Element> itQuery = listSQL.iterator();
224                while (itQuery.hasNext())
225                {
226                    Element currentQuery = itQuery.next();
227                    if (currentQuery.getAttributeValue("transformProjectionIn")
228                            .equals("false"))
229                    {
230                        if (currentQuery.getAttributeValue(
231                                "transformProjectionOut").equals("false"))
232                        {
233                            // case: transformProjectionIn = FALSE &
234                            // transformProjectionOut = FALSE
235                            service.setSQL(currentQuery.getText(), 0);
236                        }
237                        else
238                        {
239                            // case: transformProjectionIn = FALSE &
240                            // transformProjectionOut = TRUE
241                            service.setSQL(currentQuery.getText(), 1);
242                        }
243
244                    }
245                    else
246                    {
247                        if (currentQuery.getAttributeValue(
248                                "transformProjectionOut").equals("false"))
249                        {
250                            // case: transformProjectionIn = TRUE &
251                            // transformProjectionOut = FALSE
252                            service.setSQL(currentQuery.getText(), 2);
253                        }
254                        else
255                        {
256                            // case: transformProjectionIn = TRUE &
257                            // transformProjectionOut = TRUE
258                            service.setSQL(currentQuery.getText(), 3);
259                        }
260                    }
261
262                }
263               
264                List<Element> listParameters = currentService.getChild(
265                        "parameters").getChildren("parameter");
266                Iterator<Element> itParametre = listParameters.iterator();
267                Vector<Parameter> parameters = new Vector<Parameter>();
268
269                while (itParametre.hasNext())
270                {
271                    Element currentParameter = itParametre.next();
272                    /*
273                    parameter.setName(currentParameter
274                            .getAttributeValue("name"));
275                    parameter.setType(currentParameter
276                            .getAttributeValue("type"));
277                    parameter.setCodeName(currentParameter
278                            .getAttributeValue("codename"));
279                    parameter.setRequired(new Boolean(currentParameter
280                            .getAttributeValue("required")));
281                    parameter.setDefaultValue(currentParameter
282                            .getAttributeValue("default"));
283                    parameter.setValue(currentParameter
284                            .getAttributeValue("default"));
285                     */
286                    Parameter parameter = new Parameter(currentParameter);         
287                    parameters.add(parameter);
288                }
289               
290                service.setParameters(parameters);
291               
292
293               
294                List<Element> listFormat = currentService.getChild("formats")
295                        .getChildren("format");
296                Iterator<Element> itFormat = listFormat.iterator();
297                Vector<Format> formats = new Vector<Format>();
298
299                while (itFormat.hasNext())
300                {
301                    Element currentFormat = itFormat.next();
302                    /*
303                    format.setName(currentFormat.getAttributeValue("name"));
304                    format.setSrid(currentFormat.getAttributeValue("srid"));
305                    format.setEnableInput(new Boolean(currentFormat
306                            .getAttributeValue("input")));
307                    format.setEnableOutput(new Boolean(currentFormat
308                            .getAttributeValue("output")));
309                    format.setTemplate(currentFormat.getAttributeValue("template"));
310                    */
311                    Format format = new Format(currentFormat);
312                    formats.add(format);
313                }
314                               
315                if (service.getName().equals("security"))
316                    provider.setAuthService(service);
317
318                service.setFormats(formats);
319                services.add(service);
320            }
321            provider.setServices(services);
322            providers.add(provider);
323        }
324    }
325
326    /**
327     * Parses the URL request to define the provider, the service, the data
328     * input and output format. The format of the URL must be:
329     * root/version/provider/input_format/service.output_format
330     *
331     * @param url
332     *                the string to parse
333     * @throws Exception
334     *                 Creates an exception if the URL is wrong
335     */
336    public void parseURL(String url) throws Exception
337    {
338        // FORMAT: /version/provider/input/service.output
339
340        String urlSplit[] = url.split("/");
341
342        if (urlSplit[0].equals(commandCapabilities))
343        {
344            askCapabilities = 0;
345            return;
346        }
347        if (!urlSplit[0].equals(versionNumber))
348            throw new Exception("Invalid version number");
349
350        if ((iProvider = isProvider(urlSplit[1])) != -1)
351        {
352            provider = providers.get(iProvider);
353            if (urlSplit[1].equals(commandCapabilities))
354            {
355                askCapabilities = 1;
356                return;
357            }
358        }
359        else
360            throw new Exception("Unknown provider");
361
362        if ((iService = isService(urlSplit[3].split("\\.")[0])) != -1)
363        {
364            /*
365             * Service tmpService = provider.getServices().get(iService);
366             * service = new Service(tmpService.getName(), tmpService
367             * .getDataProjection(), tmpService.getSQL(), tmpService
368             * .isEnable(), tmpService.getParameters(), null, tmpService
369             * .getDatabaseConfiguration(), tmpService.getLimit());
370             */
371            service = provider.getServices().get(iService);
372        }
373        else
374            throw new Exception("unknown service");
375
376        if ((iFormat = isInput(urlSplit[2])) != -1)
377        {
378            /*
379            Format tmpFormat = providers.get(iProvider).getServices().get(
380                    iService).getFormats().get(iFormat);
381            formatIn = new Format(tmpFormat.getName(), tmpFormat.getSrid(),
382                    tmpFormat.isEnableInput(), tmpFormat.isEnableOutput());
383                */
384            formatIn = providers.get(iProvider).getServices().get(
385                    iService).getFormats().get(iFormat);
386        }
387        else
388            throw new Exception("unknown input format");
389
390        if ((iFormat = isOutput(urlSplit[3].split("\\.")[1].split("\\?")[0])) != -1)
391        {
392            /*
393            Format tmpFormat = providers.get(iProvider).getServices().get(
394                    iService).getFormats().get(iFormat);
395            formatOut = new Format(tmpFormat.getName(), tmpFormat.getSrid(),
396                    tmpFormat.isEnableInput(), tmpFormat.isEnableOutput());
397            if (formatOut.getSrid() != null && !formatOut.getSrid().equals(""))
398            {
399                service.getParameter("sridOutput")
400                        .setValue(formatOut.getSrid());
401            }
402            */
403            formatOut = providers.get(iProvider).getServices().get(
404                    iService).getFormats().get(iFormat);
405        }
406        else
407            throw new Exception("unknown output format");
408    }
409
410    /**
411     * Creates an object to write in the log file
412     *
413     * @return a new Log object
414     */
415    public Log createLog()
416    {
417        return new Log(urlLog, modeLog);
418    }
419
420    /**
421     * Determines whether this string is a provider name.
422     *
423     * @param name
424     *                a string
425     * @return index of the provider in the vector<Provider>; otherwise
426     *         returns -1
427     */
428    public int isProvider(String name)
429    {
430        for (int i = 0; i < providers.size(); i++)
431        {
432            if (providers.get(i).getName().equals(name))
433                return i;
434        }
435        return -1;
436    }
437
438    /**
439     * Determines whether this string is a service name.
440     *
441     * @param name
442     *                a string
443     * @return index of the service in the vector<Service> of the parent
444     *         provider; otherwise returns -1
445     */
446    public int isService(String name)
447    {
448
449        for (int i = 0; i < providers.get(iProvider).getServices().size(); i++)
450        {
451            if (providers.get(iProvider).getServices().get(i).getName().equals(
452                    name))
453                return i;
454        }
455        return -1;
456    }
457
458    /**
459     * Determines whether this string is a input name and whether is enabled
460     * for input data
461     *
462     * @param name
463     *                a string
464     * @return index of the format in the vector<Format> of the parent
465     *         service; otherwise returns -1
466     */
467    public int isInput(String name)
468    {
469
470        for (int i = 0; i < providers.get(iProvider).getServices()
471                .get(iService).getFormats().size(); i++)
472        {
473            if (providers.get(iProvider).getServices().get(iService)
474                    .getFormats().get(i).getName().equals(name)
475                    && providers.get(iProvider).getServices().get(iService)
476                            .getFormats().get(i).isEnableInput())
477                return i;
478        }
479        return -1;
480    }
481
482    /**
483     * Determines whether this string is a output name and whether is
484     * enabled for output data
485     *
486     * @param name
487     *                a string
488     * @return index of the format in the vector<Format> of the parent
489     *         service; otherwise returns -1
490     */
491    public int isOutput(String name)
492    {
493        for (int i = 0; i < providers.get(iProvider).getServices()
494                .get(iService).getFormats().size(); i++)
495        {
496            if (providers.get(iProvider).getServices().get(iService)
497                    .getFormats().get(i).getName().equals(name)
498                    && providers.get(iProvider).getServices().get(iService)
499                            .getFormats().get(i).isEnableOutput())
500                return i;
501        }
502        return -1;
503    }
504
505    /**
506     * Gets the port number of the restlet
507     *
508     * @return this restlet's port
509     */
510    public String getPort()
511    {
512        return port;
513    }
514
515    /**
516     * Gets the localhost address
517     *
518     * @return localhost address
519     */
520    public String getLocalhost()
521    {
522        return localhost;
523    }
524
525    /**
526     * Gets the requested provider
527     *
528     * @return the requested provider
529     */
530    public Provider getProvider()
531    {
532        return provider;
533    }
534
535    /**
536     * Gets the requested service
537     *
538     * @return the requested service
539     */
540    public Service getService()
541    {
542        return service;
543    }
544
545    /**
546     * Gets the url of CSS file (for HTML output)
547     *
548     * @return the CSS File
549     */
550    public String getCss()
551    {
552        return urlCss;
553    }
554
555    /**
556     * Gets the database configuration of the requested service
557     *
558     * @return the database configuration
559     */
560    public DatabaseConfiguration getConfigurationConnexion()
561    {
562        return service.getDatabaseConfiguration();
563    }
564
565    /**
566     * Gets the parameters of the requested service
567     *
568     * @return a vector<Parameter>
569     */
570    public Vector<Parameter> getParameters()
571    {
572        return service.getParameters();
573    }
574
575    /**
576     * Gets the requested input data format
577     *
578     * @return a format
579     */
580    public Format getFormatIn()
581    {
582        return formatIn;
583    }
584
585    /**
586     * Gets the requested output data format
587     *
588     * @return a format
589     */
590    public Format getFormatOut()
591    {
592        return formatOut;
593    }
594
595    public int askCapabilities()
596    {
597        return askCapabilities;
598    }
599
600    public String getCapabilities()
601    {
602        String res = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n";
603        SAXBuilder sxb = new SAXBuilder();
604        Document document = null;
605        try
606        {
607            document = sxb.build(new File(urlConfigurationFile));
608        }
609        catch (JDOMException e)
610        {
611            e.printStackTrace();
612        }
613        catch (IOException e)
614        {
615            e.printStackTrace();
616        }
617        Element root = document.getRootElement();
618        List<Element> listProviders = root.getChild("providers").getChildren(
619                "provider");
620        Iterator<Element> itProvider = listProviders.iterator();
621
622        while (itProvider.hasNext())
623        {
624            Element currentProvider = (Element) itProvider.next();
625            List<Element> listServices = currentProvider.getChild("services")
626                    .getChildren("service");
627            Iterator<Element> itService = listServices.iterator();
628            while (itService.hasNext())
629            {
630                Element currentService = itService.next();
631                currentService.removeChild("connection");
632                currentService.removeChild("sql");
633            }
634        }
635
636        switch (askCapabilities)
637        {
638        case 0:
639            res += new XMLOutputter().outputString(root.getChild("providers"));
640            break;
641        case 1:
642            res += new XMLOutputter()
643                    .outputString(listProviders.get(iProvider));
644            break;
645        }
646        return res;
647    }
648
649    public String getUrlXMLTemplateQuery()
650    {
651        return urlXMLTemplateQuery;
652    }
653
654    //This method parses an extent.
655    //The format should be 'X1 Y1,X2 Y2'
656    private Extent parseExtent(String coordinates)
657    {
658        BigDecimal[] coordinatesArray = null;
659        int i = 0;
660
661        StringTokenizer ll = new StringTokenizer(coordinates.trim(), ",");
662        while (ll.hasMoreTokens())
663        {
664            StringTokenizer ur = new StringTokenizer(ll.nextToken().trim(), " ");
665            while (ur.hasMoreTokens())
666            {
667                coordinatesArray[i] = new BigDecimal(ur.nextToken());
668                ++i;
669            }
670        }
671
672        Extent extent = new Extent(coordinatesArray[0], coordinatesArray[1],
673                coordinatesArray[2], coordinatesArray[3]);
674
675        return extent;
676    }
677}
Note: See TracBrowser for help on using the browser.