xref: /unit/src/java/javax/websocket/ContainerProvider.java (revision 1157:7ae152bda303)
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 package javax.websocket;
18 
19 import java.util.Iterator;
20 import java.util.ServiceLoader;
21 
22 /**
23  * Use the {@link ServiceLoader} mechanism to provide instances of the WebSocket
24  * client container.
25  */
26 public abstract class ContainerProvider {
27 
28     private static final String DEFAULT_PROVIDER_CLASS_NAME =
29             "nginx.unit.websocket.WsWebSocketContainer";
30 
31     /**
32      * Create a new container used to create outgoing WebSocket connections.
33      *
34      * @return A newly created container.
35      */
getWebSocketContainer()36     public static WebSocketContainer getWebSocketContainer() {
37         WebSocketContainer result = null;
38 
39         ServiceLoader<ContainerProvider> serviceLoader =
40                 ServiceLoader.load(ContainerProvider.class);
41         Iterator<ContainerProvider> iter = serviceLoader.iterator();
42         while (result == null && iter.hasNext()) {
43             result = iter.next().getContainer();
44         }
45 
46         // Fall-back. Also used by unit tests
47         if (result == null) {
48             try {
49                 @SuppressWarnings("unchecked")
50                 Class<WebSocketContainer> clazz =
51                         (Class<WebSocketContainer>) Class.forName(
52                                 DEFAULT_PROVIDER_CLASS_NAME);
53                 result = clazz.getConstructor().newInstance();
54             } catch (ReflectiveOperationException | IllegalArgumentException |
55                     SecurityException e) {
56                 // No options left. Just return null.
57             }
58         }
59         return result;
60     }
61 
getContainer()62     protected abstract WebSocketContainer getContainer();
63 }
64