Search in sources :

Example 6 with Response

use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.

the class RateLimitInterceptor method setResponseToServiceUnavailable.

public void setResponseToServiceUnavailable(Exchange exc) throws UnsupportedEncodingException {
    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration", PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(rateLimitStrategy.requestLimit));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = rateLimitStrategy.getServiceAvailableAgainTime(ip);
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));
    StringBuilder bodyString = new StringBuilder();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    bodyString.append(ip).append(" exceeded the rate limit of ").append(rateLimitStrategy.requestLimit).append(" requests per ").append(PeriodFormat.getDefault().print(rateLimitStrategy.requestLimitDuration.toPeriod())).append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));
    Response resp = ResponseBuilder.newInstance().status(429, "Too Many Requests.").contentType(MimeType.TEXT_PLAIN_UTF8).header(hd).body(bodyString.toString()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) DateTime(org.joda.time.DateTime)

Example 7 with Response

use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.

the class RESTInterceptor method dispatchRequest.

private Outcome dispatchRequest(Exchange exc) throws Exception {
    String path = router.getUriFactory().create(exc.getDestinations().get(0)).getPath();
    for (Method m : getClass().getMethods()) {
        Mapping a = m.getAnnotation(Mapping.class);
        if (a == null)
            continue;
        Matcher matcher = Pattern.compile(a.value()).matcher(path);
        if (matcher.matches()) {
            Object[] parameters;
            switch(m.getParameterTypes().length) {
                case 2:
                    parameters = new Object[] { new QueryParameter(URLParamUtil.getParams(router.getUriFactory(), exc), matcher), getRelativeRootPath(path) };
                    break;
                case 3:
                    parameters = new Object[] { new QueryParameter(URLParamUtil.getParams(router.getUriFactory(), exc), matcher), getRelativeRootPath(path), exc };
                    break;
                default:
                    throw new InvalidParameterException("@Mapping is supposed to annotate a 2-parameter method.");
            }
            exc.setResponse((Response) m.invoke(this, parameters));
            return Outcome.RETURN;
        }
    }
    return Outcome.CONTINUE;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) Matcher(java.util.regex.Matcher) Mapping(com.predic8.membrane.core.interceptor.administration.Mapping) Method(java.lang.reflect.Method)

Example 8 with Response

use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.

the class REST2SOAPInterceptor method handleResponse.

@Override
public Outcome handleResponse(Exchange exc) throws Exception {
    Mapping mapping = getRESTURL(exc);
    log.debug("restURL: " + mapping);
    if (getRESTURL(exc) == null)
        return Outcome.CONTINUE;
    if (log.isDebugEnabled())
        log.debug("response: " + new String(getTransformer(null).transform(getBodySource(exc), exc.getStringProperties()), Constants.UTF_8_CHARSET));
    exc.getResponse().setBodyContent(getTransformer(mapping.responseXSLT).transform(getBodySource(exc)));
    Header header = exc.getResponse().getHeader();
    header.removeFields(Header.CONTENT_TYPE);
    header.setContentType(MimeType.TEXT_XML_UTF8);
    XML2HTTP.unwrapMessageIfNecessary(exc.getResponse());
    convertResponseToJSONIfNecessary(exc.getRequest().getHeader(), mapping, exc.getResponse(), exc.getStringProperties());
    return Outcome.CONTINUE;
}
Also used : Header(com.predic8.membrane.core.http.Header)

Example 9 with Response

use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.

the class DynamicRegistration method registerWithCallbackAt.

public Client registerWithCallbackAt(String callbackUri, String registrationEndpoint) throws Exception {
    Exchange exc = new Request.Builder().post(registrationEndpoint).header(Header.CONTENT_TYPE, MimeType.APPLICATION_JSON_UTF8).body(getRegistrationBody(callbackUri)).buildExchange();
    Response response = doRequest(exc);
    HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
    if (!json.containsKey("client_id") || !json.containsKey("client_secret"))
        throw new RuntimeException("Registration endpoint didn't return clientId/clientSecret");
    return new Client(json.get("client_id"), json.get("client_secret"), "");
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) Client(com.predic8.membrane.core.interceptor.oauth2.Client) HttpClient(com.predic8.membrane.core.transport.http.HttpClient)

Example 10 with Response

use of com.predic8.membrane.core.http.Response in project service-proxy by membrane.

the class WSDLInterceptorTest method setUp.

@Before
public void setUp() throws Exception {
    exc = new Exchange(new FakeHttpHandler(3011));
    exc.setRequest(MessageUtil.getGetRequest("/axis2/services/BLZService?wsdl"));
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/blz-service.wsdl");
    Response okResponse = Response.ok().contentType("text/xml; charset=utf-8").body(resourceAsStream, true).build();
    exc.setResponse(okResponse);
    exc.setOriginalHostHeader("thomas-bayer.com:80");
    interceptor = new WSDLInterceptor();
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) InputStream(java.io.InputStream) FakeHttpHandler(com.predic8.membrane.core.transport.http.FakeHttpHandler) Before(org.junit.Before)

Aggregations

Response (com.predic8.membrane.core.http.Response)29 Exchange (com.predic8.membrane.core.exchange.Exchange)14 IOException (java.io.IOException)14 StringWriter (java.io.StringWriter)9 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)7 Request (com.predic8.membrane.core.http.Request)7 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)6 Header (com.predic8.membrane.core.http.Header)6 Test (org.junit.Test)6 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)4 Message (com.predic8.membrane.core.http.Message)4 JSONContent (com.predic8.membrane.core.interceptor.rest.JSONContent)4 ProxyRule (com.predic8.membrane.core.rules.ProxyRule)4 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)4 SQLException (java.sql.SQLException)4 Element (org.w3c.dom.Element)4 NodeList (org.w3c.dom.NodeList)4 JsonFactory (com.fasterxml.jackson.core.JsonFactory)3 MCElement (com.predic8.membrane.annot.MCElement)3 ResponseBuilder (com.predic8.membrane.core.http.Response.ResponseBuilder)3