Search in sources :

Example 1 with MethodExecutionHandle

use of io.micronaut.inject.MethodExecutionHandle in project micronaut-core by micronaut-projects.

the class AbstractNettyWebSocketHandler method callOpenMethod.

/**
 * Calls the open method of the websocket bean.
 *
 * @param ctx THe handler context
 */
protected void callOpenMethod(ChannelHandlerContext ctx) {
    if (session == null) {
        return;
    }
    Optional<? extends MethodExecutionHandle<?, ?>> executionHandle = webSocketBean.openMethod();
    if (executionHandle.isPresent()) {
        MethodExecutionHandle<?, ?> openMethod = executionHandle.get();
        BoundExecutable boundExecutable = null;
        try {
            boundExecutable = bindMethod(originatingRequest, webSocketBinder, openMethod, Collections.emptyList());
        } catch (Throwable e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Error Binding method @OnOpen for WebSocket [" + webSocketBean + "]: " + e.getMessage(), e);
            }
            if (session.isOpen()) {
                session.close(CloseReason.INTERNAL_ERROR);
            }
        }
        if (boundExecutable != null) {
            try {
                BoundExecutable finalBoundExecutable = boundExecutable;
                Object result = invokeExecutable(finalBoundExecutable, openMethod);
                if (Publishers.isConvertibleToPublisher(result)) {
                    Flux<?> flowable = Flux.from(instrumentPublisher(ctx, result));
                    flowable.subscribe(o -> {
                    }, error -> {
                        if (LOG.isErrorEnabled()) {
                            LOG.error("Error Opening WebSocket [" + webSocketBean + "]: " + error.getMessage(), error);
                        }
                        if (session.isOpen()) {
                            session.close(CloseReason.INTERNAL_ERROR);
                        }
                    }, () -> {
                    });
                }
            } catch (Throwable e) {
                forwardErrorToUser(ctx, t -> {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error Opening WebSocket [" + webSocketBean + "]: " + t.getMessage(), t);
                    }
                }, e);
                // since we failed to call onOpen, we should always close here
                if (session.isOpen()) {
                    session.close(CloseReason.INTERNAL_ERROR);
                }
            }
        }
    }
}
Also used : Publishers(io.micronaut.core.async.publisher.Publishers) ArgumentBinderRegistry(io.micronaut.core.bind.ArgumentBinderRegistry) LoggerFactory(org.slf4j.LoggerFactory) Internal(io.micronaut.core.annotation.Internal) UnsatisfiedArgumentException(io.micronaut.core.bind.exceptions.UnsatisfiedArgumentException) CloseReason(io.micronaut.websocket.CloseReason) MediaType(io.micronaut.http.MediaType) Map(java.util.Map) RequestBinderRegistry(io.micronaut.http.bind.RequestBinderRegistry) DefaultExecutableBinder(io.micronaut.core.bind.DefaultExecutableBinder) CodecException(io.micronaut.http.codec.CodecException) ContinuationWebSocketFrame(io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame) WebSocketState(io.micronaut.websocket.bind.WebSocketState) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) List(java.util.List) Optional(java.util.Optional) NettyByteBufferFactory(io.micronaut.buffer.netty.NettyByteBufferFactory) WebSocketBean(io.micronaut.websocket.context.WebSocketBean) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutableMethod(io.micronaut.inject.ExecutableMethod) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) WebSocketVersion(io.netty.handler.codec.http.websocketx.WebSocketVersion) ExecutableBinder(io.micronaut.core.bind.ExecutableBinder) ByteBuf(io.netty.buffer.ByteBuf) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) Schedulers(reactor.core.scheduler.Schedulers) CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) Argument(io.micronaut.core.type.Argument) HttpRequest(io.micronaut.http.HttpRequest) BoundExecutable(io.micronaut.core.bind.BoundExecutable) ConversionService(io.micronaut.core.convert.ConversionService) MediaTypeCodecRegistry(io.micronaut.http.codec.MediaTypeCodecRegistry) Logger(org.slf4j.Logger) WebSocketFrame(io.netty.handler.codec.http.websocketx.WebSocketFrame) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle) Channel(io.netty.channel.Channel) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) WebSocketStateBinderRegistry(io.micronaut.websocket.bind.WebSocketStateBinderRegistry) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Consumes(io.micronaut.http.annotation.Consumes) WebSocketPongMessage(io.micronaut.websocket.WebSocketPongMessage) Collections(java.util.Collections) BoundExecutable(io.micronaut.core.bind.BoundExecutable)

Example 2 with MethodExecutionHandle

use of io.micronaut.inject.MethodExecutionHandle in project micronaut-core by micronaut-projects.

the class DefaultRouteBuilder method error.

@Override
public ErrorRoute error(Class originatingClass, Class<? extends Throwable> error, Class type, String method, Class[] parameterTypes) {
    Optional<MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
    MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() -> new RoutingException("No such route: " + type.getName() + "." + method));
    DefaultErrorRoute errorRoute = new DefaultErrorRoute(originatingClass, error, executableHandle, conversionService);
    this.errorRoutes.add(errorRoute);
    return errorRoute;
}
Also used : RoutingException(io.micronaut.web.router.exceptions.RoutingException) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle)

Example 3 with MethodExecutionHandle

use of io.micronaut.inject.MethodExecutionHandle in project micronaut-core by micronaut-projects.

the class TraceInterceptor method intercept.

@Override
public Object intercept(InvocationContext context) {
    if (LOG.isTraceEnabled() && context instanceof MethodExecutionHandle) {
        MethodExecutionHandle handle = (MethodExecutionHandle) context;
        Collection<MutableArgumentValue<?>> values = context.getParameters().values();
        LOG.trace("Invoking method {}#{}(..) with arguments {}", context.getTarget().getClass().getName(), handle.getMethodName(), values.stream().map(ArgumentValue::getValue).collect(Collectors.toList()));
    }
    Object result = context.proceed();
    if (LOG.isTraceEnabled() && context instanceof MethodExecutionHandle) {
        MethodExecutionHandle handle = (MethodExecutionHandle) context;
        LOG.trace("Method {}#{}(..) returned result {}", context.getTarget().getClass().getName(), handle.getMethodName(), result);
    }
    return result;
}
Also used : MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle) MutableArgumentValue(io.micronaut.core.type.MutableArgumentValue) ArgumentValue(io.micronaut.core.type.ArgumentValue) MutableArgumentValue(io.micronaut.core.type.MutableArgumentValue)

Example 4 with MethodExecutionHandle

use of io.micronaut.inject.MethodExecutionHandle in project micronaut-core by micronaut-projects.

the class DefaultRouteBuilder method status.

@Override
public StatusRoute status(Class originatingClass, HttpStatus status, Class type, String method, Class[] parameterTypes) {
    Optional<MethodExecutionHandle<?, Object>> executionHandle = executionHandleLocator.findExecutionHandle(type, method, parameterTypes);
    MethodExecutionHandle<?, Object> executableHandle = executionHandle.orElseThrow(() -> new RoutingException("No such route: " + type.getName() + "." + method));
    DefaultStatusRoute statusRoute = new DefaultStatusRoute(originatingClass, status, executableHandle, conversionService);
    this.statusRoutes.add(statusRoute);
    return statusRoute;
}
Also used : RoutingException(io.micronaut.web.router.exceptions.RoutingException) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle)

Example 5 with MethodExecutionHandle

use of io.micronaut.inject.MethodExecutionHandle in project micronaut-core by micronaut-projects.

the class HttpSessionFilter method encodeSessionId.

private Publisher<MutableHttpResponse<?>> encodeSessionId(HttpRequest<?> request, Publisher<MutableHttpResponse<?>> responsePublisher) {
    Flux<SessionAndResponse> responseFlowable = Flux.from(responsePublisher).switchMap(response -> {
        Optional<MethodExecutionHandle> routeMatch = request.getAttribute(HttpAttributes.ROUTE_MATCH, MethodExecutionHandle.class);
        Optional<?> body = response.getBody();
        String sessionAttr;
        if (body.isPresent()) {
            sessionAttr = routeMatch.flatMap(m -> {
                if (!m.hasAnnotation(SessionValue.class)) {
                    return Optional.empty();
                } else {
                    String attributeName = m.stringValue(SessionValue.class).orElse(null);
                    if (!StringUtils.isEmpty(attributeName)) {
                        return Optional.of(attributeName);
                    } else {
                        throw new InternalServerException("@SessionValue on a return type must specify an attribute name");
                    }
                }
            }).orElse(null);
        } else {
            sessionAttr = null;
        }
        Optional<Session> opt = request.getAttributes().get(SESSION_ATTRIBUTE, Session.class);
        if (opt.isPresent()) {
            Session session = opt.get();
            if (sessionAttr != null) {
                session.put(sessionAttr, body.get());
            }
            if (session.isNew() || session.isModified()) {
                return Flux.from(Publishers.fromCompletableFuture(() -> sessionStore.save(session))).map(s -> new SessionAndResponse(Optional.of(s), response));
            }
        } else if (sessionAttr != null) {
            Session newSession = sessionStore.newSession();
            newSession.put(sessionAttr, body.get());
            return Flux.from(Publishers.fromCompletableFuture(() -> sessionStore.save(newSession))).map(s -> new SessionAndResponse(Optional.of(s), response));
        }
        return Flux.just(new SessionAndResponse(opt, response));
    });
    return responseFlowable.map(sessionAndResponse -> {
        Optional<Session> session = sessionAndResponse.session;
        MutableHttpResponse<?> response = sessionAndResponse.response;
        if (session.isPresent()) {
            Session s = session.get();
            for (HttpSessionIdEncoder encoder : encoders) {
                encoder.encodeId(request, response, s);
            }
        }
        return response;
    });
}
Also used : Filter(io.micronaut.http.annotation.Filter) Publishers(io.micronaut.core.async.publisher.Publishers) ServerFilterChain(io.micronaut.http.filter.ServerFilterChain) Publisher(org.reactivestreams.Publisher) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) SessionValue(io.micronaut.session.annotation.SessionValue) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle) StringUtils(io.micronaut.core.util.StringUtils) Flux(reactor.core.publisher.Flux) Session(io.micronaut.session.Session) List(java.util.List) CollectionUtils(io.micronaut.core.util.CollectionUtils) SessionStore(io.micronaut.session.SessionStore) HttpServerFilter(io.micronaut.http.filter.HttpServerFilter) InternalServerException(io.micronaut.http.server.exceptions.InternalServerException) Optional(java.util.Optional) HttpAttributes(io.micronaut.http.HttpAttributes) HttpRequest(io.micronaut.http.HttpRequest) ServerFilterPhase(io.micronaut.http.filter.ServerFilterPhase) InternalServerException(io.micronaut.http.server.exceptions.InternalServerException) SessionValue(io.micronaut.session.annotation.SessionValue) MethodExecutionHandle(io.micronaut.inject.MethodExecutionHandle) Session(io.micronaut.session.Session)

Aggregations

MethodExecutionHandle (io.micronaut.inject.MethodExecutionHandle)6 Publishers (io.micronaut.core.async.publisher.Publishers)2 Argument (io.micronaut.core.type.Argument)2 HttpRequest (io.micronaut.http.HttpRequest)2 ExecutableMethod (io.micronaut.inject.ExecutableMethod)2 RoutingException (io.micronaut.web.router.exceptions.RoutingException)2 NettyByteBufferFactory (io.micronaut.buffer.netty.NettyByteBufferFactory)1 Internal (io.micronaut.core.annotation.Internal)1 ArgumentBinderRegistry (io.micronaut.core.bind.ArgumentBinderRegistry)1 BoundExecutable (io.micronaut.core.bind.BoundExecutable)1 DefaultExecutableBinder (io.micronaut.core.bind.DefaultExecutableBinder)1 ExecutableBinder (io.micronaut.core.bind.ExecutableBinder)1 UnsatisfiedArgumentException (io.micronaut.core.bind.exceptions.UnsatisfiedArgumentException)1 ConversionService (io.micronaut.core.convert.ConversionService)1 ArgumentValue (io.micronaut.core.type.ArgumentValue)1 MutableArgumentValue (io.micronaut.core.type.MutableArgumentValue)1 CollectionUtils (io.micronaut.core.util.CollectionUtils)1 StringUtils (io.micronaut.core.util.StringUtils)1 HttpAttributes (io.micronaut.http.HttpAttributes)1 MediaType (io.micronaut.http.MediaType)1