Search in sources :

Example 61 with Response

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

the class QuickstartRESTTest method doit.

@Test
public void doit() throws IOException, InterruptedException {
    File baseDir = getExampleDir("quickstart-rest");
    Process2 sl = new Process2.Builder().in(baseDir).script("service-proxy").waitForMembrane().start();
    try {
        String result = getAndAssert200("http://localhost:2000/restnames/name.groovy?name=Pia");
        assertContains("Italy", result);
        AssertUtils.closeConnections();
        new ProxiesXmlUtil(new File(baseDir, "proxies.xml")).updateWith("<spring:beans xmlns=\"http://membrane-soa.org/proxies/1/\"\r\n" + "	xmlns:spring=\"http://www.springframework.org/schema/beans\"\r\n" + "	xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + "	xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd\r\n" + "					    http://membrane-soa.org/proxies/1/ http://membrane-soa.org/schemas/proxies-1.xsd\">\r\n" + "\r\n" + "	<router>\r\n" + "\r\n" + "       <serviceProxy name=\"names\" port=\"2000\">\r\n" + "         <path isRegExp=\"true\">/(rest)?names.*</path>\r\n" + "         <rewriter>\r\n" + "           <map from=\"/names/(.*)\" to=\"/restnames/name\\.groovy\\?name=$1\" />\r\n" + "         </rewriter>\r\n" + "         <statisticsCSV file=\"log.csv\" />\r\n" + "         <response>\r\n" + "           <regExReplacer regex=\"\\s*,\\s*&lt;\" replace=\"&lt;\" />\r\n" + "           <transform xslt=\"restnames.xsl\" />\r\n" + "         </response>\r\n" + "         <target host=\"thomas-bayer.com\" port=\"80\" />\r\n" + "       </serviceProxy>\r\n" + "     \r\n" + "       <serviceProxy name=\"Console\" port=\"9000\">\r\n" + "         <basicAuthentication>\r\n" + "           <user name=\"alice\" password=\"membrane\" />\r\n" + "         </basicAuthentication>			\r\n" + "         <adminConsole />\r\n" + "       </serviceProxy>	\r\n" + "     </router>\r\n" + "</spring:beans>", sl);
        result = getAndAssert200("http://localhost:2000/names/Pia");
        assertContains("Italy, Spain", result);
        assertContainsNot(",<", result);
        String csvLog = FileUtils.readFileToString(new File(baseDir, "log.csv"));
        assertContains("Pia", csvLog);
        AssertUtils.setupHTTPAuthentication("localhost", 9000, "alice", "membrane");
        result = getAndAssert200("http://localhost:9000/admin/");
        assertContains("ServiceProxies", result);
    } finally {
        sl.killScript();
    }
}
Also used : Process2(com.predic8.membrane.examples.Process2) ProxiesXmlUtil(com.predic8.membrane.examples.ProxiesXmlUtil) File(java.io.File) Test(org.junit.Test)

Example 62 with Response

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

the class Test method main.

public static void main(String[] args) throws Exception {
    URIFactory uriFactory = new URIFactory();
    uriFactory.setAllowIllegalCharacters(true);
    Response res = new HttpClient().call(new Request.Builder().get(uriFactory, "http://localhost:2000/a.{/").buildExchange()).getResponse();
    System.out.println(res.getStatusCode());
    System.out.println(res.getStartLine());
}
Also used : Response(com.predic8.membrane.core.http.Response) HttpClient(com.predic8.membrane.core.transport.http.HttpClient) URIFactory(com.predic8.membrane.core.util.URIFactory)

Example 63 with Response

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

the class AbstractHttpHandler method generateErrorResponse.

private Response generateErrorResponse(Exception e) {
    String msg;
    boolean printStackTrace = transport.isPrintStackTrace();
    if (printStackTrace) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        msg = sw.toString();
    } else {
        msg = e.toString();
    }
    String comment = "Stack traces can be " + (printStackTrace ? "dis" : "en") + "abled by setting the " + "@printStackTrace attribute on <a href=\"https://membrane-soa.org/service-proxy-doc/current/configuration/reference/transport.htm\">transport</a>. " + "More details might be found in the log.";
    Response error = null;
    ResponseBuilder b = null;
    if (e instanceof URISyntaxException)
        b = Response.badRequest();
    if (b == null)
        b = Response.internalServerError();
    switch(ContentTypeDetector.detect(exchange.getRequest()).getEffectiveContentType()) {
        case XML:
            error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8)).body(("<error><message>" + StringEscapeUtils.escapeXml(msg) + "</message><comment>" + StringEscapeUtils.escapeXml(comment) + "</comment></error>").getBytes(Constants.UTF_8_CHARSET)).build();
            break;
        case JSON:
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                JsonGenerator jg = new JsonFactory().createGenerator(baos);
                jg.writeStartObject();
                jg.writeFieldName("error");
                jg.writeString(msg);
                jg.writeFieldName("comment");
                jg.writeString(comment);
                jg.close();
            } catch (Exception f) {
                log.error("Error generating JSON error response", f);
            }
            error = b.header(HttpUtil.createHeaders(MimeType.APPLICATION_JSON_UTF8)).body(baos.toByteArray()).build();
            break;
        case SOAP:
            error = b.header(HttpUtil.createHeaders(MimeType.TEXT_XML_UTF8)).body(HttpUtil.getFaultSOAPBody("Internal Server Error", msg + " " + comment).getBytes(Constants.UTF_8_CHARSET)).build();
            break;
        case UNKNOWN:
            error = HttpUtil.setHTMLErrorResponse(b, msg, comment);
            break;
    }
    return error;
}
Also used : Response(com.predic8.membrane.core.http.Response) StringWriter(java.io.StringWriter) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) URISyntaxException(java.net.URISyntaxException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ResponseBuilder(com.predic8.membrane.core.http.Response.ResponseBuilder) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) PrintWriter(java.io.PrintWriter)

Example 64 with Response

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

the class HttpServerHandler method run.

public void run() {
    // see Request.isBindTargetConnectionToIncoming()
    Connection boundConnection = null;
    try {
        updateThreadName(true);
        setup();
        while (true) {
            srcReq = new Request();
            endpointListener.setIdleStatus(sourceSocket, true);
            try {
                srcIn.mark(2);
                if (srcIn.read() == -1)
                    break;
                srcIn.reset();
            } finally {
                endpointListener.setIdleStatus(sourceSocket, false);
            }
            if (boundConnection != null) {
                exchange.setTargetConnection(boundConnection);
                boundConnection = null;
            }
            srcReq.read(srcIn, true);
            exchange.received();
            if (srcReq.getHeader().getProxyConnection() != null) {
                srcReq.getHeader().add(Header.CONNECTION, srcReq.getHeader().getProxyConnection());
                srcReq.getHeader().removeFields(Header.PROXY_CONNECTION);
            }
            process();
            if (srcReq.isCONNECTRequest()) {
                log.debug("stopping HTTP Server Thread after establishing an HTTP connect");
                return;
            }
            boundConnection = exchange.getTargetConnection();
            exchange.setTargetConnection(null);
            if (!exchange.canKeepConnectionAlive())
                break;
            if (exchange.getResponse().isRedirect()) {
                break;
            }
            exchange.detach();
            exchange = new Exchange(this);
        }
    } catch (SocketTimeoutException e) {
        log.debug("Socket of thread " + counter + " timed out");
    } catch (SocketException se) {
        log.debug("client socket closed");
    } catch (SSLException s) {
        if (showSSLExceptions) {
            if (s.getCause() instanceof SSLException)
                s = (SSLException) s.getCause();
            if (s.getCause() instanceof SocketException)
                log.debug("ssl socket closed");
            else
                log.error("", s);
        }
    } catch (IOException e) {
        log.error("", e);
    } catch (EndOfStreamException e) {
        log.debug("stream closed");
    } catch (AbortException e) {
        log.debug("exchange aborted.");
    } catch (NoMoreRequestsException e) {
    // happens at the end of a keep-alive connection
    } catch (NoResponseException e) {
        log.debug("No response received. Maybe increase the keep-alive timeout on the server.");
    } catch (EOFWhileReadingFirstLineException e) {
        log.debug("Client connection terminated before line was read. Line so far: (" + e.getLineSoFar() + ")");
    } catch (Exception e) {
        log.error("", e);
    } finally {
        endpointListener.setOpenStatus(sourceSocket, false);
        if (boundConnection != null)
            try {
                boundConnection.close();
            } catch (IOException e) {
                log.debug("Closing bound connection.", e);
            }
        closeConnections();
        exchange.detach();
        updateThreadName(false);
    }
}
Also used : SocketException(java.net.SocketException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) Request(com.predic8.membrane.core.http.Request) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException) IOException(java.io.IOException) EndOfStreamException(com.predic8.membrane.core.util.EndOfStreamException) SocketException(java.net.SocketException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) Exchange(com.predic8.membrane.core.exchange.Exchange) SocketTimeoutException(java.net.SocketTimeoutException)

Example 65 with Response

use of com.predic8.membrane.core.http.Response in project carbon-business-process by wso2.

the class HTRenderingApiImpl method createSoapTemplate.

/**
 * Function to create response message template
 *
 * @param SrcWsdl   source wsld : wsdl file path or url
 * @param portType  callback port type
 * @param operation callback operation name
 * @param binding   callback binding
 * @return DOM element of response message template
 * @throws IOException  If error occurred while parsing string xml to Dom element
 * @throws SAXException If error occurred while parsing string xml to Dom element
 */
private static Element createSoapTemplate(String SrcWsdl, String portType, String operation, String binding) throws IOException, SAXException {
    WSDLParser parser = new WSDLParser();
    // BPS-677
    int fileLocationPrefixIndex = SrcWsdl.indexOf(HumanTaskConstants.FILE_LOCATION_FILE_PREFIX);
    if (SrcWsdl.indexOf(HumanTaskConstants.FILE_LOCATION_FILE_PREFIX) != -1) {
        SrcWsdl = SrcWsdl.substring(fileLocationPrefixIndex + HumanTaskConstants.FILE_LOCATION_FILE_PREFIX.length());
    }
    Definitions wsdl = parser.parse(SrcWsdl);
    StringWriter writer = new StringWriter();
    // SOAPRequestCreator constructor: SOARequestCreator(Definitions, Creator, MarkupBuilder)
    SOARequestCreator creator = new SOARequestCreator(wsdl, new RequestTemplateCreator(), new MarkupBuilder(writer));
    // creator.createRequest(PortType name, Operation name, Binding name);
    creator.createRequest(portType, operation, binding);
    Element outGenMessageDom = DOMUtils.stringToDOM(writer.toString());
    Element outMsgElement = null;
    NodeList nodes = outGenMessageDom.getElementsByTagNameNS(outGenMessageDom.getNamespaceURI(), "Body").item(0).getChildNodes();
    if (nodes != null) {
        for (int i = 0; i < nodes.getLength(); i++) {
            if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
                outMsgElement = (Element) nodes.item(i);
                break;
            }
        }
    }
    if (outMsgElement != null) {
        // convert element to string and back to element to remove Owner Document
        return DOMUtils.stringToDOM(DOMUtils.domToString(outMsgElement));
    }
    return null;
}
Also used : RequestTemplateCreator(com.predic8.wstool.creator.RequestTemplateCreator) StringWriter(java.io.StringWriter) Definitions(com.predic8.wsdl.Definitions) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) MarkupBuilder(groovy.xml.MarkupBuilder) WSDLParser(com.predic8.wsdl.WSDLParser) SOARequestCreator(com.predic8.wstool.creator.SOARequestCreator)

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