org.wso2.msf4j.Request Java Examples

The following examples show how to use org.wso2.msf4j.Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExchangesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{name}/permissions/owner/")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Change the owner of the exchange", notes = "", response = Void.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
    @ApiResponse(code = 204, message = "Exchange owner updated.", response = Void.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
    @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response changeExchangeOwner(@Context Request request, @PathParam("name") @ApiParam("Name of the exchange") String name,
                                    @Valid ChangeOwnerRequest changeOwnerRequest) {
    return grantApiDelegate.changeOwner(ResourceType.EXCHANGE, name, changeOwnerRequest.getOwner(),
                                        (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
}
 
Example #2
Source File: QueuesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{queueName}/permissions/actions/{action}/groups/{groupName}")
@Produces({ "application/json" })
@ApiOperation(value = "Remove permission to an action from a user group for a queue.", notes = "Revoke permissions for a user group from invoking a particular action on a specific queue.", response = ResponseMessage.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "User group removed.", response = ResponseMessage.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
    @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response deleteUserGroup(@Context Request request, @PathParam("queueName") @ApiParam("Name of the queue.") String queueName,@PathParam("action") @ApiParam("Name of the action.") String action,@PathParam("groupName") @ApiParam("Name of the user group") String groupName) {
    try {
        return authGrantApiDelegate.removeUserGroup(ResourceType.QUEUE, queueName, ResourceAction.getResourceAction(action), groupName,
                                                    (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example #3
Source File: BasicAuthSecurityInterceptor.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    String authHeader = request.getHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
    if (authHeader != null) {
        String authType = authHeader.substring(0, AUTH_TYPE_BASIC_LENGTH);
        String authEncoded = authHeader.substring(AUTH_TYPE_BASIC_LENGTH).trim();
        if (AUTH_TYPE_BASIC.equals(authType) && !authEncoded.isEmpty()) {

            // Read the Basic auth header and extract the username and password from base 64 encoded string.
            byte[] decodedByte = Base64.getDecoder().decode(authEncoded.getBytes(StandardCharsets.UTF_8));
            char[] array = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(decodedByte)).array();
            int separatorIndex = findIndex(array, ':');
            String userName = new String(Arrays.copyOfRange(array, 0, separatorIndex));
            char[] password = Arrays.copyOfRange(array, separatorIndex + 1, array.length);
            if (authenticate(userName, password)) {
                Subject subject = new Subject();
                subject.getPrincipals().add(new UsernamePrincipal(userName));
                request.getSession().setAttribute(BrokerAuthConstants.AUTHENTICATION_ID, subject);
                return true;
            }
        }
    }
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_BASIC);
    return false;
}
 
Example #4
Source File: ExchangesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{exchangeName}/permissions/actions/{action}/groups/{groupName}")
@Produces({ "application/json" })
@ApiOperation(value = "Remove permission to an action from a user group for an exchange.", notes = "Revoke permissions for a user group from invoking a particular action on a specific exchange.", response = ResponseMessage.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "User group removed.", response = ResponseMessage.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
    @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response deleteUserGroup(@Context Request request, @PathParam("exchangeName") @ApiParam("Name of the exchange.") String exchangeName,@PathParam("action") @ApiParam("Name of the action.") String action,@PathParam("groupName") @ApiParam("Name of the user group") String groupName) {
    try {
        return grantApiDelegate.removeUserGroup(ResourceType.EXCHANGE, exchangeName, ResourceAction.getResourceAction(action), groupName,
                                                (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example #5
Source File: ConnectionsApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{connectionId}/channels")
@Produces({ "application/json" })
@ApiOperation(value = "Get all channels for connection", notes = "Retrieves all AMQP channels established on an AMQP connection", response = ChannelMetadata.class, responseContainer = "List", authorizations = {
        @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "List of channels created on the connection", response = ChannelMetadata.class, responseContainer = "List"),
        @ApiResponse(code = 400, message = "Bad request. Invalid request or validation error.", response = Error.class),
        @ApiResponse(code = 401, message = "Authentication information is missing or invalid", response = Error.class),
        @ApiResponse(code = 403, message = "User is not autherized to perform operation", response = Error.class),
        @ApiResponse(code = 404, message = "The specified resource was not found", response = Error.class)
})
public Response getAllChannelsForConnection(@Context Request request,
                                            @PathParam("connectionId")
                                            @ApiParam("Identifier of the connection") Integer connectionId) {
    return connectionsApiDelegate.getAllChannels(connectionId, (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
}
 
Example #6
Source File: MSF4JHttpConnectorListener.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private void handleThrowable(MicroservicesRegistryImpl currentMicroservicesRegistry, Throwable throwable,
                             Request request) {
    Optional<ExceptionMapper> exceptionMapper = currentMicroservicesRegistry.getExceptionMapper(throwable);
    if (exceptionMapper.isPresent()) {
        org.wso2.msf4j.Response msf4jResponse = new org.wso2.msf4j.Response(request);
        msf4jResponse.setEntity(exceptionMapper.get().toResponse(throwable));
        msf4jResponse.send();
    } else {
        log.warn("Unmapped exception", throwable);
        try {
            HttpCarbonMessage response = HttpUtil.createTextResponse(
                    javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                    "Exception occurred :" + throwable.getMessage());
            response.setHeader("Content-type", "text/plain");
            response.addHttpContent(new DefaultLastHttpContent());
            request.respond(response);
        } catch (ServerConnectorException e) {
            log.error("Error while sending the response.", e);
        }
    }
}
 
Example #7
Source File: HTTPMonitoringInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preCall(Request request, Response responder, ServiceMethodInfo serviceMethodInfo) throws Exception {
    if (!enabled) {
        return true;
    }
    Method method = serviceMethodInfo.getMethod();
    MethodInterceptor methodInterceptor = map.get(method);
    if (methodInterceptor == null || !methodInterceptor.annotationScanned) {
        HTTPMonitored httpMon = extractFinalAnnotation(method);
        Interceptor interceptor = null;
        if (httpMon != null) {
            interceptor = new HTTPInterceptor(httpMon.tracing());
        }

        methodInterceptor = new MethodInterceptor(true, interceptor);
        map.put(method, methodInterceptor);
    }

    return methodInterceptor.preCall(request, responder, serviceMethodInfo);
}
 
Example #8
Source File: MSF4JTracingInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Intercepts the server response flow and extract response information
 * to be published to the DAS for tracing.
 */
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {
    long time = new Date().getTime();
    TraceEvent traceEvent = (TraceEvent) serviceMethodInfo.getAttribute(TRACE_EVENT_ATTRIBUTE);
    if (traceEvent != null) {
        TraceEvent endTraceEvent = new TraceEvent(
                TracingConstants.SERVER_TRACE_END,
                traceEvent.getTraceId(),
                traceEvent.getOriginId(),
                time
        );
        Response responder = (Response) serviceMethodInfo.getAttribute(RESPONDER_ATTRIBUTE);
        endTraceEvent.setStatusCode(responder.getStatusCode());
        TracingUtil.pushToDAS(endTraceEvent, dasUrl);
    }
}
 
Example #9
Source File: HttpMethodInfo.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Calls the http resource method.
 *
 * @param destination           matching Destinations for the route
 * @param request               original request
 * @param httpMethodInfo        http method information
 * @param microservicesRegistry micro-services registry
 * @throws Exception if error occurs while invoking the resource method
 */
public void invoke(PatternPathRouter.RoutableDestination<HttpResourceModel> destination, Request request,
                   HttpMethodInfo httpMethodInfo, MicroservicesRegistryImpl microservicesRegistry)
        throws Exception {
    request.setProperty(DECLARING_CLASS_LIST_CONSTANT, new ArrayList<Class<?>>());
    request.setProperty(RESOURCE_METHOD_LIST_CONSTANT, new ArrayList<Method>());
    ImmutablePair<Boolean, Object> returnVal =
            invokeResource(destination, httpMethodInfo, request, microservicesRegistry, false);

    // Execute method level interceptors of sub-resources and resources (first in - last out order)
    if (returnVal.getFirst()
            && InterceptorExecutor.executeMethodResponseInterceptorsForMethods(request, httpMethodInfo.responder,
            (ArrayList<Method>) request.getProperty(RESOURCE_METHOD_LIST_CONSTANT))
            // Execute class level interceptors of sub-resources and resources (first in - last out order)
            && InterceptorExecutor.executeClassResponseInterceptorsForClasses(request, httpMethodInfo.responder,
            (ArrayList<Class<?>>) request.getProperty(DECLARING_CLASS_LIST_CONSTANT))
            // Execute global interceptors
            && InterceptorExecutor.executeGlobalResponseInterceptors(microservicesRegistry, request,
            httpMethodInfo.responder)) {
        responder.setEntity(returnVal.getSecond());
    }
    responder.send();
}
 
Example #10
Source File: CustomJWTClaimsInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    HttpHeaders headers = request.getHeaders();
    if (headers != null) {
        String jwtHeader = headers.getHeaderString(JWT_HEADER);
        if (jwtHeader != null) {
            SignedJWT signedJWT = SignedJWT.parse(jwtHeader);
            ReadOnlyJWTClaimsSet readOnlyJWTClaimsSet = signedJWT.getJWTClaimsSet();
            if (readOnlyJWTClaimsSet != null) {
                // Do something with claims
                return true;
            }
        }
    }
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT);
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    return false;
}
 
Example #11
Source File: QueuesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{name}/permissions/owner/")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Change the owner of the queue", notes = "", response = ResponseMessage.class, authorizations = {
        @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
        @ApiResponse(code = 204, message = "Queue owner updated."),
        @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
        @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
        @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
        @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
        @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response changeQueueOwner(@Context Request request, @PathParam("name") @ApiParam("Name of the queue") String name,@Valid ChangeOwnerRequest changeOwnerRequest) {
    return authGrantApiDelegate.changeOwner(ResourceType.QUEUE, name, changeOwnerRequest.getOwner(),
                                            (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
}
 
Example #12
Source File: ScopesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/{name}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Update a scope", notes = "Update given scope", response = ScopeUpdateResponse.class, authorizations = {
    @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Scope updated", response = ScopeUpdateResponse.class),
    @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
    @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
    @ApiResponse(code = 404, message = "Scope key not found", response = Error.class),
    @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response updateScope(@Context Request request, @PathParam("name") @ApiParam("Name of the scope needs to update") String name, @Valid ScopeUpdateRequest body) {
    return Response.ok().entity("magic!").build();
}
 
Example #13
Source File: QueuesApi.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{name}/permissions/actions/{action}/groups")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@ApiOperation(value = "Add new user group(s) for a particular action on the queue.", notes = "Grant queue permission for new user group(s).", response = ResponseMessage.class, authorizations = {
        @Authorization(value = "basicAuth")
}, tags={  })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "User groups added.", response = ResponseMessage.class),
        @ApiResponse(code = 400, message = "Bad Request. Invalid request or validation error.", response = Error.class),
        @ApiResponse(code = 401, message = "Authentication Data is missing or invalid", response = Error.class),
        @ApiResponse(code = 403, message = "Requested action unauthorized.", response = Error.class),
        @ApiResponse(code = 409, message = "Duplicate resource", response = Error.class),
        @ApiResponse(code = 415, message = "Unsupported media type. The entity of the request was in a not supported format.", response = Error.class) })
public Response addQueueActionUserGroups(@Context Request request, @PathParam("name") @ApiParam("Name of the queue.") String name,@PathParam("action") @ApiParam("Name of the action.") String action,@Valid UserGroupList body) {
    try {
        return authGrantApiDelegate.addUserGroupsToAction(ResourceType.QUEUE, name, ResourceAction.getResourceAction(action), body,
                                                          (Subject) request.getSession().getAttribute(BrokerAuthConstants.AUTHENTICATION_ID));
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}
 
Example #14
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all stocks.
 * http://localhost:8080/stockquote/all
 *
 * @return All stocks will be sent to the client as Json/xml
 * according to the Accept header of the request.
 */
@GET
@Path("/all")
@Produces({"application/json", "text/xml"})
@ApiOperation(
        value = "Get all stocks",
        notes = "Returns all stock items",
        response = Stocks.class,
        responseContainer = "List")
public Stocks getAllStocks(@Context Request request) {
    request.getHeaders().getRequestHeaders().entrySet().forEach(entry -> System.out.println(entry.getKey() + "=" + entry
            .getValue()));
    return new Stocks(stockQuotes.values());
}
 
Example #15
Source File: RequestInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * This method will be called open request interception error (unhandled by end developer)
 * Override this method to manually handle exceptions when an unhandled error is thrown.
 *
 * @param request  MSF4J request.
 * @param response MSF4J Response.
 * @return should interception flow proceed?
 */
default boolean onRequestInterceptionError(Request request, Response response, Exception e) {
    String message = "Exception while executing request interceptor " + this.getClass();
    Logger log = LoggerFactory.getLogger(this.getClass());
    log.error(message, e);
    response.setEntity(message)
            .setMediaType(MediaType.TEXT_PLAIN)
            .setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    return false;
}
 
Example #16
Source File: InterceptorExecutor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Execute request interceptors annotated in class.
 *
 * @param request       {@link Request}
 * @param response      {@link Response}
 * @param resourceClass method declaring class
 * @return is request interceptors successful
 * @throws InterceptorException {@link InterceptorException} on interception exception
 */
public static boolean executeClassLevelRequestInterceptors(Request request, Response response,
                                                           Class<?> resourceClass) throws InterceptorException {
    Collection<Class<? extends RequestInterceptor>> classRequestInterceptorClasses =
            resourceClass.isAnnotationPresent(org.wso2.msf4j.interceptor.annotation.RequestInterceptor.class)
                    ? Arrays.asList(resourceClass
                    .getAnnotation(org.wso2.msf4j.interceptor.annotation.RequestInterceptor.class).value())
                    : new ArrayList<>();
    return executeNonGlobalRequestInterceptors(request, response, classRequestInterceptorClasses);
}
 
Example #17
Source File: JWTSecurityInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    log.info("Authentication precall");
    boolean isValidSignature;
    String jwtHeader = request.getHeader(JWT_HEADER);
    if (jwtHeader != null) {
        isValidSignature = verifySignature(jwtHeader);
        if (isValidSignature) {
            return true;
        }
    }
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT);
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    return false;
}
 
Example #18
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all stocks.
 * http://localhost:8080/stockquote/all
 *
 * @return All stocks will be sent to the client as Json/xml
 * according to the Accept header of the request.
 */
@GET
@Path("/all")
@Produces({"application/json", "text/xml"})
@ApiOperation(
        value = "Get all stocks",
        notes = "Returns all stock items",
        response = Stocks.class,
        responseContainer = "List")
public Stocks getAllStocks(@Context Request request) {
    request.getHeaders().getRequestHeaders().entrySet().forEach(entry -> log.info(entry.getKey() + "=" + entry
            .getValue()));
    return new Stocks(stockQuotes.values());
}
 
Example #19
Source File: TraceableHttpServerRequestTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws IOException {
    HttpCarbonMessage httpCarbonMessage = new HttpCarbonMessage(
            new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j"));
    httpCarbonMessage.setHeader("testK", "testV");
    httpCarbonMessage.setHttpMethod(HttpMethod.GET);
    request = new Request(httpCarbonMessage);
    request.setProperty("TO", "msf4j");
    httpServerRequest = new TraceableHttpServerRequest(request);
}
 
Example #20
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all stocks.
 * http://localhost:8080/stockquote/all
 *
 * @return All stocks will be sent to the client as Json/xml
 * according to the Accept header of the request.
 */
@GET
@Path("/all")
@Produces({"application/json", "text/xml"})
@ApiOperation(
        value = "Get all stocks",
        notes = "Returns all stock items",
        response = Stocks.class,
        responseContainer = "List")
public Stocks getAllStocks(@Context Request request) {
    return new Stocks(stockQuotes.values());
}
 
Example #21
Source File: InterceptorExecutor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Execute response interceptors annotated in method
 *
 * @param request  {@link Request}
 * @param response {@link Response}
 * @param method   method to be executed
 * @return is request interceptors successful
 * @throws InterceptorException {@link InterceptorException} on interception exception
 */
public static boolean executeMethodLevelResponseInterceptors(Request request, Response response, Method method)
        throws InterceptorException {
    List<Class<? extends ResponseInterceptor>> methodResponseInterceptorClasses =
            method.isAnnotationPresent(org.wso2.msf4j.interceptor.annotation.ResponseInterceptor.class)
                    ? Arrays.asList(method
                    .getAnnotation(org.wso2.msf4j.interceptor.annotation.ResponseInterceptor.class).value())
                    : new ArrayList<>();
    return executeNonGlobalResponseInterceptors(request, response, methodResponseInterceptorClasses);
}
 
Example #22
Source File: MetricsInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {
    if (interceptors != null) {
        for (Interceptor interceptor : interceptors) {
            interceptor.postCall(request, status, serviceMethodInfo);
        }
    }
}
 
Example #23
Source File: PropertyAddRequestInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    String propertyName = "SampleProperty";
    String property = "Sample Object";
    request.setProperty(propertyName, property);
    log.info("Property {} set to request", propertyName);
    return true;
}
 
Example #24
Source File: TestInterceptorDeprecated.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preCall(Request request, Response responder, ServiceMethodInfo serviceMethodInfo) throws Exception {
    preCallInterceptorCalls.incrementAndGet();
    PriorityDataHolder.setPriorityOrder(PriorityDataHolder.getPriorityOrder() + this.getClass().getSimpleName()
            + " - [PRE CALL]");
    return true;
}
 
Example #25
Source File: HTTPMonitoringInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) {
    HTTPMonitoringEvent httpMonitoringEvent =
            (HTTPMonitoringEvent) serviceMethodInfo.getAttribute(MONITORING_EVENT);
    httpMonitoringEvent.setResponseTime(
            TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - httpMonitoringEvent.getStartNanoTime()));
    httpMonitoringEvent.setResponseHttpStatusCode(status);
    httpMonitoringDataPublisher.publishEvent(httpMonitoringEvent);
}
 
Example #26
Source File: HTTPMonitoringInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private void handleTracing(Request request, HTTPMonitoringEvent httpMonitoringEvent) {
    String traceId, parentRequest;
    if (this.isTracing()) {
        traceId = request.getHeader(ACTIVITY_ID);
        if (traceId == null) {
            traceId = this.generateTraceId();
        }
        parentRequest = request.getHeader(PARENT_REQUEST);
    } else {
        traceId = DEFAULT_TRACE_ID;
        parentRequest = DEFAULT_PARENT_REQUEST;
    }
    httpMonitoringEvent.setActivityId(traceId);
    httpMonitoringEvent.setParentRequest(parentRequest);
}
 
Example #27
Source File: HTTPMonitoringInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preCall(Request request, Response responder, ServiceMethodInfo serviceMethodInfo)
        throws Exception {
    if (interceptor != null) {
        return interceptor.preCall(request, responder, serviceMethodInfo);
    }
    return true;
}
 
Example #28
Source File: HTTPMonitoringInterceptor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Override
public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {
    if (!enabled) {
        return;
    }
    Method method = serviceMethodInfo.getMethod();
    MethodInterceptor methodInterceptor = map.get(method);
    if (methodInterceptor != null) {
        methodInterceptor.postCall(request, status, serviceMethodInfo);
    }
}
 
Example #29
Source File: MSF4JHttpConnectorListener.java    From msf4j with Apache License 2.0 5 votes vote down vote up
private void handleHandlerException(HandlerException e, Request request) {
    try {
        HttpCarbonMessage failureResponse = e.getFailureResponse();
        failureResponse.addHttpContent(new DefaultLastHttpContent());
        request.respond(failureResponse);
    } catch (ServerConnectorException e1) {
        log.error("Error while sending the response.", e);
    }
}
 
Example #30
Source File: InterceptorExecutor.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * Execute response interceptors annotated in method for a list of methods.
 *
 * @param request  {@link Request}
 * @param response {@link Response}
 * @param methods  list of methods to be executed
 * @return is request interceptors successful
 * @throws InterceptorException {@link InterceptorException} on interception exception
 */
public static boolean executeMethodResponseInterceptorsForMethods(Request request, Response response,
                                                                  List<Method> methods)
        throws InterceptorException {
    if (methods == null) {
        return true;
    }
    for (Method resourceMethod : methods) {
        if (!(InterceptorExecutor.executeMethodLevelResponseInterceptors(request, response, resourceMethod))) {
            return false;
        }
    }
    return true;
}