Search in sources :

Example 41 with Body

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

the class XML2HTTP method unwrapMessageIfNecessary.

/**
 * Checks, if the response contains an XML doc with NS {@link Constants#HTTP_NS}.
 * If it does, the HTTP data (uri, method, status, headers, body) is extracted from the doc
 * and set as the response.
 *
 * Reverse of {@link com.predic8.membrane.core.http.xml.Request#write(XMLStreamWriter)} and
 * {@link com.predic8.membrane.core.http.xml.Response#write(XMLStreamWriter)}.
 */
public static void unwrapMessageIfNecessary(Message message) {
    if (MimeType.TEXT_XML_UTF8.equals(message.getHeader().getContentType())) {
        try {
            if (message.getBody().getLength() == 0)
                return;
            XMLEventReader parser;
            synchronized (xmlInputFactory) {
                parser = xmlInputFactory.createXMLEventReader(message.getBodyAsStreamDecoded(), message.getCharset());
            }
            /* States:
				 * 0 = before root element,
				 * 1 = root element has HTTP_NS namespace
				 */
            int state = 0;
            boolean keepSourceHeaders = false, foundHeaders = false, foundBody = false;
            while (parser.hasNext()) {
                XMLEvent event = parser.nextEvent();
                switch(state) {
                    case 0:
                        if (event.isStartElement()) {
                            QName name = event.asStartElement().getName();
                            if (Constants.HTTP_NS.equals(name.getNamespaceURI())) {
                                state = 1;
                                if ("request".equals(name.getLocalPart())) {
                                    Request req = (Request) message;
                                    req.setMethod(requireAttribute(event.asStartElement(), "method"));
                                    String httpVersion = getAttribute(event.asStartElement(), "http-version");
                                    if (httpVersion == null)
                                        httpVersion = "1.1";
                                    req.setVersion(httpVersion);
                                }
                            } else {
                                return;
                            }
                        }
                        break;
                    case 1:
                        if (event.isStartElement()) {
                            String localName = event.asStartElement().getName().getLocalPart();
                            if ("status".equals(localName)) {
                                Response res = (Response) message;
                                res.setStatusCode(Integer.parseInt(requireAttribute(event.asStartElement(), "code")));
                                res.setStatusMessage(slurpCharacterData(parser, event.asStartElement()));
                            }
                            if ("uri".equals(localName)) {
                                Request req = (Request) message;
                                req.setUri(requireAttribute(event.asStartElement(), "value"));
                                // uri/... (port,host,path,query) structure is ignored, as value already contains everything
                                slurpXMLData(parser, event.asStartElement());
                            }
                            if ("headers".equals(localName)) {
                                foundHeaders = true;
                                keepSourceHeaders = "true".equals(getAttribute(event.asStartElement(), "keepSourceHeaders"));
                            }
                            if ("header".equals(localName)) {
                                String key = requireAttribute(event.asStartElement(), "name");
                                boolean remove = getAttribute(event.asStartElement(), "remove") != null;
                                if (remove && !keepSourceHeaders)
                                    throw new XML2HTTPException("<headers keepSourceHeaders=\"false\"><header name=\"...\" remove=\"true\"> does not make sense.");
                                message.getHeader().removeFields(key);
                                if (!remove)
                                    message.getHeader().add(key, slurpCharacterData(parser, event.asStartElement()));
                            }
                            if ("body".equals(localName)) {
                                foundBody = true;
                                String type = requireAttribute(event.asStartElement(), "type");
                                if ("plain".equals(type)) {
                                    message.setBodyContent(slurpCharacterData(parser, event.asStartElement()).getBytes(Constants.UTF_8_CHARSET));
                                } else if ("xml".equals(type)) {
                                    message.setBodyContent(slurpXMLData(parser, event.asStartElement()).getBytes(Constants.UTF_8_CHARSET));
                                } else {
                                    throw new XML2HTTPException("XML-HTTP doc body type '" + type + "' is not supported (only 'plain' or 'xml').");
                                }
                            }
                        }
                        break;
                }
            }
            if (!foundHeaders && !keepSourceHeaders)
                message.getHeader().clear();
            if (!foundBody)
                message.setBodyContent(new byte[0]);
        } catch (XMLStreamException e) {
            log.error("", e);
        } catch (XML2HTTPException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
    }
}
Also used : Response(com.predic8.membrane.core.http.Response) XMLStreamException(javax.xml.stream.XMLStreamException) QName(javax.xml.namespace.QName) XMLEvent(javax.xml.stream.events.XMLEvent) Request(com.predic8.membrane.core.http.Request) XMLEventReader(javax.xml.stream.XMLEventReader) IOException(java.io.IOException)

Example 42 with Body

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

the class AdminRESTInterceptor method getRaw.

@Mapping("/admin/rest/exchanges/(-?\\d+)/(response|request)/raw")
public Response getRaw(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();
    if (msg == null) {
        return Response.noContent().build();
    }
    // TODO uses body.toString that doesn't handle different encodings than utf-8
    return Response.ok().contentType(MimeType.TEXT_PLAIN_UTF8).body(msg.toString()).build();
}
Also used : Message(com.predic8.membrane.core.http.Message) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange)

Example 43 with Body

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

the class ElasticSearchExchangeStore method removeAllExchanges.

@Override
public void removeAllExchanges(AbstractExchange[] exchanges) {
    StringBuilder sb = Stream.of(exchanges).map(exc -> exc.getId()).collect(() -> {
        StringBuilder acc = new StringBuilder();
        acc.append("[");
        return acc;
    }, (acc, id) -> acc.append(id).append(","), (acc1, acc2) -> acc1.append(",").append(acc2));
    sb.deleteCharAt(sb.length() - 1);
    sb.append("]");
    String exchangeIdsAsJsonArray = sb.toString();
    try {
        Exchange exc = new Request.Builder().post(getElasticSearchExchangesPath() + "_delete_by_query").body("{\n" + "  \"query\": {\n" + "    \"bool\": {\n" + "      \"must\": [\n" + "        {\n" + "          \"wildcard\": {\n" + "            \"issuer\": \"" + documentPrefix + "\"\n" + "          }\n" + "        },\n" + "        {\n" + "          \"terms\": {\n" + "            \"id\": \"" + exchangeIdsAsJsonArray + "\"\n" + "          }\n" + "        }\n" + "      ]\n" + "    }\n" + "  }\n" + "}").header("Content-Type", "application/json").buildExchange();
        client.call(exc);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : java.util(java.util) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) LoggerFactory(org.slf4j.LoggerFactory) DynamicAbstractExchangeSnapshot(com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot) InetAddress(java.net.InetAddress) Exchange(com.predic8.membrane.core.exchange.Exchange) MCElement(com.predic8.membrane.annot.MCElement) Interceptor(com.predic8.membrane.core.interceptor.Interceptor) RuleKey(com.predic8.membrane.core.rules.RuleKey) MCAttribute(com.predic8.membrane.annot.MCAttribute) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) AbstractExchangeSnapshot(com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) Rule(com.predic8.membrane.core.rules.Rule) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) com.predic8.membrane.core.http(com.predic8.membrane.core.http) CacheBuilder(com.google.common.cache.CacheBuilder) HttpClient(com.predic8.membrane.core.transport.http.HttpClient) Cache(com.google.common.cache.Cache) StatisticCollector(com.predic8.membrane.core.rules.StatisticCollector) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) Exchange(com.predic8.membrane.core.exchange.Exchange) CacheBuilder(com.google.common.cache.CacheBuilder) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 44 with Body

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

the class ElasticSearchExchangeStore method getFromElasticSearchById.

private AbstractExchangeSnapshot getFromElasticSearchById(int id) {
    try {
        Exchange exc = new Request.Builder().post(getElasticSearchExchangesPath() + "_search").body("{\n" + "  \"query\": {\n" + "    \"bool\": {\n" + "      \"must\": [\n" + "        {\n" + "          \"wildcard\": {\n" + "            \"issuer\": \"" + documentPrefix + "\"\n" + "          }\n" + "        },\n" + "        {\n" + "          \"match\": {\n" + "            \"id\": \"" + id + "\"\n" + "          }\n" + "        }\n" + "      ]\n" + "    }\n" + "  }\n" + "}").header("Content-Type", "application/json").buildExchange();
        exc = client.call(exc);
        Map res = responseToMap(exc);
        Map excJson = getSourceElementFromElasticSearchResponse(res).get(0);
        return mapper.readValue(mapper.writeValueAsString(excJson), AbstractExchangeSnapshot.class);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) Exchange(com.predic8.membrane.core.exchange.Exchange) CacheBuilder(com.google.common.cache.CacheBuilder) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 45 with Body

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

the class ElasticSearchExchangeStore method sendToElasticSearch.

private void sendToElasticSearch(List<AbstractExchangeSnapshot> exchanges) throws Exception {
    StringBuilder data = exchanges.stream().map(exchange -> wrapForBulkOperationElasticSearch(index, type, getLocalMachineNameWithSuffix() + "-" + exchange.getId(), collectExchangeDataFrom(exchange))).collect(StringBuilder::new, (sb, str) -> sb.append(str), (sb1, sb2) -> sb1.append(sb2));
    Exchange elasticSearchExc = new Request.Builder().post(location + "/_bulk").header("Content-Type", "application/x-ndjson").body(data.toString()).buildExchange();
    client.call(elasticSearchExc);
}
Also used : java.util(java.util) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) LoggerFactory(org.slf4j.LoggerFactory) DynamicAbstractExchangeSnapshot(com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot) InetAddress(java.net.InetAddress) Exchange(com.predic8.membrane.core.exchange.Exchange) MCElement(com.predic8.membrane.annot.MCElement) Interceptor(com.predic8.membrane.core.interceptor.Interceptor) RuleKey(com.predic8.membrane.core.rules.RuleKey) MCAttribute(com.predic8.membrane.annot.MCAttribute) Logger(org.slf4j.Logger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) AbstractExchangeSnapshot(com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) Rule(com.predic8.membrane.core.rules.Rule) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) Stream(java.util.stream.Stream) com.predic8.membrane.core.http(com.predic8.membrane.core.http) CacheBuilder(com.google.common.cache.CacheBuilder) HttpClient(com.predic8.membrane.core.transport.http.HttpClient) Cache(com.google.common.cache.Cache) StatisticCollector(com.predic8.membrane.core.rules.StatisticCollector) AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) Exchange(com.predic8.membrane.core.exchange.Exchange) CacheBuilder(com.google.common.cache.CacheBuilder)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)30 IOException (java.io.IOException)17 Response (com.predic8.membrane.core.http.Response)15 Request (com.predic8.membrane.core.http.Request)12 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)10 Test (org.junit.Test)10 CacheBuilder (com.google.common.cache.CacheBuilder)8 MCElement (com.predic8.membrane.annot.MCElement)6 Body (com.predic8.membrane.core.http.Body)6 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)6 UnknownHostException (java.net.UnknownHostException)6 Message (com.predic8.membrane.core.http.Message)5 ServiceProxy (com.predic8.membrane.core.rules.ServiceProxy)5 InputStream (java.io.InputStream)5 JsonFactory (com.fasterxml.jackson.core.JsonFactory)4 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)4 HttpRouter (com.predic8.membrane.core.HttpRouter)4 AbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot)4 DynamicAbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot)4 Header (com.predic8.membrane.core.http.Header)4