Search in sources :

Example 51 with Body

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

the class MessageAnalyserTest method getResponse.

private Exchange getResponse(String path) throws IOException {
    Exchange exc = new Exchange(null);
    exc.setResponse(Response.ok().body(getClass().getClassLoader().getResourceAsStream(path), true).build());
    return exc;
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange)

Example 52 with Body

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

the class WADLInterceptorTest method getExchange.

private Exchange getExchange() throws IOException {
    Exchange exc = new Exchange(new FakeHttpHandler(3011));
    exc.setRequest(MessageUtil.getGetRequest("/search?wadl"));
    InputStream resourceAsStream = this.getClass().getResourceAsStream("/wadls/search.wadl");
    Response okResponse = Response.ok().contentType("text/xml; charset=utf-8").body(resourceAsStream, true).build();
    exc.setResponse(okResponse);
    exc.setOriginalHostHeader("thomas-bayer.com:80");
    return exc;
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) InputStream(java.io.InputStream) FakeHttpHandler(com.predic8.membrane.core.transport.http.FakeHttpHandler)

Example 53 with Body

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

the class AbortExchangeTest method setup.

@Before
public void setup() throws Exception {
    router = new HttpRouter();
    LimitedMemoryExchangeStore es = new LimitedMemoryExchangeStore();
    router.setExchangeStore(es);
    router.getTransport().getInterceptors().add(2, new ExchangeStoreInterceptor(es));
    ServiceProxy sp2 = new ServiceProxy(new ServiceProxyKey("*", "*", ".*", 3031), "", -1);
    sp2.getInterceptors().add(new AbstractInterceptor() {

        @Override
        public Outcome handleRequest(Exchange exc) throws Exception {
            exc.getRequest().readBody();
            exc.setResponse(Response.ok("").body(new InputStream() {

                int l = 0;

                @Override
                public int read() throws IOException {
                    if (l >= 2000000)
                        return -1;
                    return 0;
                }
            }, true).build());
            return Outcome.RETURN;
        }
    });
    router.getRuleManager().addProxyAndOpenPortIfNew(sp2);
    router.init();
}
Also used : AbstractExchange(com.predic8.membrane.core.exchange.AbstractExchange) Exchange(com.predic8.membrane.core.exchange.Exchange) ServiceProxyKey(com.predic8.membrane.core.rules.ServiceProxyKey) ServiceProxy(com.predic8.membrane.core.rules.ServiceProxy) Outcome(com.predic8.membrane.core.interceptor.Outcome) InputStream(java.io.InputStream) AbstractInterceptor(com.predic8.membrane.core.interceptor.AbstractInterceptor) ExchangeStoreInterceptor(com.predic8.membrane.core.interceptor.ExchangeStoreInterceptor) HttpRouter(com.predic8.membrane.core.HttpRouter) IOException(java.io.IOException) Before(org.junit.Before)

Example 54 with Body

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

the class LargeBodyTest method large.

@Test
public void large() throws Exception {
    setup();
    long len = Integer.MAX_VALUE + 1l;
    Exchange e = new Request.Builder().post("http://localhost:3041/foo").body(len, new ConstantInputStream(len)).buildExchange();
    new HttpClient(hcc).call(e);
}
Also used : Exchange(com.predic8.membrane.core.exchange.Exchange) HttpClient(com.predic8.membrane.core.transport.http.HttpClient) Test(org.junit.Test)

Example 55 with Body

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

the class OAuth2ResourceInterceptor method handleRequest.

public boolean handleRequest(Exchange exc, String state, String publicURL, Session session) throws Exception {
    String path = uriFactory.create(exc.getDestinations().get(0)).getPath();
    if (path == null)
        return false;
    if (path.endsWith("/oauth2callback")) {
        try {
            Map<String, String> params = URLParamUtil.getParams(uriFactory, exc);
            String state2 = params.get("state");
            if (state2 == null)
                throw new RuntimeException("No CSRF token.");
            Map<String, String> param = URLParamUtil.parseQueryString(state2);
            if (param == null || !param.containsKey("security_token"))
                throw new RuntimeException("No CSRF token.");
            boolean csrfMatch = false;
            for (String state3 : stateToOriginalUrl.keySet()) if (param.get("security_token").equals(state3))
                csrfMatch = true;
            if (!csrfMatch)
                throw new RuntimeException("CSRF token mismatch.");
            Request originalRequest = stateToOriginalUrl.get(param.get("security_token"));
            String url = originalRequest.getUri();
            if (url == null)
                url = "/";
            stateToOriginalUrl.remove(state2);
            if (log.isDebugEnabled())
                log.debug("CSRF token match.");
            String code = params.get("code");
            if (code == null)
                throw new RuntimeException("No code received.");
            Exchange e = new Request.Builder().post(auth.getTokenEndpoint()).header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded").header(Header.ACCEPT, "application/json").header(Header.USER_AGENT, Constants.USERAGENT).body("code=" + code + "&client_id=" + auth.getClientId() + "&client_secret=" + auth.getClientSecret() + "&redirect_uri=" + publicURL + "oauth2callback" + "&grant_type=authorization_code").buildExchange();
            LogInterceptor logi = null;
            if (log.isDebugEnabled()) {
                logi = new LogInterceptor();
                logi.setHeaderOnly(false);
                logi.handleRequest(e);
            }
            Response response = auth.doRequest(e);
            if (response.getStatusCode() != 200) {
                response.getBody().read();
                throw new RuntimeException("Authentication server returned " + response.getStatusCode() + ".");
            }
            if (log.isDebugEnabled())
                logi.handleResponse(e);
            HashMap<String, String> json = Util.parseSimpleJSONResponse(response);
            if (!json.containsKey("access_token"))
                throw new RuntimeException("No access_token received.");
            // and also "scope": "", "token_type": "bearer"
            String token = (String) json.get("access_token");
            OAuth2AnswerParameters oauth2Answer = new OAuth2AnswerParameters();
            synchronized (session) {
                // saving for logout
                session.getUserAttributes().put("access_token", token);
            }
            oauth2Answer.setAccessToken(token);
            oauth2Answer.setTokenType(json.get("token_type"));
            oauth2Answer.setExpiration(json.get("expires_in"));
            oauth2Answer.setRefreshToken(json.get("refresh_token"));
            oauth2Answer.setReceivedAt(LocalDateTime.now());
            if (json.containsKey("id_token")) {
                if (idTokenIsValid(json.get("id_token")))
                    oauth2Answer.setIdToken(json.get("id_token"));
                else
                    oauth2Answer.setIdToken("INVALID");
            }
            validTokens.put(token, true);
            Exchange e2 = new Request.Builder().get(auth.getUserInfoEndpoint()).header("Authorization", json.get("token_type") + " " + token).header("User-Agent", Constants.USERAGENT).header(Header.ACCEPT, "application/json").buildExchange();
            if (log.isDebugEnabled()) {
                logi.setHeaderOnly(false);
                logi.handleRequest(e2);
            }
            Response response2 = auth.doRequest(e2);
            if (log.isDebugEnabled())
                logi.handleResponse(e2);
            if (response2.getStatusCode() != 200) {
                statistics.accessTokenInvalid();
                throw new RuntimeException("User data could not be retrieved.");
            }
            statistics.accessTokenValid();
            HashMap<String, String> json2 = Util.parseSimpleJSONResponse(response2);
            oauth2Answer.setUserinfo(json2);
            session.getUserAttributes().put(OAUTH2_ANSWER, oauth2Answer.serialize());
            processUserInfo(json2, session);
            exc.setRequest(originalRequest);
            return true;
        } catch (Exception e) {
            exc.setResponse(Response.badRequest().body(e.getMessage()).build());
            return true;
        }
    }
    return false;
}
Also used : CacheBuilder(com.google.common.cache.CacheBuilder) Request(com.predic8.membrane.core.http.Request) ParseException(com.floreysoft.jmte.message.ParseException) IOException(java.io.IOException) Exchange(com.predic8.membrane.core.exchange.Exchange) Response(com.predic8.membrane.core.http.Response) LogInterceptor(com.predic8.membrane.core.interceptor.LogInterceptor)

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