Search in sources :

Example 1 with HttpProxyRule

use of io.fabric8.gateway.model.HttpProxyRule in project fabric8 by jboss-fuse.

the class JsonRuleBaseReaderTest method parseWithCookiePath.

@Test
public void parseWithCookiePath() throws Exception {
    final InputStream in = JsonRuleBaseBuilder.newRuleBase().rule("/foo/{path}", "https://foo.com/cheese/{path}", "/cookiePath").inputStream();
    final Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(in);
    final HttpProxyRule httpProxyRule = rules.get("/foo/{path}");
    assertThat(httpProxyRule.getCookiePath(), equalTo("/cookiePath"));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule) Test(org.junit.Test)

Example 2 with HttpProxyRule

use of io.fabric8.gateway.model.HttpProxyRule in project fabric8 by jboss-fuse.

the class ProxyServlet method executeProxyRequest.

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);
    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
    intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED) /* 304 */
    {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation.replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);
    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }
    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }
    LOG.trace("Response has data? {}", !noData);
    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) Header(org.apache.commons.httpclient.Header) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) OutputStream(java.io.OutputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Example 3 with HttpProxyRule

use of io.fabric8.gateway.model.HttpProxyRule in project fabric8 by jboss-fuse.

the class JsonRuleBaseReader method parseJson.

/**
 * Will try to parse the {@link InputStream} which is expected to be in the following
 * JSON format:
 * <pre>
 * { "rulebase" : [
 *    { "rule": "/foo/{path}", "to": "https://foo.com/cheese/{path}"},
 *    { "rule": "/customers/{id}/address/{addressId}", "to": "http://another.com/addresses/{addressId}/customer/{id}"}
 *  ]
 * }
 * </pre>
 *
 * <strong>Note that the passed-in {@link InputStream} will be closed by this method</strong>. This
 * is a little unusual as normally the closing is the responsibility of the party that created the
 * InputStream, but in this case we decided handling this is more user friendly.
 *
 * @param in the {@link InputStream} stream to read.
 * @return {@code Map} where the key maps to the 'rule' in the JSON, and the value maps to 'to'.
 */
public static Map<String, HttpProxyRule> parseJson(InputStream in) {
    chechNotNull(in);
    HashMap<String, HttpProxyRule> map = new HashMap<String, HttpProxyRule>();
    try {
        JsonNode config = OM.readTree(in);
        JsonNode globalCookiePath = config.get("cookiePath");
        JsonNode globalDomain = config.get("cookieDomain");
        for (JsonNode entry : getRuleBase(config)) {
            String rule = entry.get("rule").asText();
            map.put(rule, new HttpProxyRule(rule).to(entry.get("to").asText()).setCookiePath(getGlobal(entry, globalCookiePath, "cookiePath")).setCookieDomain(getGlobal(entry, globalDomain, "cookieDomain")));
        }
        return map;
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        safeClose(in);
    }
}
Also used : HashMap(java.util.HashMap) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Example 4 with HttpProxyRule

use of io.fabric8.gateway.model.HttpProxyRule in project fabric8 by jboss-fuse.

the class MappingRuleResolver method findMappingRule.

public MappingResult findMappingRule(String requestURI) {
    String[] paths = Paths.splitPaths(requestURI);
    MappingResult answer = null;
    // TODO we could build a path based tree to do more efficient matching?
    for (HttpProxyRule mappingRule : mappingRules.getMappingRules().values()) {
        answer = mappingRule.matches(paths);
        if (answer != null) {
            break;
        }
    }
    return answer;
}
Also used : HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Example 5 with HttpProxyRule

use of io.fabric8.gateway.model.HttpProxyRule in project fabric8 by jboss-fuse.

the class JsonRuleBaseReaderTest method parseWithGlobalCookiePath.

@Test
public void parseWithGlobalCookiePath() throws Exception {
    final InputStream in = JsonRuleBaseBuilder.newRuleBase().globalCookiePath("/cookiePath").rule("/foo/{path}", "https://foo.com/cheese/{path}").rule("/foo2/{path}", "https://foo2.com/cheese/{path}", "/overriddenCookiePath").inputStream();
    final Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(in);
    assertThat(rules.get("/foo/{path}").getCookiePath(), equalTo("/cookiePath"));
    assertThat(rules.get("/foo2/{path}").getCookiePath(), equalTo("/overriddenCookiePath"));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule) Test(org.junit.Test)

Aggregations

HttpProxyRule (io.fabric8.gateway.model.HttpProxyRule)9 InputStream (java.io.InputStream)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 Test (org.junit.Test)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 BufferedInputStream (java.io.BufferedInputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 HashMap (java.util.HashMap)1 ServletException (javax.servlet.ServletException)1 Header (org.apache.commons.httpclient.Header)1 HttpClient (org.apache.commons.httpclient.HttpClient)1