Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   * Copyright 2010, JBoss Inc., and individual contributors as indicated
   * by the @authors tag. See the copyright.txt 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;
 
 import java.net.URI;
 import java.util.Set;
 
 
 import org.xnio.Xnio;
 
 final class EndpointImpl extends AbstractHandleableCloseable<Endpointimplements Endpoint {
 
     static {
         // Print Remoting "greeting" message
         Logger.getLogger("org.jboss.remoting").infof("JBoss Remoting version %s", Version.getVersionString());
     }
 
     private static final Logger log = Logger.getLogger("org.jboss.remoting.endpoint");
 
     private static final RemotingPermission REGISTER_SERVICE_PERM = new RemotingPermission("registerService");
     private static final RemotingPermission CONNECT_PERM = new RemotingPermission("connect");
     private static final RemotingPermission ADD_CONNECTION_PROVIDER_PERM = new RemotingPermission("addConnectionProvider");
     private static final RemotingPermission GET_CONNECTION_PROVIDER_INTERFACE_PERM = new RemotingPermission("getConnectionProviderInterface");
     private static final int CLOSED_FLAG = 0x80000000;
     private static final int COUNT_MASK = ~();
     private static final String FQCN = EndpointImpl.class.getName();
 
     private final Set<ConnectionImplconnections = Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<ConnectionImplBoolean>()));
 
     private final Attachments attachments = new Attachments();
 
 
     private final Xnio xnio;
     private final XnioWorker worker;
 
     private final Object connectionLock = new Object();
 
     private static final AtomicIntegerFieldUpdater<EndpointImplresourceCountUpdater = AtomicIntegerFieldUpdater.newUpdater(EndpointImpl.class"resourceCount");
 
     @SuppressWarnings("unused")
     private volatile int resourceCount = 0;
 
     private static final Pattern VALID_SERVICE_PATTERN = Pattern.compile("[-.:a-zA-Z_0-9]+");

    
The name of this endpoint.
    private final String name;
    @SuppressWarnings("unused")
    private final OptionMap optionMap;
    private final CloseHandler<ObjectresourceCloseHandler = new CloseHandler<Object>() {
        public void handleClose(final Object closedfinal IOException exception) {
            closeTick1(closed);
        }
    };
    private final boolean ourWorker;
    private EndpointImpl(final XnioWorker xnioWorkerfinal boolean ourWorkerfinal String namefinal OptionMap optionMapthrows IOException {
        super(xnioWorkertrue);
         = xnioWorker;
        this. = ourWorker;
        this. = xnioWorker.getXnio();
        this. = name;
        this. = optionMap;
        // initialize CPC
        // add default connection providers
        // get XNIO worker
        .tracef("Completed open of %s"this);
    }
    static EndpointImpl construct(final XnioWorker xnioWorkerfinal boolean ourWorkerfinal String namefinal OptionMap optionMapthrows IOException {
        return new EndpointImpl(xnioWorkerourWorkernameoptionMap);
    }
    public Attachments getAttachments() {
        return ;
    }
    public String getName() {
        return ;
    }
    public Executor getExecutor() {
        return ;
    }
    protected void closeComplete() {
        super.closeComplete();
    }
    private void closeTick1(Object c) {
        int res = .decrementAndGet(this);
        if (res == ) {
            // this was the last phase 1 resource.
            finishPhase1();
        } else if ((res & ) != 0) {
            // shutdown is currently in progress.
            if (.isTraceEnabled()) {
                .logf(..null"Phase 1 shutdown count %08x of %s (closed %s)", Integer.valueOf(res & ), thisc);
            }
        } else {
            if (.isTraceEnabled()) {
                .logf(..null"Resource closed count %08x of %s (closed %s)", Integer.valueOf(res & ), thisc);
            }
        }
    }
    private void finishPhase1() {
        // all our original resources were closed; now move on to stage two (thread pools)
        .tracef("Finished phase 1 shutdown of %s"this);
        if () {
            .shutdown();
        } else {
            closeComplete();
        }
        return;
    }
    void resourceUntick(Object openedthrows NotOpenException {
        int old;
        do {
            old = .get(this);
            if ((old & ) != 0) {
                throw new NotOpenException("Endpoint is not open");
            }
        } while (! .compareAndSet(thisoldold + 1));
        if (.isTraceEnabled()) {
            .tracef("Allocated tick to %d of %s (opened %s)", Integer.valueOf(old + 1), thisopened);
        }
    }
    protected void closeAction() throws IOException {
        synchronized () {
            // Commence phase one shutdown actions
            int res;
            do {
                res = ;
            } while (! .compareAndSet(thisresres | ));
            if (res == 0) {
                finishPhase1();
            } else {
                for (Object connection : .toArray()) {
                    ((ConnectionImpl)connection).closeAsync();
                }
                for (ConnectionProvider connectionProvider : .values()) {
                    connectionProvider.closeAsync();
                }
            }
        }
    }
    public Registration registerService(final String serviceTypefinal OpenListener openListenerfinal OptionMap optionMapthrows ServiceRegistrationException {
        if (! .matcher(serviceType).matches()) {
            throw new IllegalArgumentException("Service type must match " + );
        }
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission();
        }
        final RegisteredServiceImpl registeredService = new RegisteredServiceImpl(openListeneroptionMap);
        if (.putIfAbsent(serviceTyperegisteredService) != null) {
            throw new ServiceRegistrationException("Service type '" + serviceType + "' is already registered");
        }
        final MapRegistration<RegisteredServiceImplregistration = new MapRegistration<RegisteredServiceImpl>(serviceTyperegisteredService) {
            protected void closeAction() throws IOException {
                try {
                    openListener.registrationTerminated();
                } finally {
                    super.closeAction();
                }
            }
        };
        // automatically close the registration when the endpoint is closed
        final Key key = addCloseHandler(SpiUtils.closingCloseHandler(registration));
        registration.addCloseHandler(new CloseHandler<Registration>() {
            public void handleClose(final Registration closedfinal IOException exception) {
                key.remove();
            }
        });
        return registration;
    }
    private IoFuture<ConnectiondoConnect(final URI urifinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal XnioSsl xnioSslthrows IOException {
        final String scheme = uri.getScheme();
        final String destinationHost = uri.getHost();
        final SocketAddress destination;
        if (destinationHost != null) {
            final int destinationPort = uri.getPort();
            destination = new InetSocketAddress(destinationHostdestinationPort == -1 ? 0 : destinationPort);
        } else {
            destination = null;
        }
        return doConnect(schemenulldestinationconnectOptionscallbackHandlerxnioSsl);
    }
    private IoFuture<ConnectiondoConnect(final String schemefinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal XnioSsl xnioSslthrows IOException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission();
        }
        synchronized () {
            boolean ok = false;
            resourceUntick("Connection to " + destination);
            try {
                final ConnectionProvider connectionProvider = .get(scheme);
                if (connectionProvider == null) {
                    throw new UnknownURISchemeException("No connection provider for URI scheme \"" + scheme + "\" is installed");
                }
                final FutureResult<ConnectionfutureResult = new FutureResult<Connection>(getExecutor());
                final FutureResult<ConnectionHandlerFactoryconnHandlerFuture = new FutureResult<ConnectionHandlerFactory>();
                // Mark the stack because otherwise debugging connect problems can be incredibly tough
                final StackTraceElement[] mark = Thread.currentThread().getStackTrace();
                connHandlerFuture.getIoFuture().addNotifier(new HandlingNotifier<ConnectionHandlerFactoryVoid>() {
                    public void handleCancelled(final Void attachment) {
                        .logf(getClass().getName(), ..null"Registered cancellation result");
                        closeTick1("a cancelled connection");
                        futureResult.setCancelled();
                    }
                    public void handleFailed(final IOException exceptionfinal Void attachment) {
                        .logf(getClass().getName(), ..exception"Registered exception result");
                        closeTick1("a failed connection (2)");
                        SpiUtils.glueStackTraces(exceptionmark, 1, "asynchronous invocation");
                        futureResult.setException(exception);
                    }
                    public void handleDone(final ConnectionHandlerFactory connHandlerFactoryfinal Void attachment) {
                        .logf(getClass().getName(), ..null"Registered successful result %s"connHandlerFactory);
                        final ConnectionImpl connection = new ConnectionImpl(EndpointImpl.thisconnHandlerFactory);
                        .add(connection);
                        connection.getConnectionHandler().addCloseHandler(SpiUtils.asyncClosingCloseHandler(connection));
                        connection.addCloseHandler();
                        connection.addCloseHandler();
                        futureResult.setResult(connection);
                    }
                }, null);
                final Cancellable connect = connectionProvider.connect(bindAddressdestinationconnectOptions,  connHandlerFuturecallbackHandlerxnioSsl);
                ok = true;
                futureResult.addCancelHandler(connect);
                return futureResult.getIoFuture();
            } finally {
                if (! ok) {
                    closeTick1("a failed connection (1)");
                }
            }
        }
    }
    public IoFuture<Connectionconnect(final URI destinationthrows IOException {
        final UserAndRealm userRealm = getUserAndRealm(destination);
        final String uriUserName = userRealm.getUser();
        final String uriUserRealm = userRealm.getRealm();
        final OptionMap finalMap;
        final OptionMap.Builder builder = OptionMap.builder();
        if (uriUserName != nullbuilder.set(.uriUserName);
        if (uriUserRealm != nullbuilder.set(.uriUserRealm);
        finalMap = builder.getMap();
        return doConnect(destinationfinalMapnew PasswordClientCallbackHandler(finalMap.get(.), finalMap.get(.), null), null);
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsthrows IOException {
        final UserAndRealm userRealm = getUserAndRealm(destination);
        final String uriUserName = userRealm.getUser();
        final String uriUserRealm = userRealm.getRealm();
        final OptionMap finalMap;
        final OptionMap.Builder builder = OptionMap.builder().addAll(connectOptions);
        if (uriUserName != nullbuilder.set(.uriUserName);
        if (uriUserRealm != nullbuilder.set(.uriUserRealm);
        finalMap = builder.getMap();
        return doConnect(destinationfinalMapnew PasswordClientCallbackHandler(finalMap.get(.), finalMap.get(.), null), null);
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerthrows IOException {
        return connect(destinationconnectOptionscallbackHandler, (XnioSslnull);
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal SSLContext sslContextthrows IOException {
        return connect(destinationconnectOptionscallbackHandlersslContext == null ? (XnioSslnull : new JsseXnioSsl(sslContext));
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal XnioSsl xnioSslthrows IOException {
        final UserAndRealm userRealm = getUserAndRealm(destination);
        final String uriUserName = userRealm.getUser();
        final String uriUserRealm = userRealm.getRealm();
        final OptionMap finalMap;
        final OptionMap.Builder builder = OptionMap.builder().addAll(connectOptions);
        if (uriUserName != nullbuilder.set(.uriUserName);
        if (uriUserRealm != nullbuilder.set(.uriUserRealm);
        finalMap = builder.getMap();
        return doConnect(destinationfinalMapcallbackHandlerxnioSsl);
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal String userNamefinal String realmNamefinal char[] passwordthrows IOException {
        return connect(destinationconnectOptionsuserNamerealmNamepassword, (XnioSslnull);
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal String userNamefinal String realmNamefinal char[] passwordfinal SSLContext sslContextthrows IOException {
        return connect(destinationconnectOptionsuserNamerealmNamepasswordsslContext == null ? (XnioSslnull : new JsseXnioSsl(sslContext));
    }
    public IoFuture<Connectionconnect(final URI destinationfinal OptionMap connectOptionsfinal String userNamefinal String realmNamefinal char[] passwordfinal XnioSsl xnioSslthrows IOException {
        final UserAndRealm userRealm = getUserAndRealm(destination);
        final String uriUserName = userRealm.getUser();
        final String uriUserRealm = userRealm.getRealm();
        final String actualUserName = userName != null ? userName : uriUserName != null ? uriUserName : connectOptions.get(.);
        final String actualUserRealm = realmName != null ? realmName : uriUserRealm != null ? uriUserRealm : connectOptions.get(.);
        final OptionMap.Builder builder = OptionMap.builder().addAll(connectOptions);
        if (actualUserName != nullbuilder.set(.actualUserName);
        if (actualUserRealm != nullbuilder.set(.actualUserRealm);
        final OptionMap finalMap = builder.getMap();
        return doConnect(destinationfinalMapnew PasswordClientCallbackHandler(actualUserNameactualUserRealmpassword), xnioSsl);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationthrows IOException {
        return doConnect(protocolbindAddressdestination.nullnull);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsthrows IOException {
        return doConnect(protocolbindAddressdestinationconnectOptionsnullnull);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerthrows IOException {
        return doConnect(protocolbindAddressdestinationconnectOptionscallbackHandlernull);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal SSLContext sslContextthrows IOException {
        return doConnect(protocolbindAddressdestinationconnectOptionscallbackHandlersslContext == null ? (XnioSslnull : new JsseXnioSsl(sslContext));
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal CallbackHandler callbackHandlerfinal XnioSsl xnioSslthrows IOException {
        return doConnect(protocolbindAddressdestinationconnectOptionscallbackHandlerxnioSsl);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsString userNameString realmNamefinal char[] passwordthrows IOException {
        return connect(protocolbindAddressdestinationconnectOptionsuserNamerealmNamepassword, (XnioSslnull);
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsfinal String userNamefinal String realmNamefinal char[] passwordfinal SSLContext sslContextthrows IOException {
        return connect(protocolbindAddressdestinationconnectOptionsuserNamerealmNamepasswordsslContext == null ? (XnioSslnull : new JsseXnioSsl(sslContext));
    }
    public IoFuture<Connectionconnect(final String protocolfinal SocketAddress bindAddressfinal SocketAddress destinationfinal OptionMap connectOptionsString userNameString realmNamefinal char[] passwordfinal XnioSsl xnioSslthrows IOException {
        final OptionMap.Builder builder = OptionMap.builder().addAll(connectOptions);
        if (userName != nullbuilder.set(.userName); else userName = .get(.);
        if (realmName != nullbuilder.set(.realmName); else realmName = .get(.);
        final OptionMap finalMap = builder.getMap();
        return doConnect(protocolbindAddressdestinationfinalMapnew PasswordClientCallbackHandler(userNamerealmNamepassword), xnioSsl);
    }
    public Registration addConnectionProvider(final String uriSchemefinal ConnectionProviderFactory providerFactoryfinal OptionMap optionMapthrows IOException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
        }
        boolean ok = false;
        resourceUntick("Connection provider for " + uriScheme);
        try {
            final ConnectionProviderContextImpl context = new ConnectionProviderContextImpl();
            final ConnectionProvider provider = providerFactory.createInstance(contextoptionMap);
            try {
                if (.putIfAbsent(uriSchemeprovider) != null) {
                    throw new DuplicateRegistrationException("URI scheme '" + uriScheme + "' is already registered to a provider");
                }
                // add a resource count for close
                .tracef("Adding connection provider registration named '%s': %s"uriSchemeprovider);
                final Registration registration = new MapRegistration<ConnectionProvider>(uriSchemeprovider) {
                    protected void closeAction() throws IOException {
                        try {
                            provider.closeAsync();
                        } finally {
                            super.closeAction();
                        }
                    }
                };
                provider.addCloseHandler(new CloseHandler<ConnectionProvider>() {
                    public void handleClose(final ConnectionProvider closedfinal IOException exception) {
                        registration.closeAsync();
                        closeTick1(closed);
                    }
                });
                ok = true;
                return registration;
            } finally {
                if (! ok) {
                    provider.close();
                }
            }
        } finally {
            if (! ok) {
                closeTick1("Connection provider for " + uriScheme);
            }
        }
    }
    public <T> T getConnectionProviderInterface(final String uriSchemefinal Class<T> expectedTypethrows UnknownURISchemeExceptionClassCastException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
        }
        if (! expectedType.isInterface()) {
            throw new IllegalArgumentException("Interface expected");
        }
        final ConnectionProvider provider = .get(uriScheme);
        if (provider == null) {
            throw new UnknownURISchemeException("No connection provider for URI scheme \"" + uriScheme + "\" is installed");
        }
        return expectedType.cast(provider.getProviderInterface());
    }
    public boolean isValidUriScheme(final String uriScheme) {
        return .containsKey(uriScheme);
    }
    public XnioWorker getXnioWorker() {
        return ;
    }
    public String toString() {
        StringBuilder b = new StringBuilder();
        b.append("endpoint ");
        if ( != null) {
            b.append('"').append().append('"');
        } else {
            b.append("(anonymous)");
        }
        b.append(" <").append(Integer.toHexString(hashCode())).append(">");
        return b.toString();
    }
    private static final Charset UTF_8 = Charset.forName("UTF-8");
    private static String uriDecode(String encoded) {
        final char[] chars = encoded.toCharArray();
        final int olen = chars.length;
        final byte[] buf = new byte[olen];
        int c = 0;
        for (int i = 0; i < oleni++) {
            final char ch = chars[i];
            if (ch == '%') {
                buf[c++] = (byte) (Character.digit(chars[++i], 16) << 4 | Character.digit(chars[++i], 16));
            } else if (ch < 32 || ch > 127) {
                // skip it
            } else {
                buf[c++] = (bytech;
            }
        }
        return new String(buf, 0, c);
    }
    static final class UserAndRealm {
        private final String user;
        private final String realm;
        UserAndRealm(final String userfinal String realm) {
            this. = user;
            this. = realm;
        }
        public String getUser() {
            return ;
        }
        public String getRealm() {
            return ;
        }
    }
    private static final UserAndRealm EMPTY = new UserAndRealm(nullnull);
    private UserAndRealm getUserAndRealm(URI uri) {
        final String userInfo = uri.getRawUserInfo();
        if (userInfo == null) {
            return ;
        }
        int i = userInfo.indexOf(';');
        if (i == -1) {
            return new UserAndRealm(uri.getUserInfo(), null);
        } else {
            return new UserAndRealm(uriDecode(userInfo.substring(0, i)), uriDecode(userInfo.substring(i + 1)));
        }
    }
    private class MapRegistration<T> extends AbstractHandleableCloseable<Registrationimplements Registration {
        private final ConcurrentMap<String, T> map;
        private final String key;
        private final T value;
        private MapRegistration(final ConcurrentMap<String, T> mapfinal String keyfinal T value) {
            super(false);
            this. = map;
            this. = key;
            this. = value;
        }
        protected void closeAction() throws IOException {
            .remove();
            closeComplete();
        }
        public void close() {
            try {
                super.close();
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
        public String toString() {
            return String.format("Registration of '%s': %s");
        }
    }
    final class LocalConnectionContext implements ConnectionHandlerContext {
        private final Connection connection;
        LocalConnectionContext(final ConnectionProviderContext connectionProviderContextfinal Connection connection) {
            this. = connectionProviderContext;
            this. = connection;
        }
            return ;
        }
        @Deprecated
        public OpenListener getServiceOpenListener(final String serviceType) {
            final RegisteredServiceImpl registeredService = .get(serviceType);
            return registeredService == null ? null : registeredService.getOpenListener();
        }
        public RegisteredServiceImpl getRegisteredService(final String serviceType) {
            return .get(serviceType);
        }
        public Connection getConnection() {
            return ;
        }
        public void remoteClosed() {
            .closeAsync();
        }
    }
    private final class ConnectionProviderContextImpl implements ConnectionProviderContext {
        private ConnectionProviderContextImpl() {
        }
        public void accept(final ConnectionHandlerFactory connectionHandlerFactory) {
            synchronized () {
                try {
                    resourceUntick("an inbound connection");
                } catch (NotOpenException e) {
                    throw new IllegalStateException("Accept after endpoint close"e);
                }
                boolean ok = false;
                try {
                    final ConnectionImpl connection = new ConnectionImpl(EndpointImpl.thisconnectionHandlerFactorythis);
                    .add(connection);
                    connection.getConnectionHandler().addCloseHandler(SpiUtils.asyncClosingCloseHandler(connection));
                    connection.addCloseHandler();
                    connection.addCloseHandler();
                    ok = true;
                } finally {
                    if (! okcloseTick1("a failed inbound connection");
                }
            }
        }
        public Endpoint getEndpoint() {
            return EndpointImpl.this;
        }
        public Xnio getXnio() {
            return ;
        }
        public Executor getExecutor() {
            return ;
        }
        public XnioWorker getXnioWorker() {
            return ;
        }
    }
    private class ConnectionCloseHandler implements CloseHandler<Connection> {
        public void handleClose(final Connection closedfinal IOException exception) {
            .remove(closed);
        }
    }
    private static class RegisteredServiceImpl implements RegisteredService {
        private final OpenListener openListener;
        private final OptionMap optionMap;
        private RegisteredServiceImpl(final OpenListener openListenerfinal OptionMap optionMap) {
            this. = openListener;
            this. = optionMap;
        }
        public OpenListener getOpenListener() {
            return ;
        }
        public OptionMap getOptionMap() {
            return ;
        }
    }
New to GrepCode? Check out our FAQ X