Search in sources :

Example 31 with Header

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

the class ReverseProxyingInterceptorTest method getRewrittenDestination.

/**
 * Lets the ReverseProxyingInterceptor handle a fake Exchange and returns the rewritten "Destination" header.
 */
private String getRewrittenDestination(String requestHostHeader, String requestDestinationHeader, int port, String requestURI, String targetScheme, int targetPort) throws Exception {
    Exchange exc = createExchange(requestHostHeader, requestDestinationHeader, port, requestURI, null);
    String url = new URL(targetScheme, "target", targetPort, exc.getRequest().getUri()).toString();
    exc.getDestinations().add(url);
    Assert.assertEquals(Outcome.CONTINUE, rp.handleRequest(exc));
    return exc.getRequest().getHeader().getFirstValue(Header.DESTINATION);
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) URL(java.net.URL)

Example 32 with Header

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

the class ReverseProxyingInterceptorTest method createExchange.

/**
 * Creates a fake exchange which simulates a received redirect by the server.
 */
private Exchange createExchange(String requestHostHeader, String requestDestinationHeader, int port, String requestURI, String redirectionURI) {
    Exchange exc = new Exchange(new FakeHttpHandler(port));
    Request req = new Request();
    req.setUri(requestURI);
    Header header = new Header();
    if (requestHostHeader != null)
        header.setHost(requestHostHeader);
    if (requestDestinationHeader != null)
        header.add(Header.DESTINATION, requestDestinationHeader);
    req.setHeader(header);
    exc.setRequest(req);
    if (redirectionURI != null) {
        Response res = Response.redirect(redirectionURI, false).build();
        exc.setResponse(res);
        exc.getDestinations().add(requestURI);
    }
    return exc;
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) FakeHttpHandler(com.predic8.membrane.core.transport.http.FakeHttpHandler) Request(com.predic8.membrane.core.http.Request)

Example 33 with Header

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

the class ReverseProxyingInterceptorTest method getRewrittenRedirectionLocation.

/**
 * Lets the ReverseProxyingInterceptor handle a fake Exchange and returns the rewritten "Location" header.
 */
private String getRewrittenRedirectionLocation(String requestHostHeader, int port, String requestURI, String redirectionURI) throws Exception {
    Exchange exc = createExchange(requestHostHeader, null, port, requestURI, redirectionURI);
    Assert.assertEquals(Outcome.CONTINUE, rp.handleResponse(exc));
    return exc.getResponse().getHeader().getFirstValue(Header.LOCATION);
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange)

Example 34 with Header

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

the class SOAP2RESTInterceptor method handleRequest.

@Override
public Outcome handleRequest(Exchange exc) throws Exception {
    // save SOAP operationName and namespace in exchange properties to generically construct response name
    soe.handleRequest(exc);
    // apply request XSLT
    transformAndReplaceBody(exc.getRequest(), requestXSLT, new StreamSource(exc.getRequest().getBodyAsStreamDecoded()), exc.getStringProperties());
    // fill Request object from HTTP-XML
    Header header = exc.getRequest().getHeader();
    header.removeFields(Header.CONTENT_TYPE);
    header.setContentType(MimeType.TEXT_XML_UTF8);
    XML2HTTP.unwrapMessageIfNecessary(exc.getRequest());
    // reset exchange destination to new request URI
    exc.getDestinations().clear();
    di.handleRequest(exc);
    return Outcome.CONTINUE;
}
Also used : Header(com.predic8.membrane.core.http.Header) StreamSource(javax.xml.transform.stream.StreamSource)

Example 35 with Header

use of com.predic8.membrane.core.http.Header 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)

Aggregations

Exchange (com.predic8.membrane.core.exchange.Exchange)26 Header (com.predic8.membrane.core.http.Header)16 Request (com.predic8.membrane.core.http.Request)13 IOException (java.io.IOException)13 Response (com.predic8.membrane.core.http.Response)12 CacheBuilder (com.google.common.cache.CacheBuilder)8 Test (org.junit.Test)8 AbstractExchange (com.predic8.membrane.core.exchange.AbstractExchange)7 HttpClient (com.predic8.membrane.core.transport.http.HttpClient)6 UnknownHostException (java.net.UnknownHostException)6 MCElement (com.predic8.membrane.annot.MCElement)5 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)4 AbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.AbstractExchangeSnapshot)4 DynamicAbstractExchangeSnapshot (com.predic8.membrane.core.exchange.snapshots.DynamicAbstractExchangeSnapshot)4 HeaderField (com.predic8.membrane.core.http.HeaderField)4 JsonFactory (com.fasterxml.jackson.core.JsonFactory)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DateTimeFormatter (org.joda.time.format.DateTimeFormatter)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Cache (com.google.common.cache.Cache)2