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

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

Introduction

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

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientManagerImpl.java

/**
 * Configures the fresh instance of HttpClient for given proxy repository specific needs. Right now it sets
 * appropriate redirect strategy only.//from   ww w . j  a va2 s . com
 */
private void configure(final ProxyRepository proxyRepository, final Builder builder) {
    // set proxy redirect strategy
    builder.getHttpClientBuilder().setRedirectStrategy(new NexusRedirectStrategy());

    // MEXUS-7915: Allow use of circular redirects, if set
    final String proxyHostName = normalizeHostname(proxyRepository);
    if (enableCircularRedirectsForHosts.contains(proxyHostName)) {
        log.info("Allowing circular redirects in proxy {}", proxyRepository);
        builder.getRequestConfigBuilder().setCircularRedirectsAllowed(true); // allow circular redirects
        builder.getRequestConfigBuilder().setMaxRedirects(10); // lessen max redirects from default 50
    }
    // MEXUS-7915: Allow use of cookies, if set
    if (useCookiesForHosts.contains(proxyHostName)) {
        log.info("Allowing cookie use in proxy {}", proxyRepository);
        builder.getHttpClientBuilder().setDefaultCookieStore(new BasicCookieStore()); // in memory only
        builder.getRequestConfigBuilder().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); // emulate browsers
    }
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

/**
 * Cookie key \t value//  w  w w.  j  av a  2  s .co m
 */
private BasicCookieStore getCookieString(String cookieStr) {
    BasicCookieStore cookstore = new BasicCookieStore();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new StringReader(cookieStr));
        for (String line = null; (line = reader.readLine()) != null;) {
            String[] arry = line.split("\t", -1);
            if (arry != null && arry.length == 2) {
                arry[0] = StringUtils.trimToEmpty(arry[0]);
                arry[1] = StringUtils.trimToEmpty(arry[1]);
                cookstore.addCookie(new BasicClientCookie(arry[0], arry[1]));
                System.out.println("cookie : " + Arrays.toString(arry));
            }
        }
        return cookstore;
    } catch (Exception ex) {
        throw new RuntimeException(" Err : " + ex.getMessage(), ex);
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.wso2.carbon.appmgt.impl.publishers.WSO2ExternalAppStorePublisher.java

@Override
public void deleteFromStore(WebApp webApp, AppStore store) throws AppManagementException {
    if (log.isDebugEnabled()) {
        String msg = String.format("Deleting web app : %s from external store : %s ", webApp.getApiName(),
                store.getName());/*from  w  w w  . ja  v a2 s  .c  o  m*/
        log.debug(msg);
    }

    validateStore(store);

    String storeEndpoint = store.getEndpoint();
    HttpClient httpClient = AppManagerUtil.getHttpClient(storeEndpoint);
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    loginToExternalStore(store, httpContext, httpClient);
    deleteFromExternalStore(webApp, store.getUsername(), storeEndpoint, httpContext);
    logoutFromExternalStore(storeEndpoint, httpContext, httpClient);
}

From source file:com.farmafene.commons.cas.LoginTGT.java

/**
 * @param lt// w  ww  .  j  ava2  s  .  com
 * @param user
 * @param password
 * @return
 */
private Cookie doLoginCookie(LoginTicketContainer lt, String user, String password) {
    Cookie doLoginCookie = null;
    HttpResponse res = null;
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(lt.getSessionCookie());
    HttpPost post = new HttpPost(getURL("login"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("lt", lt.getLoginTicket()));
    nameValuePairs.add(new BasicNameValuePair("execution", lt.getExecution()));
    nameValuePairs.add(new BasicNameValuePair("_eventId", "submit"));
    nameValuePairs.add(new BasicNameValuePair("username", user));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        AuriusAuthException ex = new AuriusAuthException("UnsupportedEncodingException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    try {
        res = client.execute(post, localContext);
        if (res.getStatusLine().getStatusCode() != 200) {
            AuriusAuthException ex = new AuriusAuthException("Error");
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
    } catch (ClientProtocolException e) {
        AuriusAuthException ex = new AuriusAuthException("ClientProtocolException",
                AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    if (client.getCookieStore().getCookies() != null) {
        for (Cookie c : client.getCookieStore().getCookies()) {
            if (getCasTGCName().equals(c.getName())) {
                doLoginCookie = c;
                break;
            }
        }
    }
    if (doLoginCookie == null) {
        throw new AuriusAuthException("No se ha logrado el login");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Obtenido: " + doLoginCookie);
    }
    return doLoginCookie;
}

From source file:org.wildfly.elytron.web.undertow.server.FormAuthenticationWithClusteredSSOTest.java

@Test
public void testSingleLogout() throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri())));

    // authenticate on NODE_A
    HttpPost httpAuthenticate = new HttpPost(serverA.createUri("/j_security_check"));
    List<NameValuePair> parameters = new ArrayList<>();

    parameters.add(new BasicNameValuePair("j_username", "ladybird"));
    parameters.add(new BasicNameValuePair("j_password", "Coleoptera"));

    httpAuthenticate.setEntity(new UrlEncodedFormEntity(parameters));

    HttpResponse execute = httpClient.execute(httpAuthenticate);

    assertSuccessfulResponse(execute, "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverB.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverC.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverD.createUri())), "ladybird");
    assertSuccessfulResponse(httpClient.execute(new HttpGet(serverE.createUri())), "ladybird");

    httpClient.execute(new HttpGet(serverB.createUri("/logout")));

    assertLoginPage(httpClient.execute(new HttpGet(serverC.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverB.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverD.createUri())));
    assertLoginPage(httpClient.execute(new HttpGet(serverE.createUri())));
}

From source file:com.ittm_solutions.ipacore.IpaApi.java

/**
 * Returns the http client context used for all connections to the IPA
 * server.//from w  w w. ja va  2 s.  c o m
 * <p>
 * This method initializes the http client context on its first call,
 * subsequent calls return the same instance.
 *
 * @return http client context
 */
private HttpClientContext clientContext() {
    if (hcContext == null) {
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();
        // Create local HTTP context
        hcContext = HttpClientContext.create();
        // Bind custom cookie store to the local context
        hcContext.setCookieStore(cookieStore);
    }

    return hcContext;
}

From source file:com.kynetx.api.java

protected CookieStore fetchCookies() {
    CookieStore toReturn = null;/* ww  w . j  a v a  2  s  . com*/
    int size = 0;

    if (isReadable() || isWritable()) {
        try {
            File path = new File(context.getExternalFilesDir(null), "cookies");
            FileInputStream fin = new FileInputStream(path);
            ObjectInputStream ois = new ObjectInputStream(fin);

            size = ois.readInt();

            toReturn = new BasicCookieStore();

            for (int i = 0; i < size; i++) {
                BasicClientCookie cookie = new BasicClientCookie((String) ois.readObject(),
                        (String) ois.readObject());

                cookie.setDomain((String) ois.readObject());
                cookie.setPath((String) ois.readObject());
                cookie.setVersion(ois.readInt());
                toReturn.addCookie((Cookie) cookie);
            }

            ois.close();
        } catch (Exception e) {
            return null;
        }
    }
    if (size > 0) {
        return toReturn;
    } else {
        return null;
    }
}

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/*from  w w w  . j a va  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;
        }
    });
}