Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2011, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.remoting3.remote;
 
 import static org.jboss.remoting3.remote.RemoteLogger.log;
 import static org.jboss.remoting3.remote.RemoteLogger.server;
 
 
 
 import java.util.Set;
 import org.xnio.Pool;
 import org.xnio.Xnio;

Author(s):
David M. Lloyd
 
 
     private static final boolean USE_POOLING;
 
     static {
         boolean usePooling = true;
         try {
             usePooling = Boolean.parseBoolean(System.getProperty("jboss.remoting.pooled-buffers""true"));
         } catch (Throwable ignored) {}
          = usePooling;
     }
 
     private final ProviderInterface providerInterface = new ProviderInterface();
     private final Xnio xnio;
     private final XnioWorker xnioWorker;
     private final Pool<ByteBuffermessageBufferPool;
     private final Pool<ByteBufferframingBufferPool;
     private final boolean sslEnabled;
     private final Collection<CancellablependingInboundConnections = Collections.synchronizedSet(new HashSet<Cancellable>());
     private final Set<RemoteConnectionHandlerhandlers = Collections.synchronizedSet(new HashSet<RemoteConnectionHandler>());
     private final MBeanServer server;
     private final ObjectName objectName;
    RemoteConnectionProvider(final OptionMap optionMapfinal ConnectionProviderContext connectionProviderContextthrows IOException {
        super(connectionProviderContext.getExecutor());
         = connectionProviderContext.getXnio();
         = optionMap.get(.true);
         = connectionProviderContext.getXnioWorker();
        this. = connectionProviderContext;
        final int messageBufferSize = optionMap.get(..);
         =  ? new ByteBufferSlicePool(.messageBufferSizeoptionMap.get(.messageBufferSize * 2)) : Buffers.allocatedBufferPool(.messageBufferSize);
        final int framingBufferSize = messageBufferSize + 4;
         =  ? new ByteBufferSlicePool(.framingBufferSizeoptionMap.get(.framingBufferSize * 2)) : Buffers.allocatedBufferPool(.framingBufferSize);
        MBeanServer server = null;
        ObjectName objectName = null;
        try {
            server = ManagementFactory.getPlatformMBeanServer();
            objectName = new ObjectName("jboss.remoting.handler""name"connectionProviderContext.getEndpoint().getName() + "-" + hashCode());
            server.registerMBean(new RemoteConnectionProviderMXBean() {
                public void dumpConnectionState() {
                    doDumpConnectionState();
                }
                public String dumpConnectionStateToString() {
                    return doGetConnectionState();
                }
            }, objectName);
        } catch (Exception e) {
            // ignore
        }
        this. = server;
        this. = objectName;
    }
    private void doDumpConnectionState() {
        final StringBuilder b = new StringBuilder();
        doGetConnectionState(b);
        ..info(b);
    }
    private void doGetConnectionState(final StringBuilder b) {
        b.append("Connection state for ").append(this).append(':').append('\n');
        synchronized () {
            for (RemoteConnectionHandler handler : ) {
                handler.dumpState(b);
            }
        }
    }
    private String doGetConnectionState() {
        final StringBuilder b = new StringBuilder();
        doGetConnectionState(b);
        return b.toString();
    }
    public Cancellable connect(final SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal Result<ConnectionHandlerFactoryresultfinal CallbackHandler callbackHandlerXnioSsl xnioSslthrows IllegalArgumentException {
        if (! isOpen()) {
            throw new IllegalStateException("Connection provider is closed");
        }
        if (destination == null) {
            throw new IllegalArgumentException("destination address may not be null");
        }
        if (bindAddress != null && destination != null && bindAddress.getClass() != destination.getClass()) {
            throw new IllegalArgumentException("bind and destination addresses must be of the same type");
        }
        .tracef("Attempting to connect to \"%s\" with options %s"destinationconnectOptions);
        // cancellable that will be returned by this method
        final FutureResult<ConnectionHandlerFactorycancellableResult = new FutureResult<ConnectionHandlerFactory>();
        cancellableResult.addCancelHandler(new Cancellable() {
            @Override
            public Cancellable cancel() {
                cancellableResult.setCancelled();
                return this;
            }
        });
        final IoFuture<ConnectionHandlerFactoryreturnedFuture = cancellableResult.getIoFuture();
        returnedFuture.addNotifier(IoUtils.<ConnectionHandlerFactory>resultNotifier(), result);
        final boolean sslCapable = ;
        final boolean useSsl = sslCapable && connectOptions.get(.true) && !connectOptions.get(.false);
        final AccessControlContext accessControlContext = AccessController.getContext();
        final ChannelListener<ConnectedStreamChannelopenListener = new ChannelListener<ConnectedStreamChannel>() {
            public void handleEvent(final ConnectedStreamChannel channel) {
                try {
                    channel.setOption(..);
                } catch (IOException e) {
                    // ignore
                }
                final FramedMessageChannel messageChannel = new FramedMessageChannel(channel.allocate(), .allocate());
                final RemoteConnection remoteConnection = new RemoteConnection(channelmessageChannelconnectOptionsRemoteConnectionProvider.this);
                cancellableResult.addCancelHandler(new Cancellable() {
                    @Override
                    public Cancellable cancel() {
                        RemoteConnectionHandler.sendCloseRequestBody(remoteConnection);
                        remoteConnection.handlePreAuthCloseRequest();
                        return this;
                    }
                });
                if (messageChannel.isOpen()) {
                    remoteConnection.setResult(cancellableResult);
                    messageChannel.getWriteSetter().set(remoteConnection.getWriteListener());
                    final ClientConnectionOpenListener openListener = new ClientConnectionOpenListener(remoteConnectioncallbackHandleraccessControlContext , connectOptions);
                    openListener.handleEvent(messageChannel);
                }
            }
        };
        final IoFuture<? extends ConnectedStreamChannelfuture;
        if (useSsl && destination instanceof InetSocketAddress) {
            if (xnioSsl == null) {
                try {
                    xnioSsl = .getSslProvider(connectOptions);
                } catch (GeneralSecurityException e) {
                    result.setException(sslConfigFailure(e));
                    return IoUtils.nullCancellable();
                }
            }
            future = createSslConnection(bindAddress, (InetSocketAddressdestinationconnectOptionsxnioSslopenListener);
        } else {
            future = createConnection(bindAddressdestinationconnectOptionsopenListener);
        }
        .add(returnedFuture);
        // if the connection fails, we need to propagate that
            public void handleFailed(final IOException exceptionfinal FutureResult<ConnectionHandlerFactoryattachment) {
                attachment.setException(exception);
            }
            public void handleCancelled(final FutureResult<ConnectionHandlerFactoryattachment) {
                attachment.setCancelled();
            }
        }, cancellableResult);
            public void handleCancelled(IoFuture<ConnectionHandlerFactoryattachment) {
                .remove(attachment);
                future.cancel();
            }
            public void handleFailed(final IOException exceptionIoFuture<ConnectionHandlerFactoryattachment) {
                .remove(attachment);
            }
            public void handleDone(final ConnectionHandlerFactory dataIoFuture<ConnectionHandlerFactoryattachment) {
                .remove(attachment);
            }
        }, returnedFuture);
        return returnedFuture;
    }
    protected IoFuture<ConnectedStreamChannelcreateConnection(final SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal ChannelListener<ConnectedStreamChannelopenListener) {
        return bindAddress == null ? .connectStream(destinationopenListenerconnectOptions) : .connectStream(bindAddressdestinationopenListenernullconnectOptions);
    }
    protected IoFuture<ConnectedSslStreamChannelcreateSslConnection(final SocketAddress bindAddressfinal InetSocketAddress destinationfinal OptionMap connectOptionsfinal XnioSsl xnioSslfinal ChannelListener<ConnectedStreamChannelopenListener) {
        return bindAddress == null ? xnioSsl.connectSsl(, (InetSocketAddressdestinationopenListenerconnectOptions) : xnioSsl.connectSsl(, (InetSocketAddressbindAddress, (InetSocketAddressdestinationopenListenerconnectOptions);
    }
    public Object getProviderInterface() {
        return ;
    }
    protected void closeAction() {
        try {
            final Cancellable[] cancellables;
            synchronized () {
                cancellables = .toArray(new Cancellable[.size()]);
                .clear();
            }
            for (Cancellable pendingConnectioncancellables) {
                pendingConnection.cancel();
            }
            closeComplete();
        } finally {
            if ( != null &&  != null) {
                try {
                    .unregisterMBean();
                } catch (Throwable ignored) {
                }
            }
        }
    }
    void addConnectionHandler(final RemoteConnectionHandler connectionHandler) {
        .add(connectionHandler);
    }
    void removeConnectionHandler(final RemoteConnectionHandler connectionHandler) {
        .remove(connectionHandler);
    }
    final class ProviderInterface implements NetworkServerProvider {
        public AcceptingChannel<? extends ConnectedStreamChannelcreateServer(final SocketAddress bindAddressfinal OptionMap optionMapfinal ServerAuthenticationProvider authenticationProviderXnioSsl xnioSslthrows IOException {
            final AccessControlContext accessControlContext = AccessController.getContext();
            final boolean sslCapable = ;
            final AcceptListener acceptListener = new AcceptListener(optionMapauthenticationProvideraccessControlContext);
            final AcceptingChannel<? extends ConnectedStreamChannelresult;
            if (sslCapable && optionMap.get(.true)) {
                if (xnioSsl == null) {
                    try {
                        xnioSsl = .getSslProvider(optionMap);
                    } catch (GeneralSecurityException e) {
                        throw sslConfigFailure(e);
                    }
                }
                result = xnioSsl.createSslTcpServer(, (InetSocketAddressbindAddressacceptListeneroptionMap);
            } else {
                result = .createStreamServer(bindAddressacceptListeneroptionMap);
            }
            addCloseHandler(new CloseHandler<ConnectionProvider>() {
                public void handleClose(final ConnectionProvider closedfinal IOException exception) {
                    IoUtils.safeClose(result);
                }
            });
            result.resumeAccepts();
            return result;
        }
    }
    protected Executor getExecutor() {
        return super.getExecutor();
    }
    private static IOException sslConfigFailure(final GeneralSecurityException e) {
        return new IOException("Failed to configure SSL"e);
    }
    private final class AcceptListener implements ChannelListener<AcceptingChannel<? extends ConnectedStreamChannel>> {
        private final OptionMap serverOptionMap;
        private final AccessControlContext accessControlContext;
        AcceptListener(final OptionMap serverOptionMapfinal ServerAuthenticationProvider serverAuthenticationProviderfinal AccessControlContext accessControlContext) {
            this. = serverOptionMap;
            this. = serverAuthenticationProvider;
            this. = accessControlContext;
        }
        public void handleEvent(final AcceptingChannel<? extends ConnectedStreamChannelchannel) {
            final ConnectedStreamChannel accepted;
            try {
                accepted = channel.accept();
                if (accepted == null) {
                    return;
                }
            } catch (IOException e) {
                .failedToAccept(e);
                return;
            }
            try {
                accepted.setOption(..);
            } catch (IOException e) {
                // ignore
            }
            final FramedMessageChannel messageChannel = new FramedMessageChannel(accepted.allocate(), .allocate());
            final RemoteConnection connection = new RemoteConnection(acceptedmessageChannelRemoteConnectionProvider.this);
            messageChannel.getWriteSetter().set(connection.getWriteListener());
            ..tracef("Accepted connection from %s to %s"accepted.getPeerAddress(), accepted.getLocalAddress());
            openListener.handleEvent(messageChannel);
        }
    }
    public String toString() {
        return String.format("Remoting remote connection provider %x for %s", Integer.valueOf(hashCode()), .getEndpoint());
    }
    protected XnioWorker getXnioWorker() {
        return ;
    }
    public Pool<ByteBuffergetFramingBufferPool() {
        return ;
    }
        return ;
    }
    public Pool<ByteBuffergetMessageBufferPool() {
        return ;
    }
New to GrepCode? Check out our FAQ X