Search in sources :

Example 1 with Response

use of org.forgerock.http.protocol.Response in project OpenAM by OpenRock.

the class XMLResourceExceptionHandlerTest method testWrite.

@Test
public void testWrite() throws Exception {
    //given
    MessageContext context = mock(MessageContext.class);
    AuditTrail mockAudit = mock(AuditTrail.class);
    Response response = new Response();
    doReturn(mockAudit).when(context).getAuditTrail();
    doReturn(response).when(context).getResponse();
    String message = "I don't know where it is";
    ResourceException ex = new NotFoundException(message);
    AuthenticationException ex2 = new AuthenticationException(ex);
    //when
    handler.write(context, ex2);
    //then
    assertThat(response.getStatus()).isEqualTo(Status.NOT_FOUND);
    String text = response.getEntity().getString();
    assertThat(text).contains("<message>" + message + "</message>");
    assertThat(text).contains("<code>404</code>");
}
Also used : Response(org.forgerock.http.protocol.Response) AuthenticationException(org.forgerock.caf.authentication.api.AuthenticationException) NotFoundException(org.forgerock.json.resource.NotFoundException) ResourceException(org.forgerock.json.resource.ResourceException) MessageContext(org.forgerock.caf.authentication.api.MessageContext) AuditTrail(org.forgerock.caf.authentication.framework.AuditTrail) Test(org.testng.annotations.Test)

Example 2 with Response

use of org.forgerock.http.protocol.Response in project OpenAM by OpenRock.

the class CrestProtocolEnforcementFilterTest method requestWithIncorrectProtocolMajorVersionShouldReturnBadRequestResponse.

@Test
public void requestWithIncorrectProtocolMajorVersionShouldReturnBadRequestResponse() throws IOException {
    //Given
    Context context = mock(Context.class);
    Request request = new Request();
    Handler next = mock(Handler.class);
    request.getHeaders().put(AcceptApiVersionHeader.valueOf("protocol=2"));
    //When
    Response response = filter.filter(context, request, next).getOrThrowUninterruptibly();
    //Then
    assertThat(getUnsupportedMajorVersionExceptionJson(version(2))).isEqualTo(response.getEntity().getJson());
    assertThat(AcceptApiVersionHeader.valueOf(request).getProtocolVersion()).isEqualTo(version(2));
    verify(next, never()).handle(context, request);
}
Also used : Context(org.forgerock.services.context.Context) Response(org.forgerock.http.protocol.Response) Request(org.forgerock.http.protocol.Request) Handler(org.forgerock.http.Handler) Test(org.testng.annotations.Test)

Example 3 with Response

use of org.forgerock.http.protocol.Response in project OpenAM by OpenRock.

the class PendingRequestEmailTemplate method resolveScope.

private String resolveScope(String scope, Locale locale) {
    if (URI.create(scope).getScheme() != null) {
        Request request = new Request().setMethod("GET").setUri(URI.create(scope));
        request.getHeaders().put("Accept-Language", locale.toLanguageTag());
        Response response = client.send(request).getOrThrowUninterruptibly();
        if (Status.OK.equals(response.getStatus())) {
            try {
                JsonValue json = json(response.getEntity().getJson());
                if (json.isDefined("name") && json.get("name").isString()) {
                    return json.get("name").asString();
                }
            } catch (IOException e) {
                debug.warning("Failed to parse Scope description JSON", e);
            }
        }
    }
    return scope;
}
Also used : Response(org.forgerock.http.protocol.Response) Request(org.forgerock.http.protocol.Request) JsonValue(org.forgerock.json.JsonValue) IOException(java.io.IOException)

Example 4 with Response

use of org.forgerock.http.protocol.Response in project OpenAM by OpenRock.

the class XMLResourceExceptionHandler method write.

@Override
public void write(MessageContext context, AuthenticationException exception) {
    Reject.ifNull(exception);
    try {
        ResourceException jre;
        if (exception instanceof AuthenticationFailedException) {
            jre = new PermanentException(Status.UNAUTHORIZED.getCode(), exception.getMessage(), null);
        } else if (exception.getCause() instanceof ResourceException) {
            jre = (ResourceException) exception.getCause();
        } else {
            LOGGER.error(exception.getMessage(), exception);
            jre = new InternalServerErrorException("Authentication Failed", exception);
        }
        AuditTrail auditTrail = context.getAuditTrail();
        List<Map<String, Object>> failureReasonList = auditTrail.getFailureReasons();
        if (failureReasonList != null && !failureReasonList.isEmpty()) {
            jre.setDetail(json(object(field("failureReasons", failureReasonList))));
        }
        Response response = context.getResponse();
        response.setStatus(Status.valueOf(jre.getCode()));
        context.<Response>getResponse().getHeaders().put(ContentTypeHeader.valueOf(MediaType.XML_UTF_8.toString()));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Transformer transformer = XMLUtils.getTransformerFactory().newTransformer();
        transformer.transform(new DOMSource(asXMLDOM(jre.includeCauseInJsonValue().toJsonValue().asMap())), new StreamResult(outputStream));
        response.getEntity().setBytes(outputStream.toByteArray());
    } catch (TransformerException e1) {
        throw new IllegalStateException("Could not write XML to response", e1);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) AuthenticationFailedException(org.forgerock.caf.authentication.framework.AuthenticationFailedException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Response(org.forgerock.http.protocol.Response) PermanentException(org.forgerock.json.resource.PermanentException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ResourceException(org.forgerock.json.resource.ResourceException) AuditTrail(org.forgerock.caf.authentication.framework.AuditTrail) Map(java.util.Map) TransformerException(javax.xml.transform.TransformerException)

Example 5 with Response

use of org.forgerock.http.protocol.Response in project OpenAM by OpenRock.

the class Endpoints method from.

/**
     * Produce a {@code Handler} from the annotated methods on the provided object.
     * <p>
     * This method currently only distinguishes requests by their method type. In future this
     * should be extended to support selection by request and response media types, and request
     * path.
     * @param obj The object containing annotated methods.
     * @return A new {@code Handler}.
     */
public static Handler from(final Object obj) {
    final Map<String, AnnotatedMethod> methods = new HashMap<>();
    methods.put("DELETE", AnnotatedMethod.findMethod(obj, Delete.class));
    methods.put("GET", AnnotatedMethod.findMethod(obj, Get.class));
    methods.put("POST", AnnotatedMethod.findMethod(obj, Post.class));
    methods.put("PUT", AnnotatedMethod.findMethod(obj, Put.class));
    return new Handler() {

        @Override
        public Promise<Response, NeverThrowsException> handle(Context context, Request request) {
            AnnotatedMethod method = methods.get(getMethod(request));
            if (method == null) {
                Response response = new Response(Status.METHOD_NOT_ALLOWED);
                response.setEntity(new NotSupportedException().toJsonValue().getObject());
                return newResultPromise(response);
            }
            return method.invoke(context, request);
        }
    };
}
Also used : Context(org.forgerock.services.context.Context) HashMap(java.util.HashMap) Request(org.forgerock.http.protocol.Request) Handler(org.forgerock.http.Handler) Response(org.forgerock.http.protocol.Response) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Aggregations

Response (org.forgerock.http.protocol.Response)22 Request (org.forgerock.http.protocol.Request)15 Test (org.testng.annotations.Test)14 Context (org.forgerock.services.context.Context)8 JsonValue (org.forgerock.json.JsonValue)6 AttributesContext (org.forgerock.services.context.AttributesContext)6 RootContext (org.forgerock.services.context.RootContext)6 Handler (org.forgerock.http.Handler)4 ReadRequest (org.forgerock.json.resource.ReadRequest)4 ResourceResponse (org.forgerock.json.resource.ResourceResponse)4 RestAuthException (org.forgerock.openam.core.rest.authn.exceptions.RestAuthException)4 RestAuthResponseException (org.forgerock.openam.core.rest.authn.exceptions.RestAuthResponseException)4 NeverThrowsException (org.forgerock.util.promise.NeverThrowsException)4 Map (java.util.Map)3 UriRouterContext (org.forgerock.http.routing.UriRouterContext)3 SessionContext (org.forgerock.http.session.SessionContext)3 ActionRequest (org.forgerock.json.resource.ActionRequest)3 ActionResponse (org.forgerock.json.resource.ActionResponse)3 CreateRequest (org.forgerock.json.resource.CreateRequest)3 DeleteRequest (org.forgerock.json.resource.DeleteRequest)3