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.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

protected HttpClientContext createHttpClientContextForUser(final CloseableHttpClient httpClient,
        String userName, String password) throws IOException {
    final HttpClientContext context = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    context.setCookieStore(cookieStore);
    HttpUriRequest request = handleLogin(getPageContent(oauth.getLoginFormUrl(), httpClient, context), userName,
            password);// w  ww  .java2  s.c  o  m
    Assert.assertThat(parseAndCloseResponse(httpClient.execute(request, context)),
            containsString("<title>AUTH_RESPONSE</title>"));
    return context;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskXMsgClient.CFAsteriskXMsgClientHttpSchema.java

public boolean connect(String loginId, String password, String clusterName, String tenantName) {
    final String S_ProcName = "connect-full";
    CFTipClientHandler clientHandler = getCFTipClientHandler();
    String deviceName = clientHandler.getDeviceName();
    if (clientContext != null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "clientContext already exists");
    }/*from ww w .j a  v  a  2s.c o m*/
    CookieStore cookieStore = new BasicCookieStore();
    clientContext = HttpClientContext.create();
    clientContext.setCookieStore(cookieStore);

    String rqst = null;

    try {
        clientHandler.requestServerInfo();

        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes("UTF-8"));
        byte[] hash = msgDigest.digest();
        byte[] encodedHash = Base64.encodeBase64(hash);
        byte[] devEncPWHash = clientHandler.encryptWithDevicePrivateKey(encodedHash);

        clientHandler.initSessionKey();

        rqst = CFAsteriskXMsgSchemaMessageFormatter.formatRqstXmlPreamble() + "\n" + "\t"
                + CFAsteriskXMsgSchemaMessageFormatter.formatRqstLogIn("\n\t\t\t", loginId, deviceName,
                        devEncPWHash, clusterName, tenantName)
                + "\n" + CFAsteriskXMsgSchemaMessageFormatter.formatRqstXmlPostamble();
    } catch (NoSuchAlgorithmException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught UnsupportedEncodingException - " + e.getMessage(), e);
    } catch (InvalidKeyException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeyException - " + e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException - " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught IllegalBlockSizeException - " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught BadPaddingException - " + e.getMessage(), e);
    } catch (InvalidKeySpecException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeySpecException - " + e.getMessage(), e);
    } catch (RuntimeException e) {
        clientContext = null;
        throw e;
    }

    try {
        cftipClientHandler.issueLoginRequest(rqst);
    } catch (InvalidAlgorithmParameterException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidAlgorithmParameterException - " + e.getMessage(), e);
    } catch (BadPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught BadPaddingException - " + e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught IllegalBlockSizeException - " + e.getMessage(), e);
    } catch (InvalidKeyException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught InvalidKeyException - " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException - " + e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        clientContext = null;
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException - " + e.getMessage(), e);
    } catch (RuntimeException e) {
        clientContext = null;
        throw e;
    }
    // The response handler sets up the authorization
    ICFTipResponseHandler responseHandler = cftipClientHandler.getResponseHandler();
    CFLibRuntimeException exceptionRaised = responseHandler.getExceptionRaised();
    if (exceptionRaised != null) {
        clientContext = null;
        throw exceptionRaised;
    }
    // If we got a response instead of an exception, we succeeded at logging in.
    return (true);
}

From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java

@Override
public boolean deleteFromStore(APIIdentifier apiId, APIStore store) throws APIManagementException {
    boolean deleted = false;
    if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) {
        String msg = "External APIStore endpoint URL or credentials are not defined. "
                + "Cannot proceed with publishing API to the APIStore - " + store.getDisplayName();
        throw new APIManagementException(msg);
    } else {//from  www.  j  a va2s  .c  o  m
        CookieStore cookieStore = new BasicCookieStore();
        HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        boolean authenticated = authenticateAPIM(store, httpContext);
        if (authenticated) {
            deleted = deleteWSO2Store(apiId, store.getUsername(), store.getEndpoint(), httpContext,
                    store.getDisplayName());
            logoutFromExternalStore(store, httpContext);
        }
        return deleted;
    }
}

From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java

@Override
public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php");
    List<ValidationResultEntry> validationResultEntries = new ArrayList<>();

    try {//from   w  ww  .j  av a  2 s .co m
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("uri", new StringBody(""));
        multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800"));
        multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html"));
        multipartEntity.addPart("validate_file", new StringBody("Check It"));
        multipartEntity.addPart("pastehtml", new StringBody(""));
        multipartEntity.addPart("radio_gid[]", new StringBody("8"));
        multipartEntity.addPart("checkbox_gid[]", new StringBody("8"));
        multipartEntity.addPart("rpt_format", new StringBody("1"));

        request.setEntity(multipartEntity);
        Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext);
        Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors");

        String title = "";
        StringBuilder descriptionSb = new StringBuilder();
        boolean descriptionStarted = false;

        for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) {
            if ("h3".equals(e.getTagName())) {
                if (descriptionStarted) {
                    validationResultEntries.add(new DefaultValidationResultEntry(title,
                            descriptionSb.toString(), ValidationResultEntryType.ERROR));
                }

                title = e.getTextContent();
                descriptionSb.setLength(0);
                descriptionStarted = false;
            } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) {
                if (descriptionStarted) {
                    descriptionSb.append('\n');
                }

                if (extractDescription(e, descriptionSb)) {
                    descriptionStarted = true;
                }
            }
        }

        if (descriptionStarted) {
            validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(),
                    ValidationResultEntryType.ERROR));
        }
    } finally {
        request.releaseConnection();
    }

    return new DefaultValidationResult("WAI Validation", fileToValidate.getName(),
            new DefaultValidationResultType("WAI"), validationResultEntries);
}

From source file:org.coding.git.api.CodingNetConnection.java

private static CookieStore createCookieStore(CodingNetAuthData auth) {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CodingNetAuthData.BasicAuth basicAuth = auth.getBasicAuth();
    if (basicAuth != null) {
        String code = basicAuth.getSid();
        if (code != null) {
            BasicClientCookie cookie = new BasicClientCookie("sid", code);
            cookie.setDomain(".coding.net");
            cookie.setPath("/");
            cookie.setSecure(true);//from   w  w w  . j a  va 2s  .co m
            cookieStore.addCookie(cookie);
        }
    }
    return cookieStore;
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

public static String doPost(String url, String data, String contentType, String encoding) {
    StringBuffer buffer = new StringBuffer();
    InputStreamReader is = null;/*from w  ww .  java  2  s.  c  o  m*/
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        HttpPost post = new HttpPost(url);
        if (data != null) {
            StringEntity entity = new StringEntity(data, encoding);
            post.setHeader("Content-Type", contentType);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:edu.mit.scratch.ScratchSession.java

public ScratchCloudSession getCloudSession(final int projectID) throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);/*from  ww w. ja v a  2  s .  c  o  m*/
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp = null;

    final HttpUriRequest project = RequestBuilder.get()
            .setUri("https://scratch.mit.edu/projects/" + projectID + "/").addHeader("Accept", "text/html")
            .addHeader("Referer", "https://scratch.mit.edu").build();
    try {
        resp = httpClient.execute(project);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
    String projectStr = null;
    try {
        projectStr = Scratch.consume(resp);
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
    final Pattern p = Pattern.compile("cloudToken: '([a-zA-Z0-9\\-]+)'");
    final Matcher m = p.matcher(projectStr);
    m.find();
    final String cloudToken = m.group(1);

    return new ScratchCloudSession(this, cloudToken, projectID);
}

From source file:io.undertow.servlet.test.session.ServletURLRewritingSessionTestCase.java

@Test
public void testURLRewritingWithExistingOldSessionId() throws IOException {
    TestHttpClient client = new TestHttpClient();
    client.setCookieStore(new BasicCookieStore());
    try {//from  www.  j a  v a 2 s.c  o m
        HttpGet get = new HttpGet(
                DefaultServer.getDefaultServerURL() + "/servletContext/foo;jsessionid=foobar");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String url = HttpClientUtils.readResponse(result);
        Header[] header = result.getHeaders(COUNT);
        Assert.assertEquals("0", header[0].getValue());

        get = new HttpGet(url);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        url = HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("1", header[0].getValue());

        get = new HttpGet(url);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        url = HttpClientUtils.readResponse(result);
        header = result.getHeaders(COUNT);
        Assert.assertEquals("2", header[0].getValue());

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.wso2.automation.platform.tests.apim.is.SingleSignOnTestCase.java

@BeforeClass(alwaysRun = true)
public void init() throws APIManagerIntegrationTestException {

    super.init(TestUserMode.SUPER_TENANT_ADMIN);
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    DefaultHttpClient client = new DefaultHttpClient();

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);

    httpClient = new DefaultHttpClient(mgr, client.getParams());

    CookieStore cookieStore = new BasicCookieStore();

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    AutomationContext isContext;/*from   w w  w.  ja va2s .c o m*/
    httpsPublisherUrl = publisherUrls.getWebAppURLHttps() + "publisher";
    httpsStoreUrl = storeUrls.getWebAppURLHttps() + "store";
    try {
        providerName = publisherContext.getContextTenant().getContextUser().getUserName();
    } catch (XPathExpressionException e) {
        log.error(e);
        throw new APIManagerIntegrationTestException("Error while getting server url", e);
    }

    try {
        isContext = new AutomationContext("IS", "SP", TestUserMode.SUPER_TENANT_ADMIN);
        commonAuthUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "commonauth";
        samlSsoEndpointUrl = isContext.getContextUrls().getBackEndUrl().replaceAll("services/", "") + "samlsso";
    } catch (XPathExpressionException e) {
        log.error("Error initializing IS server details", e);
        throw new APIManagerIntegrationTestException("Error initializing IS server details", e);
    }

}