Search in sources :

Example 6 with Message

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

the class AdminRESTInterceptor method getRequestBody.

@Mapping("/admin/rest/exchanges/(-?\\d+)/(response|request)/body")
public Response getRequestBody(QueryParameter params, String relativeRootPath) throws Exception {
    AbstractExchange exc = router.getExchangeStore().getExchangeById(params.getGroupInt(1));
    if (exc == null) {
        return Response.notFound().build();
    }
    Message msg = params.getGroup(2).equals("response") ? exc.getResponse() : exc.getRequest();
    String ct = params.getGroup(2).equals("response") ? exc.getResponseContentType() : exc.getRequestContentType();
    if (msg == null || msg.isBodyEmpty()) {
        return Response.noContent().build();
    }
    ResponseBuilder rb = Response.ok().contentType(ct).body(msg.getBodyAsStream(), false);
    String contentEncoding = msg.getHeader().getContentEncoding();
    if (contentEncoding != null)
        rb.header(Header.CONTENT_ENCODING, contentEncoding);
    return rb.build();
}
Also used : Message(com.predic8.membrane.core.http.Message) ResponseBuilder(com.predic8.membrane.core.http.Response.ResponseBuilder) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange)

Example 7 with Message

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

the class LoginDialog method handleLoginRequest.

public void handleLoginRequest(Exchange exc) throws Exception {
    Session s = sessionManager.getSession(exc);
    String uri = exc.getRequest().getUri().substring(path.length() - 1);
    if (uri.indexOf('?') >= 0)
        uri = uri.substring(0, uri.indexOf('?'));
    exc.getDestinations().set(0, uri);
    if (uri.equals("/logout")) {
        if (s != null)
            s.clear();
        exc.setResponse(Response.redirect(path, false).body("").build());
    } else if (uri.equals("/consent")) {
        if (exc.getRequest().getMethod().equals("POST"))
            processConsentPageResult(exc, s);
        else
            showConsentPage(exc, s);
    } else if (uri.equals("/")) {
        if (s == null || !s.isPreAuthorized()) {
            if (exc.getRequest().getMethod().equals("POST")) {
                Map<String, String> userAttributes;
                Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
                String username = params.get("username");
                if (username == null) {
                    showPage(exc, 0, "error", "INVALID_PASSWORD");
                    return;
                }
                if (accountBlocker != null && accountBlocker.isBlocked(username)) {
                    showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                    return;
                }
                try {
                    userAttributes = userDataProvider.verify(params);
                } catch (NoSuchElementException e) {
                    List<String> params2 = Lists.newArrayList("error", "INVALID_PASSWORD");
                    if (accountBlocker != null) {
                        if (accountBlocker.fail(username))
                            params2.addAll(Lists.newArrayList("accountBlocked", "true"));
                    }
                    showPage(exc, 0, params2.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (exposeUserCredentialsToSession) {
                    for (Map.Entry<String, String> param : params.entrySet()) if (!userAttributes.containsKey(param.getKey()))
                        userAttributes.put(param.getKey(), param.getValue());
                }
                if (tokenProvider != null)
                    showPage(exc, 1);
                else {
                    String target = params.get("target");
                    if (StringUtils.isEmpty(target))
                        target = "/";
                    exc.setResponse(Response.redirectWithout300(target).build());
                }
                Session session = sessionManager.getOrCreateSession(exc);
                session.preAuthorize(username, userAttributes);
                if (tokenProvider != null)
                    tokenProvider.requestToken(session.getUserAttributes());
            } else {
                showPage(exc, 0);
            }
        } else {
            if (accountBlocker != null && accountBlocker.isBlocked(s.getUserName())) {
                showPage(exc, 0, "error", "ACCOUNT_BLOCKED");
                return;
            }
            if (exc.getRequest().getMethod().equals("POST")) {
                String token = URLParamUtil.getParams(uriFactory, exc).get("token");
                try {
                    if (tokenProvider != null)
                        tokenProvider.verifyToken(s.getUserAttributes(), token);
                } catch (NoSuchElementException e) {
                    List<String> params = Lists.newArrayList("error", "INVALID_TOKEN");
                    if (accountBlocker != null)
                        if (accountBlocker.fail(s.getUserName()))
                            params.addAll(Lists.newArrayList("accountBlocked", "true"));
                    s.clear();
                    showPage(exc, 0, params.toArray());
                    return;
                } catch (Exception e) {
                    log.error("", e);
                    s.clear();
                    showPage(exc, 0, "error", "INTERNAL_SERVER_ERROR");
                    return;
                }
                if (accountBlocker != null)
                    accountBlocker.unblock(s.getUserName());
                String target = URLParamUtil.getParams(uriFactory, exc).get("target");
                if (StringUtils.isEmpty(target))
                    target = "/";
                if (this.message != null)
                    exc.setResponse(Response.redirectWithout300(target, message).build());
                else
                    exc.setResponse(Response.redirectWithout300(target).build());
                s.authorize();
            } else {
                showPage(exc, 1);
            }
        }
    } else {
        wsi.handleRequest(exc);
    }
}
Also used : ResolverMap(com.predic8.membrane.core.resolver.ResolverMap) ParseException(com.floreysoft.jmte.message.ParseException) MalformedURLException(java.net.MalformedURLException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Session(com.predic8.membrane.core.interceptor.authentication.session.SessionManager.Session)

Example 8 with Message

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

the class AMQuota method setResponseToServiceUnavailable.

private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
    // TODO do a better response here
    Header hd = new Header();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "Quota Exceeded");
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter)

Example 9 with Message

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

the class AMRateLimiter method setResponseToServiceUnavailable.

public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl) 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(prl.getInterval().toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = prl.getNextCleanup();
    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(prl.getRequests())
                .append(" requests per ")
                .append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
                .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "The rate limit of " + prl.getRequests() + " requests in " + prl.getInterval().getStandardSeconds() + " seconds is exceeded. The next requests can be made at " + dtFormatter.print(availableAgainDateTime));
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) DateTime(org.joda.time.DateTime)

Example 10 with Message

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

the class XMLContentFilter method removeMatchingElements.

/**
 * Removes parts of an XML document based on an XPath expression.
 *
 * If the message is not valid XML, it is left unchanged.
 */
public void removeMatchingElements(Message message) {
    try {
        Message xop = null;
        try {
            xop = xopReconstitutor.getReconstitutedMessage(message);
        } catch (ParseException e) {
        } catch (EndOfStreamException e) {
        } catch (FactoryConfigurationError e) {
        }
        if (elementFinder != null && !elementFinder.matches(xop != null ? xop.getBodyAsStream() : message.getBodyAsStream())) {
            return;
        }
        DocumentBuilder db = createDocumentBuilder();
        Document d;
        try {
            d = db.parse(xop != null ? xop.getBodyAsStream() : message.getBodyAsStream());
        } finally {
            db.reset();
        }
        removeElementsIfNecessary(message, xop, d);
    } catch (SAXException e) {
        return;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (XMLStreamException e) {
        return;
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (TransformerFactoryConfigurationError e) {
        throw new RuntimeException(e);
    }
}
Also used : TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) Message(com.predic8.membrane.core.http.Message) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XMLStreamException(javax.xml.stream.XMLStreamException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParseException(javax.mail.internet.ParseException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) TransformerException(javax.xml.transform.TransformerException)

Aggregations

Message (com.predic8.membrane.core.http.Message)9 Response (com.predic8.membrane.core.http.Response)7 IOException (java.io.IOException)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)5 JsonFactory (com.fasterxml.jackson.core.JsonFactory)4 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)4 Header (com.predic8.membrane.core.http.Header)4 Request (com.predic8.membrane.core.http.Request)4 Exchange (com.predic8.membrane.core.exchange.Exchange)2 Body (com.predic8.membrane.core.http.Body)2 HeaderField (com.predic8.membrane.core.http.HeaderField)2 ResponseBuilder (com.predic8.membrane.core.http.Response.ResponseBuilder)2 AbstractExchangeViewerListener (com.predic8.membrane.core.model.AbstractExchangeViewerListener)2 ResolverMap (com.predic8.membrane.core.resolver.ResolverMap)2 EndOfStreamException (com.predic8.membrane.core.util.EndOfStreamException)2 StringWriter (java.io.StringWriter)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)2 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)1