KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > catalina > connector > Connector


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18
19 package org.apache.catalina.connector;
20
21 import java.lang.reflect.Method JavaDoc;
22 import java.net.URLEncoder JavaDoc;
23 import java.util.HashMap JavaDoc;
24
25 import javax.management.MBeanRegistration JavaDoc;
26 import javax.management.MBeanServer JavaDoc;
27 import javax.management.MalformedObjectNameException JavaDoc;
28 import javax.management.ObjectName JavaDoc;
29
30 import org.apache.catalina.Container;
31 import org.apache.catalina.Lifecycle;
32 import org.apache.catalina.LifecycleException;
33 import org.apache.catalina.LifecycleListener;
34 import org.apache.catalina.Service;
35 import org.apache.catalina.core.StandardEngine;
36 import org.apache.catalina.util.LifecycleSupport;
37 import org.apache.catalina.util.StringManager;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40 import org.apache.coyote.Adapter;
41 import org.apache.coyote.ProtocolHandler;
42 import org.apache.tomcat.util.IntrospectionUtils;
43 import org.apache.tomcat.util.http.mapper.Mapper;
44 import org.apache.tomcat.util.modeler.Registry;
45
46
47 /**
48  * Implementation of a Coyote connector for Tomcat 5.x.
49  *
50  * @author Craig R. McClanahan
51  * @author Remy Maucherat
52  * @version $Revision: 470756 $ $Date: 2006-11-03 11:56:25 +0100 (ven., 03 nov. 2006) $
53  */

54
55
56 public class Connector
57     implements Lifecycle, MBeanRegistration JavaDoc
58 {
59     private static Log log = LogFactory.getLog(Connector.class);
60
61
62     /**
63      * Alternate flag to enable recycling of facades.
64      */

65     public static final boolean RECYCLE_FACADES =
66         Boolean.valueOf(System.getProperty("org.apache.catalina.connector.RECYCLE_FACADES", "false")).booleanValue();
67
68     
69     // ------------------------------------------------------------ Constructor
70

71
72     public Connector()
73         throws Exception JavaDoc {
74         this(null);
75     }
76     
77     public Connector(String JavaDoc protocol)
78         throws Exception JavaDoc {
79         setProtocol(protocol);
80         // Instantiate protocol handler
81
try {
82             Class JavaDoc clazz = Class.forName(protocolHandlerClassName);
83             this.protocolHandler = (ProtocolHandler) clazz.newInstance();
84         } catch (Exception JavaDoc e) {
85             log.error
86                 (sm.getString
87                  ("coyoteConnector.protocolHandlerInstantiationFailed", e));
88         }
89     }
90     
91     
92     // ----------------------------------------------------- Instance Variables
93

94
95     /**
96      * The <code>Service</code> we are associated with (if any).
97      */

98     protected Service service = null;
99
100
101     /**
102      * Do we allow TRACE ?
103      */

104     protected boolean allowTrace = false;
105
106
107     /**
108      * The Container used for processing requests received by this Connector.
109      */

110     protected Container container = null;
111
112
113     /**
114      * Use "/" as path for session cookies ?
115      */

116     protected boolean emptySessionPath = false;
117
118
119     /**
120      * The "enable DNS lookups" flag for this Connector.
121      */

122     protected boolean enableLookups = false;
123
124
125     /*
126      * Is generation of X-Powered-By response header enabled/disabled?
127      */

128     protected boolean xpoweredBy = false;
129
130
131     /**
132      * Descriptive information about this Connector implementation.
133      */

134     protected static final String JavaDoc info =
135         "org.apache.catalina.connector.Connector/2.1";
136
137
138     /**
139      * The lifecycle event support for this component.
140      */

141     protected LifecycleSupport lifecycle = new LifecycleSupport(this);
142
143
144     /**
145      * The port number on which we listen for requests.
146      */

147     protected int port = 0;
148
149
150     /**
151      * The server name to which we should pretend requests to this Connector
152      * were directed. This is useful when operating Tomcat behind a proxy
153      * server, so that redirects get constructed accurately. If not specified,
154      * the server name included in the <code>Host</code> header is used.
155      */

156     protected String JavaDoc proxyName = null;
157
158
159     /**
160      * The server port to which we should pretent requests to this Connector
161      * were directed. This is useful when operating Tomcat behind a proxy
162      * server, so that redirects get constructed accurately. If not specified,
163      * the port number specified by the <code>port</code> property is used.
164      */

165     protected int proxyPort = 0;
166
167
168     /**
169      * The redirect port for non-SSL to SSL redirects.
170      */

171     protected int redirectPort = 443;
172
173
174     /**
175      * The request scheme that will be set on all requests received
176      * through this connector.
177      */

178     protected String JavaDoc scheme = "http";
179
180
181     /**
182      * The secure connection flag that will be set on all requests received
183      * through this connector.
184      */

185     protected boolean secure = false;
186
187
188     /**
189      * The string manager for this package.
190      */

191     protected StringManager sm =
192         StringManager.getManager(Constants.Package);
193
194
195     /**
196      * Maximum size of a POST which will be automatically parsed by the
197      * container. 2MB by default.
198      */

199     protected int maxPostSize = 2 * 1024 * 1024;
200
201
202     /**
203      * Maximum size of a POST which will be saved by the container
204      * during authentication. 4kB by default
205      */

206     protected int maxSavePostSize = 4 * 1024;
207
208
209     /**
210      * Has this component been initialized yet?
211      */

212     protected boolean initialized = false;
213
214
215     /**
216      * Has this component been started yet?
217      */

218     protected boolean started = false;
219
220
221     /**
222      * The shutdown signal to our background thread
223      */

224     protected boolean stopped = false;
225
226     /**
227      * Flag to use IP-based virtual hosting.
228      */

229     protected boolean useIPVHosts = false;
230
231     /**
232      * The background thread.
233      */

234     protected Thread JavaDoc thread = null;
235
236
237     /**
238      * Coyote Protocol handler class name.
239      * Defaults to the Coyote HTTP/1.1 protocolHandler.
240      */

241     protected String JavaDoc protocolHandlerClassName =
242         "org.apache.coyote.http11.Http11Protocol";
243
244
245     /**
246      * Coyote protocol handler.
247      */

248     protected ProtocolHandler protocolHandler = null;
249
250
251     /**
252      * Coyote adapter.
253      */

254     protected Adapter adapter = null;
255
256
257      /**
258       * Mapper.
259       */

260      protected Mapper mapper = new Mapper();
261
262
263      /**
264       * Mapper listener.
265       */

266      protected MapperListener mapperListener = new MapperListener(mapper);
267
268
269      /**
270       * URI encoding.
271       */

272      protected String JavaDoc URIEncoding = null;
273
274
275      /**
276       * URI encoding as body.
277       */

278      protected boolean useBodyEncodingForURI = false;
279
280
281      protected static HashMap JavaDoc replacements = new HashMap JavaDoc();
282      static {
283          replacements.put("acceptCount", "backlog");
284          replacements.put("connectionLinger", "soLinger");
285          replacements.put("connectionTimeout", "soTimeout");
286          replacements.put("connectionUploadTimeout", "timeout");
287          replacements.put("clientAuth", "clientauth");
288          replacements.put("keystoreFile", "keystore");
289          replacements.put("randomFile", "randomfile");
290          replacements.put("rootFile", "rootfile");
291          replacements.put("keystorePass", "keypass");
292          replacements.put("keystoreType", "keytype");
293          replacements.put("sslProtocol", "protocol");
294          replacements.put("sslProtocols", "protocols");
295      }
296      
297      
298     // ------------------------------------------------------------- Properties
299

300
301     /**
302      * Return a configured property.
303      */

304     public Object JavaDoc getProperty(String JavaDoc name) {
305         String JavaDoc repl = name;
306         if (replacements.get(name) != null) {
307             repl = (String JavaDoc) replacements.get(name);
308         }
309         return IntrospectionUtils.getProperty(protocolHandler, repl);
310     }
311
312     
313     /**
314      * Set a configured property.
315      */

316     public void setProperty(String JavaDoc name, String JavaDoc value) {
317         String JavaDoc repl = name;
318         if (replacements.get(name) != null) {
319             repl = (String JavaDoc) replacements.get(name);
320         }
321         IntrospectionUtils.setProperty(protocolHandler, repl, value);
322     }
323
324     
325     /**
326      * Return a configured property.
327      */

328     public Object JavaDoc getAttribute(String JavaDoc name) {
329         return getProperty(name);
330     }
331
332     
333     /**
334      * Set a configured property.
335      */

336     public void setAttribute(String JavaDoc name, Object JavaDoc value) {
337         setProperty(name, String.valueOf(value));
338     }
339
340     
341     /**
342      * remove a configured property.
343      */

344     public void removeProperty(String JavaDoc name) {
345         // FIXME !
346
//protocolHandler.removeAttribute(name);
347
}
348
349     
350     /**
351      * Return the <code>Service</code> with which we are associated (if any).
352      */

353     public Service getService() {
354
355         return (this.service);
356
357     }
358
359
360     /**
361      * Set the <code>Service</code> with which we are associated (if any).
362      *
363      * @param service The service that owns this Engine
364      */

365     public void setService(Service service) {
366
367         this.service = service;
368         // FIXME: setProperty("service", service);
369

370     }
371
372
373     /**
374      * True if the TRACE method is allowed. Default value is "false".
375      */

376     public boolean getAllowTrace() {
377
378         return (this.allowTrace);
379
380     }
381
382
383     /**
384      * Set the allowTrace flag, to disable or enable the TRACE HTTP method.
385      *
386      * @param allowTrace The new allowTrace flag
387      */

388     public void setAllowTrace(boolean allowTrace) {
389
390         this.allowTrace = allowTrace;
391         setProperty("allowTrace", String.valueOf(allowTrace));
392
393     }
394
395     /**
396      * Is this connector available for processing requests?
397      */

398     public boolean isAvailable() {
399
400         return (started);
401
402     }
403
404
405     /**
406      * Return the input buffer size for this Connector.
407      *
408      * @deprecated
409      */

410     public int getBufferSize() {
411         return 2048;
412     }
413
414     /**
415      * Set the input buffer size for this Connector.
416      *
417      * @param bufferSize The new input buffer size.
418      * @deprecated
419      */

420     public void setBufferSize(int bufferSize) {
421     }
422
423     
424     /**
425      * Return the Container used for processing requests received by this
426      * Connector.
427      */

428     public Container getContainer() {
429         if( container==null ) {
430             // Lazy - maybe it was added later
431
findContainer();
432         }
433         return (container);
434
435     }
436
437
438     /**
439      * Set the Container used for processing requests received by this
440      * Connector.
441      *
442      * @param container The new Container to use
443      */

444     public void setContainer(Container container) {
445
446         this.container = container;
447
448     }
449
450
451     /**
452      * Return the "empty session path" flag.
453      */

454     public boolean getEmptySessionPath() {
455
456         return (this.emptySessionPath);
457
458     }
459
460
461     /**
462      * Set the "empty session path" flag.
463      *
464      * @param emptySessionPath The new "empty session path" flag value
465      */

466     public void setEmptySessionPath(boolean emptySessionPath) {
467
468         this.emptySessionPath = emptySessionPath;
469         setProperty("emptySessionPath", String.valueOf(emptySessionPath));
470
471     }
472
473
474     /**
475      * Return the "enable DNS lookups" flag.
476      */

477     public boolean getEnableLookups() {
478
479         return (this.enableLookups);
480
481     }
482
483
484     /**
485      * Set the "enable DNS lookups" flag.
486      *
487      * @param enableLookups The new "enable DNS lookups" flag value
488      */

489     public void setEnableLookups(boolean enableLookups) {
490
491         this.enableLookups = enableLookups;
492         setProperty("enableLookups", String.valueOf(enableLookups));
493
494     }
495
496
497     /**
498      * Return descriptive information about this Connector implementation.
499      */

500     public String JavaDoc getInfo() {
501
502         return (info);
503
504     }
505
506
507      /**
508       * Return the mapper.
509       */

510      public Mapper getMapper() {
511
512          return (mapper);
513
514      }
515
516
517     /**
518      * Return the maximum size of a POST which will be automatically
519      * parsed by the container.
520      */

521     public int getMaxPostSize() {
522
523         return (maxPostSize);
524
525     }
526
527
528     /**
529      * Set the maximum size of a POST which will be automatically
530      * parsed by the container.
531      *
532      * @param maxPostSize The new maximum size in bytes of a POST which will
533      * be automatically parsed by the container
534      */

535     public void setMaxPostSize(int maxPostSize) {
536
537         this.maxPostSize = maxPostSize;
538     }
539
540
541     /**
542      * Return the maximum size of a POST which will be saved by the container
543      * during authentication.
544      */

545     public int getMaxSavePostSize() {
546
547         return (maxSavePostSize);
548
549     }
550
551
552     /**
553      * Set the maximum size of a POST which will be saved by the container
554      * during authentication.
555      *
556      * @param maxSavePostSize The new maximum size in bytes of a POST which will
557      * be saved by the container during authentication.
558      */

559     public void setMaxSavePostSize(int maxSavePostSize) {
560
561         this.maxSavePostSize = maxSavePostSize;
562         setProperty("maxSavePostSize", String.valueOf(maxSavePostSize));
563     }
564
565
566     /**
567      * Return the port number on which we listen for requests.
568      */

569     public int getPort() {
570
571         return (this.port);
572
573     }
574
575
576     /**
577      * Set the port number on which we listen for requests.
578      *
579      * @param port The new port number
580      */

581     public void setPort(int port) {
582
583         this.port = port;
584         setProperty("port", String.valueOf(port));
585
586     }
587
588
589     /**
590      * Return the Coyote protocol handler in use.
591      */

592     public String JavaDoc getProtocol() {
593
594         if ("org.apache.coyote.http11.Http11Protocol".equals
595             (getProtocolHandlerClassName())
596             || "org.apache.coyote.http11.Http11AprProtocol".equals
597             (getProtocolHandlerClassName())) {
598             return "HTTP/1.1";
599         } else if ("org.apache.coyote.ajp.AjpProtocol".equals
600                    (getProtocolHandlerClassName())
601                    || "org.apache.coyote.ajp.AjpAprProtocol".equals
602                    (getProtocolHandlerClassName())) {
603             return "AJP/1.3";
604         }
605         return getProtocolHandlerClassName();
606
607     }
608
609
610     /**
611      * Set the Coyote protocol which will be used by the connector.
612      *
613      * @param protocol The Coyote protocol name
614      */

615     public void setProtocol(String JavaDoc protocol) {
616
617         // Test APR support
618
boolean apr = false;
619         try {
620             String JavaDoc methodName = "initialize";
621             Class JavaDoc paramTypes[] = new Class JavaDoc[1];
622             paramTypes[0] = String JavaDoc.class;
623             Object JavaDoc paramValues[] = new Object JavaDoc[1];
624             paramValues[0] = null;
625             Method JavaDoc method = Class.forName("org.apache.tomcat.jni.Library")
626                 .getMethod(methodName, paramTypes);
627             method.invoke(null, paramValues);
628             apr = true;
629         } catch (Throwable JavaDoc t) {
630             // Ignore
631
}
632
633         if (apr) {
634             if ("HTTP/1.1".equals(protocol)) {
635                 setProtocolHandlerClassName
636                     ("org.apache.coyote.http11.Http11AprProtocol");
637             } else if ("AJP/1.3".equals(protocol)) {
638                 setProtocolHandlerClassName
639                     ("org.apache.coyote.ajp.AjpAprProtocol");
640             } else if (protocol != null) {
641                 setProtocolHandlerClassName(protocol);
642             } else {
643                 setProtocolHandlerClassName
644                     ("org.apache.coyote.http11.Http11AprProtocol");
645             }
646         } else {
647             if ("HTTP/1.1".equals(protocol)) {
648                 setProtocolHandlerClassName
649                     ("org.apache.coyote.http11.Http11Protocol");
650             } else if ("AJP/1.3".equals(protocol)) {
651                 setProtocolHandlerClassName
652                     ("org.apache.coyote.ajp.AjpProtocol");
653             } else if (protocol != null) {
654                 setProtocolHandlerClassName(protocol);
655             }
656         }
657
658     }
659
660
661     /**
662      * Return the class name of the Coyote protocol handler in use.
663      */

664     public String JavaDoc getProtocolHandlerClassName() {
665
666         return (this.protocolHandlerClassName);
667
668     }
669
670
671     /**
672      * Set the class name of the Coyote protocol handler which will be used
673      * by the connector.
674      *
675      * @param protocolHandlerClassName The new class name
676      */

677     public void setProtocolHandlerClassName(String JavaDoc protocolHandlerClassName) {
678
679         this.protocolHandlerClassName = protocolHandlerClassName;
680
681     }
682
683
684     /**
685      * Return the protocol handler associated with the connector.
686      */

687     public ProtocolHandler getProtocolHandler() {
688
689         return (this.protocolHandler);
690
691     }
692
693
694     /**
695      * Return the proxy server name for this Connector.
696      */

697     public String JavaDoc getProxyName() {
698
699         return (this.proxyName);
700
701     }
702
703
704     /**
705      * Set the proxy server name for this Connector.
706      *
707      * @param proxyName The new proxy server name
708      */

709     public void setProxyName(String JavaDoc proxyName) {
710
711         if(proxyName != null && proxyName.length() > 0) {
712             this.proxyName = proxyName;
713             setProperty("proxyName", proxyName);
714         } else {
715             this.proxyName = null;
716             removeProperty("proxyName");
717         }
718
719     }
720
721
722     /**
723      * Return the proxy server port for this Connector.
724      */

725     public int getProxyPort() {
726
727         return (this.proxyPort);
728
729     }
730
731
732     /**
733      * Set the proxy server port for this Connector.
734      *
735      * @param proxyPort The new proxy server port
736      */

737     public void setProxyPort(int proxyPort) {
738
739         this.proxyPort = proxyPort;
740         setProperty("proxyPort", String.valueOf(proxyPort));
741
742     }
743
744
745     /**
746      * Return the port number to which a request should be redirected if
747      * it comes in on a non-SSL port and is subject to a security constraint
748      * with a transport guarantee that requires SSL.
749      */

750     public int getRedirectPort() {
751
752         return (this.redirectPort);
753
754     }
755
756
757     /**
758      * Set the redirect port number.
759      *
760      * @param redirectPort The redirect port number (non-SSL to SSL)
761      */

762     public void setRedirectPort(int redirectPort) {
763
764         this.redirectPort = redirectPort;
765         setProperty("redirectPort", String.valueOf(redirectPort));
766
767     }
768
769     
770     /**
771      * Return the scheme that will be assigned to requests received
772      * through this connector. Default value is "http".
773      */

774     public String JavaDoc getScheme() {
775
776         return (this.scheme);
777
778     }
779
780
781     /**
782      * Set the scheme that will be assigned to requests received through
783      * this connector.
784      *
785      * @param scheme The new scheme
786      */

787     public void setScheme(String JavaDoc scheme) {
788
789         this.scheme = scheme;
790
791     }
792
793
794     /**
795      * Return the secure connection flag that will be assigned to requests
796      * received through this connector. Default value is "false".
797      */

798     public boolean getSecure() {
799
800         return (this.secure);
801
802     }
803
804
805     /**
806      * Set the secure connection flag that will be assigned to requests
807      * received through this connector.
808      *
809      * @param secure The new secure connection flag
810      */

811     public void setSecure(boolean secure) {
812
813         this.secure = secure;
814         setProperty("secure", Boolean.toString(secure));
815     }
816
817      /**
818       * Return the character encoding to be used for the URI.
819       */

820      public String JavaDoc getURIEncoding() {
821
822          return (this.URIEncoding);
823
824      }
825
826
827      /**
828       * Set the URI encoding to be used for the URI.
829       *
830       * @param URIEncoding The new URI character encoding.
831       */

832      public void setURIEncoding(String JavaDoc URIEncoding) {
833
834          this.URIEncoding = URIEncoding;
835          setProperty("uRIEncoding", URIEncoding);
836
837      }
838
839
840      /**
841       * Return the true if the entity body encoding should be used for the URI.
842       */

843      public boolean getUseBodyEncodingForURI() {
844
845          return (this.useBodyEncodingForURI);
846
847      }
848
849
850      /**
851       * Set if the entity body encoding should be used for the URI.
852       *
853       * @param useBodyEncodingForURI The new value for the flag.
854       */

855      public void setUseBodyEncodingForURI(boolean useBodyEncodingForURI) {
856
857          this.useBodyEncodingForURI = useBodyEncodingForURI;
858          setProperty
859              ("useBodyEncodingForURI", String.valueOf(useBodyEncodingForURI));
860
861      }
862
863
864     /**
865      * Indicates whether the generation of an X-Powered-By response header for
866      * servlet-generated responses is enabled or disabled for this Connector.
867      *
868      * @return true if generation of X-Powered-By response header is enabled,
869      * false otherwise
870      */

871     public boolean getXpoweredBy() {
872         return xpoweredBy;
873     }
874
875
876     /**
877      * Enables or disables the generation of an X-Powered-By header (with value
878      * Servlet/2.4) for all servlet-generated responses returned by this
879      * Connector.
880      *
881      * @param xpoweredBy true if generation of X-Powered-By response header is
882      * to be enabled, false otherwise
883      */

884     public void setXpoweredBy(boolean xpoweredBy) {
885         this.xpoweredBy = xpoweredBy;
886         setProperty("xpoweredBy", String.valueOf(xpoweredBy));
887     }
888
889     /**
890      * Enable the use of IP-based virtual hosting.
891      *
892      * @param useIPVHosts <code>true</code> if Hosts are identified by IP,
893      * <code>false/code> if Hosts are identified by name.
894      */

895     public void setUseIPVHosts(boolean useIPVHosts) {
896         this.useIPVHosts = useIPVHosts;
897         setProperty("useIPVHosts", String.valueOf(useIPVHosts));
898     }
899
900     /**
901      * Test if IP-based virtual hosting is enabled.
902      */

903     public boolean getUseIPVHosts() {
904         return useIPVHosts;
905     }
906
907     // --------------------------------------------------------- Public Methods
908

909
910     /**
911      * Create (or allocate) and return a Request object suitable for
912      * specifying the contents of a Request to the responsible Container.
913      */

914     public Request createRequest() {
915
916         Request request = new Request();
917         request.setConnector(this);
918         return (request);
919
920     }
921
922
923     /**
924      * Create (or allocate) and return a Response object suitable for
925      * receiving the contents of a Response from the responsible Container.
926      */

927     public Response createResponse() {
928
929         Response response = new Response();
930         response.setConnector(this);
931         return (response);
932
933     }
934
935
936     // ------------------------------------------------------ Lifecycle Methods
937

938
939     /**
940      * Add a lifecycle event listener to this component.
941      *
942      * @param listener The listener to add
943      */

944     public void addLifecycleListener(LifecycleListener listener) {
945
946         lifecycle.addLifecycleListener(listener);
947
948     }
949
950
951     /**
952      * Get the lifecycle listeners associated with this lifecycle. If this
953      * Lifecycle has no listeners registered, a zero-length array is returned.
954      */

955     public LifecycleListener[] findLifecycleListeners() {
956
957         return lifecycle.findLifecycleListeners();
958
959     }
960
961
962     /**
963      * Remove a lifecycle event listener from this component.
964      *
965      * @param listener The listener to add
966      */

967     public void removeLifecycleListener(LifecycleListener listener) {
968
969         lifecycle.removeLifecycleListener(listener);
970
971     }
972
973     
974     protected ObjectName JavaDoc createObjectName(String JavaDoc domain, String JavaDoc type)
975             throws MalformedObjectNameException JavaDoc {
976         String JavaDoc encodedAddr = null;
977         if (getProperty("address") != null) {
978             encodedAddr = URLEncoder.encode(getProperty("address").toString());
979         }
980         String JavaDoc addSuffix = (getProperty("address") == null) ? "" : ",address="
981                 + encodedAddr;
982         ObjectName JavaDoc _oname = new ObjectName JavaDoc(domain + ":type=" + type + ",port="
983                 + getPort() + addSuffix);
984         return _oname;
985     }
986     
987     /**
988      * Initialize this connector (create ServerSocket here!)
989      */

990     public void initialize()
991         throws LifecycleException
992     {
993         if (initialized) {
994             if(log.isInfoEnabled())
995                 log.info(sm.getString("coyoteConnector.alreadyInitialized"));
996            return;
997         }
998
999         this.initialized = true;
1000
1001        if( oname == null && (container instanceof StandardEngine)) {
1002            try {
1003                // we are loaded directly, via API - and no name was given to us
1004
StandardEngine cb=(StandardEngine)container;
1005                oname = createObjectName(cb.getName(), "Connector");
1006                Registry.getRegistry(null, null)
1007                    .registerComponent(this, oname, null);
1008                controller=oname;
1009            } catch (Exception JavaDoc e) {
1010                log.error( "Error registering connector ", e);
1011            }
1012            if(log.isDebugEnabled())
1013                log.debug("Creating name for connector " + oname);
1014        }
1015
1016        // Initializa adapter
1017
adapter = new CoyoteAdapter(this);
1018        protocolHandler.setAdapter(adapter);
1019
1020        IntrospectionUtils.setProperty(protocolHandler, "jkHome",
1021                                       System.getProperty("catalina.base"));
1022
1023        try {
1024            protocolHandler.init();
1025        } catch (Exception JavaDoc e) {
1026            throw new LifecycleException
1027                (sm.getString
1028                 ("coyoteConnector.protocolHandlerInitializationFailed", e));
1029        }
1030    }
1031
1032
1033    /**
1034     * Pause the connector.
1035     */

1036    public void pause()
1037        throws LifecycleException {
1038        try {
1039            protocolHandler.pause();
1040        } catch (Exception JavaDoc e) {
1041            log.error(sm.getString
1042                      ("coyoteConnector.protocolHandlerPauseFailed"), e);
1043        }
1044    }
1045
1046
1047    /**
1048     * Pause the connector.
1049     */

1050    public void resume()
1051        throws LifecycleException {
1052        try {
1053            protocolHandler.resume();
1054        } catch (Exception JavaDoc e) {
1055            log.error(sm.getString
1056                      ("coyoteConnector.protocolHandlerResumeFailed"), e);
1057        }
1058    }
1059
1060
1061    /**
1062     * Begin processing requests via this Connector.
1063     *
1064     * @exception LifecycleException if a fatal startup error occurs
1065     */

1066    public void start() throws LifecycleException {
1067        if( !initialized )
1068            initialize();
1069
1070        // Validate and update our current state
1071
if (started ) {
1072            if(log.isInfoEnabled())
1073                log.info(sm.getString("coyoteConnector.alreadyStarted"));
1074            return;
1075        }
1076        lifecycle.fireLifecycleEvent(START_EVENT, null);
1077        started = true;
1078
1079        // We can't register earlier - the JMX registration of this happens
1080
// in Server.start callback
1081
if ( this.oname != null ) {
1082            // We are registred - register the adapter as well.
1083
try {
1084                Registry.getRegistry(null, null).registerComponent
1085                    (protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
1086            } catch (Exception JavaDoc ex) {
1087                log.error(sm.getString
1088                          ("coyoteConnector.protocolRegistrationFailed"), ex);
1089            }
1090        } else {
1091            if(log.isInfoEnabled())
1092                log.info(sm.getString
1093                     ("coyoteConnector.cannotRegisterProtocol"));
1094        }
1095
1096        try {
1097            protocolHandler.start();
1098        } catch (Exception JavaDoc e) {
1099            String JavaDoc errPrefix = "";
1100            if(this.service != null) {
1101                errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
1102            }
1103
1104            throw new LifecycleException
1105                (errPrefix + " " + sm.getString
1106                 ("coyoteConnector.protocolHandlerStartFailed", e));
1107        }
1108
1109        if( this.domain != null ) {
1110            mapperListener.setDomain( domain );
1111            //mapperListener.setEngine( service.getContainer().getName() );
1112
mapperListener.init();
1113            try {
1114                ObjectName JavaDoc mapperOname = createObjectName(this.domain,"Mapper");
1115                if (log.isDebugEnabled())
1116                    log.debug(sm.getString(
1117                            "coyoteConnector.MapperRegistration", mapperOname));
1118                Registry.getRegistry(null, null).registerComponent
1119                    (mapper, mapperOname, "Mapper");
1120            } catch (Exception JavaDoc ex) {
1121                log.error(sm.getString
1122                        ("coyoteConnector.protocolRegistrationFailed"), ex);
1123            }
1124        }
1125    }
1126
1127
1128    /**
1129     * Terminate processing requests via this Connector.
1130     *
1131     * @exception LifecycleException if a fatal shutdown error occurs
1132     */

1133    public void stop() throws LifecycleException {
1134
1135        // Validate and update our current state
1136
if (!started) {
1137            log.error(sm.getString("coyoteConnector.notStarted"));
1138            return;
1139
1140        }
1141        lifecycle.fireLifecycleEvent(STOP_EVENT, null);
1142        started = false;
1143
1144        try {
1145            mapperListener.destroy();
1146            Registry.getRegistry(null, null).unregisterComponent
1147                (createObjectName(this.domain,"Mapper"));
1148            Registry.getRegistry(null, null).unregisterComponent
1149                (createObjectName(this.domain,"ProtocolHandler"));
1150        } catch (MalformedObjectNameException JavaDoc e) {
1151            log.error( sm.getString
1152                    ("coyoteConnector.protocolUnregistrationFailed"), e);
1153        }
1154        try {
1155            protocolHandler.destroy();
1156        } catch (Exception JavaDoc e) {
1157            throw new LifecycleException
1158                (sm.getString
1159                 ("coyoteConnector.protocolHandlerDestroyFailed", e));
1160        }
1161
1162    }
1163
1164
1165    // -------------------- JMX registration --------------------
1166
protected String JavaDoc domain;
1167    protected ObjectName JavaDoc oname;
1168    protected MBeanServer JavaDoc mserver;
1169    ObjectName JavaDoc controller;
1170
1171    public ObjectName JavaDoc getController() {
1172        return controller;
1173    }
1174
1175    public void setController(ObjectName JavaDoc controller) {
1176        this.controller = controller;
1177    }
1178
1179    public ObjectName JavaDoc getObjectName() {
1180        return oname;
1181    }
1182
1183    public String JavaDoc getDomain() {
1184        return domain;
1185    }
1186
1187    public ObjectName JavaDoc preRegister(MBeanServer JavaDoc server,
1188                                  ObjectName JavaDoc name) throws Exception JavaDoc {
1189        oname=name;
1190        mserver=server;
1191        domain=name.getDomain();
1192        return name;
1193    }
1194
1195    public void postRegister(Boolean JavaDoc registrationDone) {
1196    }
1197
1198    public void preDeregister() throws Exception JavaDoc {
1199    }
1200
1201    public void postDeregister() {
1202        try {
1203            if( started ) {
1204                stop();
1205            }
1206        } catch( Throwable JavaDoc t ) {
1207            log.error( "Unregistering - can't stop", t);
1208        }
1209    }
1210    
1211    protected void findContainer() {
1212        try {
1213            // Register to the service
1214
ObjectName JavaDoc parentName=new ObjectName JavaDoc( domain + ":" +
1215                    "type=Service");
1216            
1217            if(log.isDebugEnabled())
1218                log.debug("Adding to " + parentName );
1219            if( mserver.isRegistered(parentName )) {
1220                mserver.invoke(parentName, "addConnector", new Object JavaDoc[] { this },
1221                        new String JavaDoc[] {"org.apache.catalina.connector.Connector"});
1222                // As a side effect we'll get the container field set
1223
// Also initialize will be called
1224
//return;
1225
}
1226            // XXX Go directly to the Engine
1227
// initialize(); - is called by addConnector
1228
ObjectName JavaDoc engName=new ObjectName JavaDoc( domain + ":" + "type=Engine");
1229            if( mserver.isRegistered(engName )) {
1230                Object JavaDoc obj=mserver.getAttribute(engName, "managedResource");
1231                if(log.isDebugEnabled())
1232                      log.debug("Found engine " + obj + " " + obj.getClass());
1233                container=(Container)obj;
1234                
1235                // Internal initialize - we now have the Engine
1236
initialize();
1237                
1238                if(log.isDebugEnabled())
1239                    log.debug("Initialized");
1240                // As a side effect we'll get the container field set
1241
// Also initialize will be called
1242
return;
1243            }
1244        } catch( Exception JavaDoc ex ) {
1245            log.error( "Error finding container " + ex);
1246        }
1247    }
1248
1249    public void init() throws Exception JavaDoc {
1250
1251        if( this.getService() != null ) {
1252            if(log.isDebugEnabled())
1253                 log.debug( "Already configured" );
1254            return;
1255        }
1256        if( container==null ) {
1257            findContainer();
1258        }
1259    }
1260
1261    public void destroy() throws Exception JavaDoc {
1262        if( oname!=null && controller==oname ) {
1263            if(log.isDebugEnabled())
1264                 log.debug("Unregister itself " + oname );
1265            Registry.getRegistry(null, null).unregisterComponent(oname);
1266        }
1267        if( getService() == null)
1268            return;
1269        getService().removeConnector(this);
1270    }
1271
1272}
1273
Popular Tags