001    //$HeadURL: svn+ssh://jwilden@svn.wald.intevation.org/deegree/base/branches/2.5_testing/src/org/deegree/portal/owswatch/ServiceConfiguration.java $
002    /*----------------------------------------------------------------------------
003     This file is part of deegree, http://deegree.org/
004     Copyright (C) 2001-2009 by:
005       Department of Geography, University of Bonn
006     and
007       lat/lon GmbH
008    
009     This library is free software; you can redistribute it and/or modify it under
010     the terms of the GNU Lesser General Public License as published by the Free
011     Software Foundation; either version 2.1 of the License, or (at your option)
012     any later version.
013     This library is distributed in the hope that it will be useful, but WITHOUT
014     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
015     FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
016     details.
017     You should have received a copy of the GNU Lesser General Public License
018     along with this library; if not, write to the Free Software Foundation, Inc.,
019     59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
020    
021     Contact information:
022    
023     lat/lon GmbH
024     Aennchenstr. 19, 53177 Bonn
025     Germany
026     http://lat-lon.de/
027    
028     Department of Geography, University of Bonn
029     Prof. Dr. Klaus Greve
030     Postfach 1147, 53001 Bonn
031     Germany
032     http://www.geographie.uni-bonn.de/deegree/
033    
034     e-mail: info@deegree.org
035    ----------------------------------------------------------------------------*/
036    
037    package org.deegree.portal.owswatch;
038    
039    import java.io.Serializable;
040    import java.io.UnsupportedEncodingException;
041    import java.util.Enumeration;
042    import java.util.Properties;
043    
044    import org.apache.commons.httpclient.HttpMethodBase;
045    import org.apache.commons.httpclient.methods.GetMethod;
046    import org.apache.commons.httpclient.methods.PostMethod;
047    import org.apache.commons.httpclient.methods.StringRequestEntity;
048    import org.deegree.framework.log.ILogger;
049    import org.deegree.framework.log.LoggerFactory;
050    import org.deegree.framework.util.StringTools;
051    import org.deegree.ogcwebservices.OGCWebServiceException;
052    
053    import org.deegree.portal.owswatch.validator.Validator;
054    
055    /**
056     * A data class to hold the information about a certain test. Like test name , type, etc..
057     *
058     * @author <a href="mailto:elmasry@lat-lon.de">Moataz Elmasry</a>
059     * @author last edited by: $Author: jmays $
060     *
061     * @version $Revision: 20271 $, $Date: 2009-10-21 13:07:15 +0200 (Mi, 21 Okt 2009) $
062     */
063    public class ServiceConfiguration implements Serializable {
064    
065        /**
066         *
067         */
068        private static final long serialVersionUID = -8730764035469230765L;
069    
070        private static final ILogger LOG = LoggerFactory.getLogger( ServiceConfiguration.class );
071    
072        private Properties requestProps = null;
073    
074        private static int serviceCounter = 0;
075    
076        private int serviceid;
077    
078        private String requestType = null;
079    
080        private String serviceVersion = null;
081    
082        private String serviceType = null;
083    
084        private boolean active;
085    
086        private int timeout;
087    
088        private int refreshRate;
089    
090        private String onlineResource = null;
091    
092        private String serviceName = null;
093    
094        private String httpMethod = null;
095    
096        private Validator validator = null;
097    
098        private HttpMethodBase method = null;
099    
100        /**
101         * This constructor is used by both ServicesConfigurationFactory and to build requests from the jsp page ,when
102         * adding/changing a service.
103         *
104         * @param serviceId
105         *            -1 to assign a new id to this service
106         * @param serviceName
107         * @param httpMethod
108         * @param onlineResource
109         * @param active
110         * @param interval
111         * @param timeout
112         * @param requestParams
113         *            Contains the kvp request parameter, it must at least the following keys include VERSION, SERVICE,
114         *            REQUEST
115         * @throws ConfigurationsException
116         *             if any of the mandatory parameters is null
117         */
118        public ServiceConfiguration( int serviceId, String serviceName, String httpMethod, String onlineResource,
119                                     boolean active, int interval, int timeout, Properties requestParams )
120                                throws ConfigurationsException {
121            if ( serviceId > serviceCounter ) {
122                serviceCounter = serviceId;
123            }
124    
125            if ( serviceId < 1 ) {
126                serviceId = generateServiceId();
127            }
128    
129            this.serviceid = serviceId;
130    
131            if ( serviceName == null ) {
132                throw new ConfigurationsException( "The serviceName can not be null" );
133            }
134            this.serviceName = serviceName;
135    
136            if ( httpMethod == null ) {
137                throw new ConfigurationsException( "The HttpMethod can not be null" );
138            }
139            this.httpMethod = httpMethod;
140    
141            if ( httpMethod.equals( "POST" ) && !requestParams.containsKey( Constants.XML_REQUEST ) ) {
142                throw new ConfigurationsException( "Missing XML request from service: " + serviceName );
143            }
144    
145            if ( onlineResource == null ) {
146                throw new ConfigurationsException( "Online Resource can not be null" );
147            }
148            this.onlineResource = onlineResource;
149    
150            if ( requestParams == null ) {
151                throw new ConfigurationsException( "The properties can not be null" );
152            }
153    
154            this.requestProps = requestParams;
155    
156            if ( !requestParams.containsKey( Constants.SERVICE_TYPE ) ) {
157                throw new ConfigurationsException( "The service type can not be null" );
158            }
159            this.serviceType = requestParams.getProperty( Constants.SERVICE_TYPE );
160    
161            if ( !requestParams.containsKey( Constants.REQUEST_TYPE ) ) {
162                throw new ConfigurationsException( "The requestType can not be null" );
163            }
164            this.requestType = requestProps.getProperty( Constants.REQUEST_TYPE );
165    
166            if ( !requestParams.containsKey( Constants.VERSION ) ) {
167                throw new ConfigurationsException( "The Version can not be null" );
168            }
169            this.serviceVersion = requestParams.getProperty( Constants.VERSION );
170    
171            this.active = active;
172    
173            if ( interval < 1 ) {
174                throw new ConfigurationsException( "The refresh refreshRate can not be less than one" );
175            }
176            this.refreshRate = interval;
177    
178            if ( timeout < 0 ) {
179                throw new ConfigurationsException( "The timeout can not be less than one" );
180            }
181            this.timeout = timeout;
182        }
183    
184        /**
185         * @return Service properties
186         */
187        public Properties getProperties() {
188            return requestProps;
189        }
190    
191        /**
192         * Creates a http request based on the content of the Service. These contens also include whether its POST or GET
193         * method
194         *
195         * @return the request String
196         */
197        public String createHttpRequest() {
198    
199            if ( httpMethod.equals( "POST" ) ) {
200                return createPOSTRequest();
201            } else if ( httpMethod.equals( "GET" ) ) {
202                return createGETRequest();
203            } else {
204                return null;
205            }
206        }
207    
208        /**
209         * @return the created GET Request
210         */
211        protected String createGETRequest() {
212    
213            StringBuilder builder = new StringBuilder( 200 );
214            builder.append( onlineResource );
215            if ( !onlineResource.endsWith( "?" ) ) {
216                builder.append( "?" );
217            }
218            Enumeration keys = requestProps.keys();
219            while ( keys.hasMoreElements() ) {
220                String key = (String) keys.nextElement();
221                builder.append( key ).append( "=" ).append( requestProps.get( key ) );
222                if ( keys.hasMoreElements() ) {
223                    builder.append( "&" );
224                }
225            }
226            return builder.toString();
227        }
228    
229        /**
230         * @return stored XML POST fragment
231         */
232        protected String createPOSTRequest() {
233            return requestProps.getProperty( Constants.XML_REQUEST );
234        }
235    
236        /**
237         * @return int
238         */
239        public static int generateServiceId() {
240            return ++serviceCounter;
241        }
242    
243        /**
244         * @return int
245         */
246        public int getServiceid() {
247            return serviceid;
248        }
249    
250        /**
251         * @return boolean
252         */
253        public boolean isActive() {
254            return active;
255        }
256    
257        /**
258         * @param active
259         */
260        public void setActive( boolean active ) {
261            this.active = active;
262        }
263    
264        /**
265         * @return String
266         */
267        public String getHttpMethod() {
268            return httpMethod;
269        }
270    
271        /**
272         * @return the refresh refreshRate
273         */
274        public int getRefreshRate() {
275            return refreshRate;
276        }
277    
278        /**
279         * @return the server address to which the requests will be sent
280         */
281        public String getOnlineResource() {
282            return onlineResource;
283        }
284    
285        /**
286         * @return ex. Getcapabilities, GetFeature, etc..
287         */
288        public String getRequestType() {
289            return requestType;
290        }
291    
292        /**
293         * @return the given name during adding a new test
294         */
295        public String getServiceName() {
296            return serviceName;
297        }
298    
299        /**
300         * @return ex WMS, WFS, etc..
301         */
302        public String getServiceType() {
303            return serviceType;
304        }
305    
306        /**
307         * @return String
308         */
309        public String getServiceVersion() {
310            return serviceVersion;
311        }
312    
313        /**
314         * @return Timeout of the requests
315         */
316        public int getTimeout() {
317            return timeout;
318        }
319    
320        /**
321         * @return counter is assigned to the newly created service
322         */
323        public static int getServiceCounter() {
324            return serviceCounter;
325        }
326    
327        /**
328         * @param serviceCounter
329         *            Sets the service counter. It should be used solely by the class ServiceWatcher
330         *
331         */
332        public static void setServiceCounter( int serviceCounter ) {
333            if ( serviceCounter > ServiceConfiguration.serviceCounter ) {
334                ServiceConfiguration.serviceCounter = serviceCounter;
335            }
336        }
337    
338        /**
339         * @param onlineResource
340         *            of the service
341         */
342        public void setOnlineResource( String onlineResource ) {
343            this.onlineResource = onlineResource;
344        }
345    
346        /**
347         * @param serviceName
348         */
349        public void setServiceName( String serviceName ) {
350            this.serviceName = serviceName;
351        }
352    
353        /**
354         * @param timeout
355         *            in milliseconds
356         */
357        public void setTimeout( int timeout ) {
358            this.timeout = timeout;
359        }
360    
361        /**
362         * Creates an HttpMethodBase on the first call and keeps returning it back
363         *
364         * @return {@link HttpMethodBase}
365         * @throws OGCWebServiceException
366         *             If no Httpmethod could be initialized as POST
367         */
368        public HttpMethodBase getHttpMethodBase()
369                                throws OGCWebServiceException {
370    
371            if ( method == null ) {
372                HttpMethodBase method = null;
373                if ( "POST".equals( ( getHttpMethod() ) ) ) {
374                    method = new PostMethod( getOnlineResource() );
375                    try {
376                        // In POST, the next line has to be added, otherwise POST does not work
377                        ( (PostMethod) method ).setRequestEntity( new StringRequestEntity( createHttpRequest(), "text/xml",
378                                                                                           "UTF-8" ) );
379                    } catch ( UnsupportedEncodingException e ) {
380                        throw new OGCWebServiceException( StringTools.concat( 100, "Could not set RequestEntity for ",
381                                                                              getServiceName(), " in executeMethod()" ) );
382                    }
383                } else if ( "GET".equals( getHttpMethod() ) ) {
384                    method = new GetMethod( createHttpRequest() );
385                }
386    
387                return method;
388            }
389            return method;
390        }
391    
392        /**
393         * Generically creates an instance of the needed Validator using reflection
394         *
395         * @return {@link Validator}
396         * @throws ConfigurationsException
397         */
398        public Validator getValidator()
399                                throws ConfigurationsException {
400    
401            if ( validator == null ) {
402    
403                String validatorClassName = StringTools.concat( 100, getClass().getPackage().getName(), ".validator.", serviceType,
404                                                                requestType, "Validator" );
405                if ( validatorClassName.startsWith( "package" ) ) {
406                    validatorClassName = validatorClassName.substring( "package".length() ).trim();
407                }
408                try {
409                    // get the validate function
410                    this.validator = (Validator) getClass().getClassLoader().loadClass( validatorClassName ).getConstructor(
411                                                                                                                             new Class[] {} ).newInstance(
412                                                                                                                                                           new Object[] {} );
413    
414                } catch ( Exception e ) {
415                    LOG.logError( e.getLocalizedMessage() );
416                    throw new ConfigurationsException( StringTools.concat( 100, "Error: The method ", validatorClassName,
417                                                                           " is not implemented" ) );
418    
419                }
420            }
421    
422            return validator;
423        }
424    
425        /*
426         * (non-Javadoc)
427         *
428         * @see java.lang.Object#hashCode()
429         */
430        @Override
431        public int hashCode() {
432            return getServiceid();
433        }
434    }