Search in sources :

Example 1 with InstanceHandle

use of io.undertow.servlet.api.InstanceHandle in project undertow by undertow-io.

the class Encoding method encodeText.

public String encodeText(final Object o) throws EncodeException {
    List<InstanceHandle<? extends Encoder>> encoders = textEncoders.get(o.getClass());
    if (encoders == null) {
        for (Map.Entry<Class<?>, List<InstanceHandle<? extends Encoder>>> entry : textEncoders.entrySet()) {
            if (entry.getKey().isAssignableFrom(o.getClass())) {
                encoders = entry.getValue();
                break;
            }
        }
    }
    if (encoders != null) {
        for (InstanceHandle<? extends Encoder> decoderHandle : encoders) {
            Encoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Encoder.Text) {
                return ((Encoder.Text) decoder).encode(o);
            } else {
                try {
                    StringWriter out = new StringWriter();
                    ((Encoder.TextStream) decoder).encode(o, out);
                    return out.toString();
                } catch (IOException e) {
                    throw new EncodeException(o, "Could not encode text", e);
                }
            }
        }
    }
    if (EncodingFactory.isPrimitiveOrBoxed(o.getClass())) {
        return o.toString();
    }
    throw new EncodeException(o, "Could not encode text");
}
Also used : EncodeException(javax.websocket.EncodeException) IOException(java.io.IOException) StringWriter(java.io.StringWriter) Encoder(javax.websocket.Encoder) List(java.util.List) InstanceHandle(io.undertow.servlet.api.InstanceHandle) Map(java.util.Map)

Example 2 with InstanceHandle

use of io.undertow.servlet.api.InstanceHandle in project undertow by undertow-io.

the class Encoding method encodeBinary.

public ByteBuffer encodeBinary(final Object o) throws EncodeException {
    List<InstanceHandle<? extends Encoder>> encoders = binaryEncoders.get(o.getClass());
    if (encoders == null) {
        for (Map.Entry<Class<?>, List<InstanceHandle<? extends Encoder>>> entry : binaryEncoders.entrySet()) {
            if (entry.getKey().isAssignableFrom(o.getClass())) {
                encoders = entry.getValue();
                break;
            }
        }
    }
    if (encoders != null) {
        for (InstanceHandle<? extends Encoder> decoderHandle : encoders) {
            Encoder decoder = decoderHandle.getInstance();
            if (decoder instanceof Encoder.Binary) {
                return ((Encoder.Binary) decoder).encode(o);
            } else {
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ((Encoder.BinaryStream) decoder).encode(o, out);
                    return ByteBuffer.wrap(out.toByteArray());
                } catch (IOException e) {
                    throw new EncodeException(o, "Could not encode binary", e);
                }
            }
        }
    }
    throw new EncodeException(o, "Could not encode binary");
}
Also used : EncodeException(javax.websocket.EncodeException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Encoder(javax.websocket.Encoder) List(java.util.List) InstanceHandle(io.undertow.servlet.api.InstanceHandle) Map(java.util.Map)

Example 3 with InstanceHandle

use of io.undertow.servlet.api.InstanceHandle in project undertow by undertow-io.

the class EndpointSessionHandler method onConnect.

@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    ConfiguredServerEndpoint config = HandshakeUtil.getConfig(channel);
    try {
        if (container.isClosed()) {
            // if the underlying container is closed we just reject
            channel.sendClose();
            channel.resumeReceives();
            return;
        }
        InstanceFactory<?> endpointFactory = config.getEndpointFactory();
        ServerEndpointConfig.Configurator configurator = config.getEndpointConfiguration().getConfigurator();
        final InstanceHandle<?> instance;
        DefaultContainerConfigurator.setCurrentInstanceFactory(endpointFactory);
        final Object instanceFromConfigurator = configurator.getEndpointInstance(config.getEndpointConfiguration().getEndpointClass());
        final InstanceHandle<?> factoryInstance = DefaultContainerConfigurator.clearCurrentInstanceFactory();
        if (factoryInstance == null) {
            instance = new ImmediateInstanceHandle<>(instanceFromConfigurator);
        } else if (factoryInstance.getInstance() == instanceFromConfigurator) {
            instance = factoryInstance;
        } else {
            // the default instance has been wrapped
            instance = new InstanceHandle<Object>() {

                @Override
                public Object getInstance() {
                    return instanceFromConfigurator;
                }

                @Override
                public void release() {
                    factoryInstance.release();
                }
            };
        }
        ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        Principal principal = exchange.getAttachment(HandshakeUtil.PRINCIPAL);
        if (principal == null) {
            if (src.getServletRequest() instanceof HttpServletRequest) {
                principal = ((HttpServletRequest) src.getServletRequest()).getUserPrincipal();
            } else {
                principal = src.getOriginalRequest().getUserPrincipal();
            }
        }
        final InstanceHandle<Endpoint> endpointInstance;
        if (config.getAnnotatedEndpointFactory() != null) {
            final AnnotatedEndpoint annotated = config.getAnnotatedEndpointFactory().createInstance(instance);
            endpointInstance = new InstanceHandle<Endpoint>() {

                @Override
                public Endpoint getInstance() {
                    return annotated;
                }

                @Override
                public void release() {
                    instance.release();
                }
            };
        } else {
            endpointInstance = (InstanceHandle<Endpoint>) instance;
        }
        UndertowSession session = new UndertowSession(channel, URI.create(exchange.getRequestURI()), exchange.getAttachment(HandshakeUtil.PATH_PARAMS), exchange.getRequestParameters(), this, principal, endpointInstance, config.getEndpointConfiguration(), exchange.getQueryString(), config.getEncodingFactory().createEncoding(config.getEndpointConfiguration()), config, channel.getSubProtocol(), Collections.<Extension>emptyList(), null);
        config.addOpenSession(session);
        session.setMaxBinaryMessageBufferSize(getContainer().getDefaultMaxBinaryMessageBufferSize());
        session.setMaxTextMessageBufferSize(getContainer().getDefaultMaxTextMessageBufferSize());
        session.setMaxIdleTimeout(getContainer().getDefaultMaxSessionIdleTimeout());
        session.getAsyncRemote().setSendTimeout(getContainer().getDefaultAsyncSendTimeout());
        try {
            endpointInstance.getInstance().onOpen(session, config.getEndpointConfiguration());
        } catch (Exception e) {
            endpointInstance.getInstance().onError(session, e);
            IoUtils.safeClose(session);
        }
        channel.resumeReceives();
    } catch (Exception e) {
        JsrWebSocketLogger.REQUEST_LOGGER.endpointCreationFailed(e);
        IoUtils.safeClose(channel);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) Principal(java.security.Principal)

Example 4 with InstanceHandle

use of io.undertow.servlet.api.InstanceHandle in project undertow by undertow-io.

the class ServerSentEventSCI method onStartup.

@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    if (c == null || c.isEmpty()) {
        return;
    }
    try {
        final Map<String, ServerSentEventConnectionCallback> callbacks = new HashMap<>();
        ServletContextImpl servletContext = (ServletContextImpl) ctx;
        final List<InstanceHandle<?>> handles = new ArrayList<>();
        for (Class<?> clazz : c) {
            final ServerSentEvent annotation = clazz.getAnnotation(ServerSentEvent.class);
            if (annotation == null) {
                continue;
            }
            String path = annotation.value();
            final InstanceHandle<?> instance = servletContext.getDeployment().getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance();
            handles.add(instance);
            callbacks.put(path, (ServerSentEventConnectionCallback) instance.getInstance());
        }
        if (callbacks.isEmpty()) {
            return;
        }
        servletContext.getDeployment().getDeploymentInfo().addInnerHandlerChainWrapper(new HandlerWrapper() {

            @Override
            public HttpHandler wrap(HttpHandler handler) {
                PathTemplateHandler pathTemplateHandler = new PathTemplateHandler(handler, false);
                for (Map.Entry<String, ServerSentEventConnectionCallback> e : callbacks.entrySet()) {
                    pathTemplateHandler.add(e.getKey(), new ServerSentEventHandler(e.getValue()));
                }
                return pathTemplateHandler;
            }
        });
        servletContext.addListener(new ServletContextListener() {

            @Override
            public void contextInitialized(ServletContextEvent sce) {
            }

            @Override
            public void contextDestroyed(ServletContextEvent sce) {
                for (InstanceHandle<?> h : handles) {
                    h.release();
                }
            }
        });
    } catch (Exception e) {
        throw new ServletException(e);
    }
}
Also used : HttpHandler(io.undertow.server.HttpHandler) HashMap(java.util.HashMap) ServletContextListener(javax.servlet.ServletContextListener) ServerSentEventConnectionCallback(io.undertow.server.handlers.sse.ServerSentEventConnectionCallback) PathTemplateHandler(io.undertow.server.handlers.PathTemplateHandler) ServletContextImpl(io.undertow.servlet.spec.ServletContextImpl) ArrayList(java.util.ArrayList) ServerSentEventHandler(io.undertow.server.handlers.sse.ServerSentEventHandler) HandlerWrapper(io.undertow.server.HandlerWrapper) ServletException(javax.servlet.ServletException) ServletException(javax.servlet.ServletException) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ServletContextEvent(javax.servlet.ServletContextEvent)

Aggregations

InstanceHandle (io.undertow.servlet.api.InstanceHandle)4 IOException (java.io.IOException)2 List (java.util.List)2 Map (java.util.Map)2 EncodeException (javax.websocket.EncodeException)2 Encoder (javax.websocket.Encoder)2 HandlerWrapper (io.undertow.server.HandlerWrapper)1 HttpHandler (io.undertow.server.HttpHandler)1 PathTemplateHandler (io.undertow.server.handlers.PathTemplateHandler)1 ServerSentEventConnectionCallback (io.undertow.server.handlers.sse.ServerSentEventConnectionCallback)1 ServerSentEventHandler (io.undertow.server.handlers.sse.ServerSentEventHandler)1 ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)1 ServletContextImpl (io.undertow.servlet.spec.ServletContextImpl)1 ImmediateInstanceHandle (io.undertow.servlet.util.ImmediateInstanceHandle)1 AnnotatedEndpoint (io.undertow.websockets.jsr.annotated.AnnotatedEndpoint)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 StringWriter (java.io.StringWriter)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1