Example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

List of usage examples for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultRedirectStrategy DefaultRedirectStrategy.

Prototype

public DefaultRedirectStrategy() 

Source Link

Usage

From source file:io.undertow.servlet.test.security.form.ServletFormAuthTestCase.java

@Test
public void testServletFormAuth() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override//from  w w  w.ja v a  2 s. c om
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });
    try {
        final String uri = DefaultServer.getDefaultServerURL() + "/servletContext/secured/test";
        HttpGet get = new HttpGet(uri);
        HttpResponse result = client.execute(get);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("Login Page", response);

        BasicNameValuePair[] pairs = new BasicNameValuePair[] { new BasicNameValuePair("j_username", "user1"),
                new BasicNameValuePair("j_password", "password1") };
        final List<NameValuePair> data = new ArrayList<>();
        data.addAll(Arrays.asList(pairs));
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL()
                + "/servletContext/j_security_check;jsessionid=dsjahfklsahdfjklsa");

        post.setEntity(new UrlEncodedFormEntity(data));

        result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("user1", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.mockey.ClientExecuteProxy.java

/**
 * //  ww w  . j a va  2s.c  o m
 * @param twistInfo
 * @param proxyServer
 * @param realServiceUrl
 * @param httpMethod
 * @param request
 * @return
 * @throws ClientExecuteProxyException
 */
public ResponseFromService execute(TwistInfo twistInfo, ProxyServerModel proxyServer, Url realServiceUrl,
        boolean allowRedirectFollow, RequestFromClient request) throws ClientExecuteProxyException {
    log.info("Request: " + String.valueOf(realServiceUrl));

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    if (!allowRedirectFollow) {
        // Do NOT allow for 302 REDIRECT
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                boolean isRedirect = false;
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!isRedirect) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 301 || responseCode == 302) {
                        return true;
                    }
                }
                return isRedirect;
            }
        });
    } else {
        // Yes, allow for 302 REDIRECT
        // Nothing needed here.
    }

    // Prevent CACHE, 304 not modified
    //      httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            
    //            request.setHeader("If-modified-Since", "Fri, 13 May 2006 23:54:18 GMT");
    //
    //         }
    //      });

    CookieStore cookieStore = httpclient.getCookieStore();
    for (Cookie httpClientCookie : request.getHttpClientCookies()) {
        // HACK:
        // httpClientCookie.getValue();
        cookieStore.addCookie(httpClientCookie);
    }
    // httpclient.setCookieStore(cookieStore);

    if (ClientExecuteProxy.cookieStore == null) {
        ClientExecuteProxy.cookieStore = httpclient.getCookieStore();

    } else {
        httpclient.setCookieStore(ClientExecuteProxy.cookieStore);
    }

    StringBuffer requestCookieInfo = new StringBuffer();
    // Show what cookies are in the store .
    for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
        log.debug("Cookie in the cookie STORE: " + cookie.toString());
        requestCookieInfo.append(cookie.toString() + "\n\n\n");

    }

    if (proxyServer.isProxyEnabled()) {
        // make sure to use a proxy that supports CONNECT
        httpclient.getCredentialsProvider().setCredentials(proxyServer.getAuthScope(),
                proxyServer.getCredentials());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost());
    }

    // TWISTING
    Url originalRequestUrlBeforeTwisting = null;
    if (twistInfo != null) {
        String fullurl = realServiceUrl.getFullUrl();
        String twistedUrl = twistInfo.getTwistedValue(fullurl);
        if (twistedUrl != null) {
            originalRequestUrlBeforeTwisting = realServiceUrl;
            realServiceUrl = new Url(twistedUrl);
        }
    }

    ResponseFromService responseMessage = null;
    try {
        HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(),
                realServiceUrl.getScheme());

        HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl));
        if (response.getStatusLine().getStatusCode() == 302) {
            log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl());
        }
        responseMessage = new ResponseFromService(response);
        responseMessage.setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting);
        responseMessage.setRequestUrl(realServiceUrl);
    } catch (Exception e) {
        log.error(e);
        throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Parse out the response information we're looking for
    // StringBuffer responseCookieInfo = new StringBuffer();
    // // Show what cookies are in the store .
    // for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
    // log.info("Cookie in the cookie STORE: " + cookie.toString());
    // responseCookieInfo.append(cookie.toString() + "\n\n\n");
    //
    // }
    // responseMessage.setRequestCookies(requestCookieInfo.toString());
    // responseMessage.setResponseCookies(responseCookieInfo.toString());
    return responseMessage;
}

From source file:org.commonjava.web.json.test.WebFixture.java

public void enableRedirection() {
    http.setRedirectStrategy(new DefaultRedirectStrategy());
}

From source file:org.jutge.joc.porra.service.EmailService.java

/**
 * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down:
 * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside.
 * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail.
 * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over
 * @param userAccount user to send the mail to
 * @param message the message body/*from   w  ww.  j  a v a  2s.  c o  m*/
 * @throws Exception should anything crash
 */
private void sendMail(final Account userAccount, final String message) throws Exception {
    // Enviar mail pel Raco
    // Authenticate
    final List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp"));
    params.add(new BasicNameValuePair("loginDirecte", "true"));
    params.add(new BasicNameValuePair("username", "XXXXXXXX"));
    params.add(new BasicNameValuePair("password", "XXXXXXXX"));
    HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login");
    post.setEntity(new UrlEncodedFormEntity(params));
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) {
            boolean isRedirect = false;
            try {
                isRedirect = super.isRedirected(request, response, context);
            } catch (ProtocolException e) {
                EmailService.this.logger.error(e.getMessage());
            }
            if (!isRedirect) {
                final int responseCode = response.getStatusLine().getStatusCode();
                isRedirect = responseCode == 301 || responseCode == 302;
            }
            return isRedirect;
        }
    });
    HttpResponse response = httpClient.execute(post);
    HttpEntity entity = response.getEntity();
    EntityUtils.consumeQuietly(entity);
    // get form page
    final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq="
            + System.currentTimeMillis());
    response = httpClient.execute(get);
    entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    // Find form action with uniq parameter 
    Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN);
    Matcher matcher = pattern.matcher(responseBody);
    matcher.find();
    final String action = matcher.group();
    // formtoken
    responseBody = responseBody.substring(matcher.end(), responseBody.length());
    pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN);
    matcher = pattern.matcher(responseBody);
    matcher.find();
    String formToken = matcher.group();
    formToken = formToken.substring(28, formToken.length());
    // to
    final String email = userAccount.getEmail();
    // Send mail - it's a multipart post
    final MultipartEntity multipart = new MultipartEntity();
    multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240"));
    multipart.addPart("actionID", new StringBody("send_message"));
    multipart.addPart("__formToken_compose", new StringBody(formToken));
    multipart.addPart("messageCache", new StringBody(""));
    multipart.addPart("spellcheck", new StringBody(""));
    multipart.addPart("page", new StringBody(""));
    multipart.addPart("start", new StringBody(""));
    multipart.addPart("thismailbox", new StringBody("INBOX"));
    multipart.addPart("attachmentAction", new StringBody(""));
    multipart.addPart("reloaded", new StringBody("1"));
    multipart.addPart("oldrtemode", new StringBody(""));
    multipart.addPart("rtemode", new StringBody("1"));
    multipart.addPart("last_identity", new StringBody("0"));
    multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu"));
    multipart.addPart("to", new StringBody(email));
    multipart.addPart("cc", new StringBody(""));
    multipart.addPart("bcc", new StringBody(""));
    multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA"));
    multipart.addPart("charset", new StringBody("UTF-8"));
    multipart.addPart("save_sent_mail", new StringBody("on"));
    multipart.addPart("message", new StringBody(message));
    multipart.addPart("upload_1", new StringBody(""));
    multipart.addPart("upload_disposition_1", new StringBody("attachment"));
    multipart.addPart("save_attachments_select", new StringBody("0"));
    multipart.addPart("link_attachments", new StringBody("0"));
    post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action);
    post.setEntity(multipart);
    response = httpClient.execute(post);
    EntityUtils.consumeQuietly(entity);
    this.logger.info("EmailService.sendMail done");
}

From source file:com.bigdata.rdf.sparql.ast.service.RemoteServiceCallImpl.java

@Override
public ICloseableIterator<BindingSet> call(final BindingSet[] bindingSets) throws Exception {

    final String uriStr = params.getServiceURI().stringValue();

    final RemoteServiceOptions serviceOptions = getServiceOptions();

    final ConnectOptions o = new ConnectOptions(uriStr);

    {/* www .  ja va2  s  . co  m*/

        final String acceptHeader = serviceOptions.getAcceptHeader();

        if (acceptHeader != null) {

            o.setAcceptHeader(acceptHeader);

        } else {

            o.setAcceptHeader(ConnectOptions.DEFAULT_SOLUTIONS_ACCEPT_HEADER);

        }

    }

    o.method = serviceOptions.isGET() ? "GET" : "POST";

    //        final QueryOptions opts = new QueryOptions(serviceURI.stringValue());
    //
    //        opts.acceptHeader = serviceOptions.getAcceptHeader();

    /*
     * Note: This uses a factory pattern to handle each of the possible ways
     * in which we have to vector solutions to the service end point.
     */
    final IRemoteSparqlQueryBuilder queryBuilder = RemoteSparqlBuilderFactory.get(serviceOptions,
            params.getServiceNode(), bindingSets);

    final String queryStr = queryBuilder.getSparqlQuery(bindingSets);

    //        opts.queryStr = queryStr;

    final UUID queryId = UUID.randomUUID();

    o.addRequestParam("query", queryStr);

    o.addRequestParam("queryId", queryId.toString());

    final DefaultHttpClient httpClient = new DefaultHttpClient(params.getClientConnectionManager());

    // Setup a standard strategy for following redirects.
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());

    final RemoteRepository repo = new RemoteRepository(uriStr, //
            httpClient, //
            params.getTripleStore().getExecutorService());

    /*
     * Note: This does not stream chunks back. The ServiceCallJoin currently
     * materializes all solutions from the service in a single chunk, so
     * there is no point doing something incremental here unless it is
     * coordinated with the ServiceCallJoin.
     */

    final TupleQueryResult queryResult;

    try {

        //            final HttpResponse resp = repo.doConnect(o);
        //            
        //            RemoteRepository.checkResponseCode(resp);
        //            
        //            queryResult = repo.tupleResults(resp);
        //            
        ////            queryResult = parseResults(checkResponseCode(doSparqlQuery(opts)));

        queryResult = repo.tupleResults(o, queryId);

    } finally {

        /*
         * Note: HttpURLConnection.disconnect() is not a "close". close() is
         * an implicit action for this class.
         */

    }

    return new Sesame2BigdataIterator<BindingSet, QueryEvaluationException>(queryResult);

}

From source file:io.undertow.servlet.test.security.form.ServletFormAuthURLRewriteTestCase.java

@Test
public void testServletFormAuth() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override/*w w  w  .ja  v  a 2s .  co m*/
        public boolean isRedirected(final HttpRequest request, final HttpResponse response,
                final HttpContext context) throws ProtocolException {
            if (response.getStatusLine().getStatusCode() == StatusCodes.FOUND) {
                return true;
            }
            return super.isRedirected(request, response, context);
        }
    });
    try {
        final String uri = DefaultServer.getDefaultServerURL() + "/servletContext/secured/test";
        HttpGet get = new HttpGet(uri);
        HttpResponse result = client.execute(get);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertTrue(response.startsWith("j_security_check"));

        BasicNameValuePair[] pairs = new BasicNameValuePair[] { new BasicNameValuePair("j_username", "user1"),
                new BasicNameValuePair("j_password", "password1") };
        final List<NameValuePair> data = new ArrayList<>();
        data.addAll(Arrays.asList(pairs));
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext/" + response);

        post.setEntity(new UrlEncodedFormEntity(data));

        result = client.execute(post);
        assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());

        response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("user1", response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java

private HttpAsyncClientBuilder setRedirects(HttpAsyncClientBuilder clientBuilder) {
    clientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        /** Redirectable methods. */
        private String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME,
                HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpHead.METHOD_NAME };

        @Override/*from  w  w w.  j  a  va  2s.  co  m*/
        protected boolean isRedirectable(String method) {
            for (String m : REDIRECT_METHODS) {
                if (m.equalsIgnoreCase(method)) {
                    return true;
                }
            }
            return false;
        }
    });
    return clientBuilder;
}

From source file:com.bigdata.rdf.sail.webapp.TestNanoSparqlServer.java

@Override
public void setUp() throws Exception {

    log.warn("Setting up test:" + getName());

    final Properties journalProperties = new Properties();
    {//from  w  w  w  .  j a v a 2s  .co  m
        journalProperties.setProperty(Journal.Options.BUFFER_MODE, BufferMode.MemStore.name());
    }

    // guaranteed distinct namespace for the KB instance.
    namespace = getName() + UUID.randomUUID();

    m_indexManager = new Journal(journalProperties);

    // Properties for the KB instance.  
    final Properties tripleStoreProperties = new Properties();
    {

        tripleStoreProperties.setProperty(BigdataSail.Options.TRUTH_MAINTENANCE, "false");

        tripleStoreProperties.setProperty(BigdataSail.Options.TRIPLES_MODE, "true");

    }

    // Create the triple store instance.
    final AbstractTripleStore tripleStore = createTripleStore(m_indexManager, namespace, tripleStoreProperties);

    // Override namespace.  Do not create the default KB.
    final Map<String, String> initParams = new LinkedHashMap<String, String>();
    {

        initParams.put(ConfigParams.NAMESPACE, namespace);

        initParams.put(ConfigParams.CREATE, "false");

    }

    // Start server for that kb instance.
    m_fixture = NanoSparqlServer.newInstance(0/* port */, m_indexManager, initParams);

    m_fixture.start();

    //        final WebAppContext wac = NanoSparqlServer.getWebApp(m_fixture);
    //
    //        wac.start();
    //
    //        for (Map.Entry<String, String> e : initParams.entrySet()) {
    //
    //            wac.setInitParameter(e.getKey(), e.getValue());
    //
    //        }

    final int port = NanoSparqlServer.getLocalPort(m_fixture);

    // log.info("Getting host address");

    final String hostAddr = NicUtil.getIpAddress("default.nic", "default", true/* loopbackOk */);

    if (hostAddr == null) {

        fail("Could not identify network address for this host.");

    }

    m_rootURL = new URL("http", hostAddr, port, ""/* contextPath */
    ).toExternalForm();

    m_serviceURL = new URL("http", hostAddr, port, BigdataStatics.getContextPath()).toExternalForm();

    if (log.isInfoEnabled())
        log.info("Setup done: \nname=" + getName() + "\nnamespace=" + namespace + "\nrootURL=" + m_rootURL
                + "\nserviceURL=" + m_serviceURL);

    m_cm = DefaultClientConnectionManagerFactory.getInstance().newInstance();

    final DefaultHttpClient httpClient = new DefaultHttpClient(m_cm);
    m_httpClient = httpClient;

    /*
     * Ensure that the client follows redirects using a standard policy.
     * 
     * Note: This is necessary for tests of the webapp structure since the
     * container may respond with a redirect (302) to the location of the
     * webapp when the client requests the root URL.
     */
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy());

    m_repo = new RemoteRepositoryManager(m_serviceURL, m_httpClient, m_indexManager.getExecutorService());

}

From source file:com.googlecode.libautocaptcha.tools.VodafoneItalyTool.java

private void initHttpClient() {
    httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0");
    httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    httpClient.setCookieStore(new BasicCookieStore());
    httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override/* w w w.java 2  s  .  c  o m*/
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                throws ProtocolException {
            boolean isRedirected = super.isRedirected(request, response, context);
            if (!isRedirected && request.getRequestLine().getMethod().equals(HttpPost.METHOD_NAME)
                    && response.getStatusLine().getStatusCode() == 302)
                return true; // allow POST redirection
            return isRedirected;
        }
    });
}