01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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: */package org.apache.openejb.client;
17:
18: import java.io.IOException;
19: import java.net.URI;
20: import java.rmi.RemoteException;
21: import java.util.logging.Level;
22: import java.util.logging.Logger;
23:
24: public class StickToLastServerConnectionFactoryStrategy implements
25: ConnectionFactoryStrategy {
26: private static final Logger LOGGER = Logger
27: .getLogger("OpenEJB.client");
28:
29: private URI lastLocation;
30:
31: public Connection connect(URI[] locations, Request request)
32: throws RemoteException {
33: if (null != lastLocation) {
34: for (int i = 0; i < locations.length; i++) {
35: if (locations[i].equals(lastLocation)) {
36: try {
37: return connect(lastLocation);
38: } catch (IOException e) {
39: LOGGER.log(Level.WARNING,
40: "Cannot connect to last server: "
41: + lastLocation.getHost() + ":"
42: + lastLocation.getPort()
43: + " Exception: ", e);
44: }
45: }
46: }
47: }
48:
49: Connection connection = null;
50: for (int i = 0; i < locations.length; i++) {
51: URI uri = locations[i];
52: try {
53: connection = connect(uri);
54: lastLocation = uri;
55: break;
56: } catch (IOException e) {
57: LOGGER.log(Level.WARNING,
58: "Cannot connect to server(s): " + uri.getHost()
59: + ":" + uri.getPort() + " Exception: ",
60: e);
61: } catch (Throwable e) {
62: throw new RemoteException(
63: "Cannot connect to server: "
64: + uri.getHost()
65: + ":"
66: + uri.getPort()
67: + " due to an unkown exception in the OpenEJB client: ",
68: e);
69: }
70: }
71: if (null != connection) {
72: return connection;
73: }
74:
75: // If no servers responded, throw an error
76: StringBuffer buffer = new StringBuffer();
77: for (int i = 0; i < locations.length; i++) {
78: URI uri = locations[i];
79: buffer.append((i != 0 ? ", " : "") + "Server #" + i + ": "
80: + uri);
81: }
82: throw new RemoteException("Cannot connect to any servers: "
83: + buffer.toString());
84: }
85:
86: protected Connection connect(URI uri) throws IOException {
87: return ConnectionManager.getConnection(uri);
88: }
89:
90: }
|