001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common Development
008: * and Distribution License("CDDL") (collectively, the "License"). You
009: * may not use this file except in compliance with the License. You can obtain
010: * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011: * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
012: * language governing permissions and limitations under the License.
013: *
014: * When distributing the software, include this License Header Notice in each
015: * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016: * Sun designates this particular file as subject to the "Classpath" exception
017: * as provided by Sun in the GPL Version 2 section of the License file that
018: * accompanied this code. If applicable, add the following below the License
019: * Header, with the fields enclosed by brackets [] replaced by your own
020: * identifying information: "Portions Copyrighted [year]
021: * [name of copyright owner]"
022: *
023: * Contributor(s):
024: *
025: * If you wish your version of this file to be governed by only the CDDL or
026: * only the GPL Version 2, indicate your decision by adding "[Contributor]
027: * elects to include this software in this distribution under the [CDDL or GPL
028: * Version 2] license." If you don't indicate a single choice of license, a
029: * recipient has the option to distribute your version of this file under
030: * either the CDDL, the GPL Version 2 or to extend the choice of license to
031: * its licensees as provided above. However, if you add GPL Version 2 code
032: * and therefore, elected the GPL Version 2 license, then the option applies
033: * only if the new code is made subject to such option by the copyright
034: * holder.
035: */
036:
037: package com.sun.xml.ws.transport.tcp.client;
038:
039: import com.sun.istack.NotNull;
040: import com.sun.xml.ws.api.WSBinding;
041: import com.sun.xml.ws.api.WSService;
042: import com.sun.xml.ws.api.pipe.Codec;
043: import com.sun.xml.ws.client.ClientTransportException;
044: import com.sun.xml.ws.transport.tcp.resources.MessagesMessages;
045: import com.sun.xml.ws.transport.tcp.util.ChannelSettings;
046: import com.sun.xml.ws.transport.tcp.io.Connection;
047: import com.sun.xml.ws.transport.tcp.util.ChannelContext;
048: import com.sun.xml.ws.transport.tcp.util.ConnectionSession;
049: import com.sun.xml.ws.transport.tcp.util.SessionAbortedException;
050: import com.sun.xml.ws.transport.tcp.util.SessionCloseListener;
051: import com.sun.xml.ws.transport.tcp.util.TCPConstants;
052: import com.sun.xml.ws.transport.tcp.util.Version;
053: import com.sun.xml.ws.transport.tcp.util.VersionController;
054: import com.sun.xml.ws.transport.tcp.util.VersionMismatchException;
055: import com.sun.xml.ws.transport.tcp.util.WSTCPURI;
056: import com.sun.xml.ws.transport.tcp.servicechannel.ServiceChannelException;
057: import com.sun.xml.ws.transport.tcp.servicechannel.stubs.ServiceChannelWSImpl;
058: import com.sun.xml.ws.transport.tcp.servicechannel.stubs.ServiceChannelWSImplService;
059: import com.sun.xml.ws.transport.tcp.util.BindingUtils;
060: import com.sun.xml.ws.transport.tcp.io.DataInOutUtils;
061: import com.sun.xml.ws.transport.tcp.wsit.ConnectionManagementSettings;
062: import com.sun.xml.ws.transport.tcp.connectioncache.spi.transport.ConnectionFinder;
063: import com.sun.xml.ws.transport.tcp.connectioncache.spi.transport.OutboundConnectionCache;
064: import com.sun.xml.ws.transport.tcp.connectioncache.spi.transport.ConnectionCacheFactory;
065: import com.sun.xml.ws.transport.tcp.connectioncache.spi.transport.ContactInfo;
066: import java.io.IOException;
067: import java.io.InputStream;
068: import java.io.OutputStream;
069: import java.util.Collection;
070: import java.util.HashMap;
071: import java.util.List;
072: import java.util.Map;
073: import java.util.logging.Level;
074: import java.util.logging.Logger;
075: import javax.xml.ws.BindingProvider;
076: import javax.xml.ws.Holder;
077:
078: /**
079: * @author Alexey Stashok
080: */
081: @SuppressWarnings({"unchecked"})
082: public class WSConnectionManager implements
083: ConnectionFinder<ConnectionSession>,
084: SessionCloseListener<ConnectionSession> {
085: private static final Logger logger = Logger
086: .getLogger(com.sun.xml.ws.transport.tcp.util.TCPConstants.LoggingDomain
087: + ".client");
088:
089: private static final int HIGH_WATER_MARK = 1500;
090: private static final int NUMBER_TO_RECLAIM = 1;
091: private static final int MAX_PARALLEL_CONNECTIONS = 5;
092:
093: private static final WSConnectionManager instance = new WSConnectionManager();
094:
095: // set of locked connections, which are in use
096: private final Map<ConnectionSession, Thread> lockedConnections = new HashMap<ConnectionSession, Thread>();
097:
098: public static WSConnectionManager getInstance() {
099: return instance;
100: }
101:
102: // Cache for outbound connections (orb)
103: private volatile OutboundConnectionCache<ConnectionSession> connectionCache;
104:
105: private WSConnectionManager() {
106: int highWatermark = HIGH_WATER_MARK;
107: int numberToReclaim = NUMBER_TO_RECLAIM;
108: int maxParallelConnections = MAX_PARALLEL_CONNECTIONS;
109:
110: ConnectionManagementSettings policySettings = ConnectionManagementSettings
111: .getClientSettingsInstance();
112: if (policySettings != null) {
113: highWatermark = policySettings
114: .getHighWatermark(HIGH_WATER_MARK);
115: numberToReclaim = policySettings
116: .getNumberToReclaim(NUMBER_TO_RECLAIM);
117: maxParallelConnections = policySettings
118: .getMaxParallelConnections(MAX_PARALLEL_CONNECTIONS);
119: }
120:
121: connectionCache = ConnectionCacheFactory
122: .<ConnectionSession> makeBlockingOutboundConnectionCache(
123: "SOAP/TCP client side cache", highWatermark,
124: numberToReclaim, maxParallelConnections, logger);
125: }
126:
127: public @NotNull
128: ChannelContext openChannel(@NotNull
129: final WSTCPURI uri, @NotNull
130: final WSService wsService, @NotNull
131: final WSBinding wsBinding, final @NotNull
132: Codec defaultCodec) throws InterruptedException, IOException,
133: ServiceChannelException, VersionMismatchException {
134: final int uriHashKey = uri.hashCode();
135:
136: if (logger.isLoggable(Level.FINE)) {
137: logger.log(Level.FINE, MessagesMessages
138: .WSTCP_1030_CONNECTION_MANAGER_ENTER(uri, wsService
139: .getServiceName(),
140: wsBinding.getBindingID(), defaultCodec
141: .getClass().getName()));
142: }
143:
144: // Try to use available connection to endpoint
145: final ConnectionSession session = connectionCache
146: .get(uri, this );
147: ChannelContext channelContext = session
148: .findWSServiceContextByURI(uri);
149: if (channelContext == null) {
150: channelContext = doOpenChannel(session, uri, wsService,
151: wsBinding, defaultCodec);
152: }
153:
154: if (logger.isLoggable(Level.FINE)) {
155: logger
156: .log(
157: Level.FINE,
158: MessagesMessages
159: .WSTCP_1033_CONNECTION_MANAGER_RETURN_CHANNEL_CONTEXT(channelContext
160: .getChannelId()));
161: }
162: return channelContext;
163: }
164:
165: public void closeChannel(@NotNull
166: final ChannelContext channelContext) {
167: final ConnectionSession connectionSession = channelContext
168: .getConnectionSession();
169: final ServiceChannelWSImpl serviceChannelWSImplPort = getSessionServiceChannel(connectionSession);
170:
171: try {
172: lockConnection(connectionSession);
173: serviceChannelWSImplPort.closeChannel(channelContext
174: .getChannelId());
175: connectionSession.deregisterChannel(channelContext);
176: } catch (SessionAbortedException e) {
177: // if session was closed before
178: } catch (InterruptedException e) {
179: } catch (ServiceChannelException e) {
180: } finally {
181: freeConnection(connectionSession);
182: }
183: }
184:
185: public void lockConnection(@NotNull
186: final ConnectionSession connectionSession)
187: throws InterruptedException, SessionAbortedException {
188: synchronized (connectionSession) {
189: do {
190: final Thread thread = lockedConnections
191: .get(connectionSession);
192: if (thread == null) {
193: lockedConnections.put(connectionSession, Thread
194: .currentThread());
195: return;
196: } else if (thread.equals(Thread.currentThread())) {
197: return;
198: }
199: connectionSession.wait(500);
200: } while (true);
201: }
202: }
203:
204: public void freeConnection(@NotNull
205: final ConnectionSession connectionSession) {
206: connectionCache.release(connectionSession, 0);
207: synchronized (connectionSession) {
208: lockedConnections.put(connectionSession, null);
209: connectionSession.notify();
210: }
211: }
212:
213: public void abortConnection(@NotNull
214: final ConnectionSession connectionSession) {
215: connectionCache.close(connectionSession);
216: }
217:
218: /**
219: * Open new tcp connection and establish service virtual connection
220: */
221: public @NotNull
222: ConnectionSession createConnectionSession(@NotNull
223: final WSTCPURI tcpURI) throws VersionMismatchException,
224: ServiceChannelException {
225: try {
226: if (logger.isLoggable(Level.FINE)) {
227: logger
228: .log(
229: Level.FINE,
230: MessagesMessages
231: .WSTCP_1034_CONNECTION_MANAGER_CREATE_SESSION_ENTER(tcpURI));
232: }
233: final Connection connection = Connection.create(
234: tcpURI.host, tcpURI.port);
235: doSendMagicAndCheckVersions(connection);
236: final ConnectionSession connectionSession = new ClientConnectionSession(
237: connection, this );
238:
239: final ServiceChannelWSImplService serviceChannelWS = new ServiceChannelWSImplService();
240: final ServiceChannelWSImpl serviceChannelWSImplPort = serviceChannelWS
241: .getServiceChannelWSImplPort();
242: connectionSession.setAttribute(
243: TCPConstants.SERVICE_PIPELINE_ATTR_NAME,
244: serviceChannelWSImplPort);
245:
246: final BindingProvider bindingProvider = (BindingProvider) serviceChannelWSImplPort;
247: bindingProvider.getRequestContext().put(
248: TCPConstants.TCP_SESSION, connectionSession);
249:
250: if (logger.isLoggable(Level.FINE)) {
251: logger
252: .log(
253: Level.FINE,
254: MessagesMessages
255: .WSTCP_1035_CONNECTION_MANAGER_INITIATE_SESSION());
256: }
257:
258: //@TODO check initiateSession result
259: serviceChannelWSImplPort.initiateSession();
260:
261: return connectionSession;
262: } catch (IOException e) {
263: // ClientTransportException could be processed special way, outside transport layer
264: throw new ClientTransportException(
265: MessagesMessages
266: .localizableWSTCP_0015_ERROR_PROTOCOL_VERSION_EXCHANGE(),
267: e);
268: }
269: }
270:
271: /**
272: * Open new channel over existing connection session
273: */
274: private @NotNull
275: ChannelContext doOpenChannel(@NotNull
276: final ConnectionSession connectionSession, @NotNull
277: final WSTCPURI targetWSURI, @NotNull
278: final WSService wsService, @NotNull
279: final WSBinding wsBinding, final @NotNull
280: Codec defaultCodec) throws IOException, ServiceChannelException {
281: if (logger.isLoggable(Level.FINEST)) {
282: logger
283: .log(
284: Level.FINEST,
285: MessagesMessages
286: .WSTCP_1036_CONNECTION_MANAGER_DO_OPEN_CHANNEL_ENTER());
287: }
288: final ServiceChannelWSImpl serviceChannelWSImplPort = getSessionServiceChannel(connectionSession);
289:
290: // Send to server possible mime types and parameters
291: final BindingUtils.NegotiatedBindingContent negotiatedContent = BindingUtils
292: .getNegotiatedContentTypesAndParams(wsBinding);
293:
294: if (logger.isLoggable(Level.FINEST)) {
295: logger.log(Level.FINEST, MessagesMessages
296: .WSTCP_1037_CONNECTION_MANAGER_DO_OPEN_WS_CALL(
297: targetWSURI,
298: negotiatedContent.negotiatedMimeTypes,
299: negotiatedContent.negotiatedParams));
300: }
301:
302: Holder<List<String>> negotiatedMimeTypesHolder = new Holder<List<String>>(
303: negotiatedContent.negotiatedMimeTypes);
304: Holder<List<String>> negotiatedParamsHolder = new Holder<List<String>>(
305: negotiatedContent.negotiatedParams);
306: final int channelId = serviceChannelWSImplPort.openChannel(
307: targetWSURI.toString(), negotiatedMimeTypesHolder,
308: negotiatedParamsHolder);
309:
310: ChannelSettings settings = new ChannelSettings(
311: negotiatedMimeTypesHolder.value,
312: negotiatedParamsHolder.value, channelId, wsService
313: .getServiceName(), targetWSURI);
314:
315: if (logger.isLoggable(Level.FINEST)) {
316: logger
317: .log(
318: Level.FINEST,
319: MessagesMessages
320: .WSTCP_1038_CONNECTION_MANAGER_DO_OPEN_PROCESS_SERVER_SETTINGS(settings));
321: }
322: final ChannelContext channelContext = new ChannelContext(
323: connectionSession, settings);
324:
325: ChannelContext.configureCodec(channelContext, wsBinding
326: .getSOAPVersion(), defaultCodec);
327:
328: if (logger.isLoggable(Level.FINEST)) {
329: logger
330: .log(
331: Level.FINEST,
332: MessagesMessages
333: .WSTCP_1039_CONNECTION_MANAGER_DO_OPEN_REGISTER_CHANNEL(channelContext
334: .getChannelId()));
335: }
336: connectionSession.registerChannel(channelContext);
337: return channelContext;
338: }
339:
340: /**
341: * Get ConnectionSession's ServiceChannel web service
342: */
343: private @NotNull
344: ServiceChannelWSImpl getSessionServiceChannel(@NotNull
345: final ConnectionSession connectionSession) {
346: return (ServiceChannelWSImpl) connectionSession
347: .getAttribute(TCPConstants.SERVICE_PIPELINE_ATTR_NAME);
348: }
349:
350: public ConnectionSession find(
351: final ContactInfo<ConnectionSession> contactInfo,
352: final Collection<ConnectionSession> idleConnections,
353: final Collection<ConnectionSession> busyConnections)
354: throws IOException {
355: final WSTCPURI wsTCPURI = (WSTCPURI) contactInfo;
356: ConnectionSession lru = null;
357: for (ConnectionSession connectionSession : idleConnections) {
358: if (connectionSession.findWSServiceContextByURI(wsTCPURI) != null) {
359: return connectionSession;
360: }
361: if (lru == null)
362: lru = connectionSession;
363: }
364:
365: if (lru != null
366: || connectionCache.canCreateNewConnection(contactInfo))
367: return lru;
368:
369: for (ConnectionSession connectionSession : busyConnections) {
370: if (connectionSession.findWSServiceContextByURI(wsTCPURI) != null) {
371: return connectionSession;
372: }
373: if (lru == null)
374: lru = connectionSession;
375: }
376:
377: return lru;
378: }
379:
380: public void notifySessionClose(ConnectionSession connectionSession) {
381: if (logger.isLoggable(Level.FINE)) {
382: logger
383: .log(
384: Level.FINE,
385: MessagesMessages
386: .WSTCP_1043_CONNECTION_MANAGER_NOTIFY_SESSION_CLOSE(connectionSession
387: .getConnection()));
388: }
389: freeConnection(connectionSession);
390: }
391:
392: private static void doSendMagicAndCheckVersions(
393: final Connection connection) throws IOException,
394: VersionMismatchException {
395: final VersionController versionController = VersionController
396: .getInstance();
397: final Version framingVersion = versionController
398: .getFramingVersion();
399: final Version connectionManagementVersion = versionController
400: .getConnectionManagementVersion();
401:
402: if (logger.isLoggable(Level.FINE)) {
403: logger
404: .log(
405: Level.FINE,
406: MessagesMessages
407: .WSTCP_1040_CONNECTION_MANAGER_DO_CHECK_VERSION_ENTER(
408: framingVersion,
409: connectionManagementVersion));
410: }
411: connection.setDirectMode(true);
412:
413: final OutputStream outputStream = connection.openOutputStream();
414: outputStream.write(TCPConstants.PROTOCOL_SCHEMA
415: .getBytes("US-ASCII"));
416:
417: DataInOutUtils.writeInts4(outputStream, framingVersion
418: .getMajor(), framingVersion.getMinor(),
419: connectionManagementVersion.getMajor(),
420: connectionManagementVersion.getMinor());
421: connection.flush();
422: if (logger.isLoggable(Level.FINE)) {
423: logger
424: .log(
425: Level.FINE,
426: MessagesMessages
427: .WSTCP_1041_CONNECTION_MANAGER_DO_CHECK_VERSION_SENT());
428: }
429:
430: final InputStream inputStream = connection.openInputStream();
431: final int[] versionInfo = new int[4];
432:
433: DataInOutUtils.readInts4(inputStream, versionInfo, 4);
434:
435: final Version serverFramingVersion = new Version(
436: versionInfo[0], versionInfo[1]);
437: final Version serverConnectionManagementVersion = new Version(
438: versionInfo[2], versionInfo[3]);
439:
440: connection.setDirectMode(false);
441:
442: final boolean success = versionController
443: .isVersionSupported(serverFramingVersion,
444: serverConnectionManagementVersion);
445:
446: if (!success) {
447: throw new VersionMismatchException(MessagesMessages
448: .WSTCP_0006_VERSION_MISMATCH(),
449: serverFramingVersion,
450: serverConnectionManagementVersion);
451: }
452: }
453: }
|