Example usage for org.apache.http.impl.client DefaultHttpClient setCookieStore

List of usage examples for org.apache.http.impl.client DefaultHttpClient setCookieStore

Introduction

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

Prototype

public synchronized void setCookieStore(final CookieStore cookieStore) 

Source Link

Usage

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

public void doLogout(Cookie cookie) {
    HttpResponse res = null;//from   www  .  j  a v  a2s .co m
    HttpClientFactory f = new HttpClientFactory();
    f.setLoginURL(getCasServerURL());
    DefaultHttpClient client = null;
    client = f.getClient();
    HttpContext localContext = new BasicHttpContext();
    BasicCookieStore cs = new BasicCookieStore();
    cs.addCookie(cookie);

    HttpPost post = new HttpPost(getURL("logout"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    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;
    }
}

From source file:org.xdi.oxauth.ws.rs.SSOWithMultipleBackendServicesHttpTest.java

@Parameters({ "redirectUris", "userId", "userSecret", "redirectUri", "hostnameVerifier" })
@Test/*w  w  w .j a va2 s.c o m*/
public void sessionWorkFlow1(final String redirectUris, final String userId, final String userSecret,
        final String redirectUri, String hostnameVerifier) throws Exception {
    showTitle("sessionWorkFlow1");

    // Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200,
            "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient = createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest1.setAuthUsername(userId);
    authorizationRequest1.setAuthPassword(userSecret);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState("af0ifjsldkj");
    authorizationRequest1.setRequestSessionId(true);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    showClient(authorizeClient1);
    assertEquals(authorizationResponse1.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse1.getStatus());
    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse1.getSessionId(), "The sessionId is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String code1 = authorizationResponse1.getCode();
    String sessionId = authorizationResponse1.getSessionId();

    // TV sends the code to the Backend
    // We don't use httpClient and cookieStore during this call

    ////////////////////////////////////////////////
    //             Backend  1 side. Code 1        //
    ////////////////////////////////////////////////

    // Get the access token
    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse1 = tokenClient1.execAuthorizationCode(code1, redirectUri, clientId,
            clientSecret);

    showClient(tokenClient1);
    assertEquals(tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getEntity(), "The entity is null");
    assertNotNull(tokenResponse1.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse1.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null");

    String accessToken1 = tokenResponse1.getAccessToken();

    // Get the user's claims
    UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken1);

    showClient(userInfoClient1);
    assertEquals(userInfoResponse1.getStatus(), 200,
            "Unexpected response code: " + userInfoResponse1.getStatus());
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.SUBJECT_IDENTIFIER),
            "Unexpected result: subject not found");
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.NAME), "Unexpected result: name not found");
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.GIVEN_NAME),
            "Unexpected result: given_name not found");
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.FAMILY_NAME),
            "Unexpected result: family_name not found");
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.EMAIL), "Unexpected result: email not found");

    ////////////////////////////////////////////////
    //             TV side. Code 2                //
    ////////////////////////////////////////////////

    AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState("af0ifjsldkj");
    authorizationRequest2.setSessionId(sessionId);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient2);
    assertEquals(authorizationResponse2.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse2.getStatus());
    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");
    assertNotNull(authorizationResponse2.getScope(), "The scope is null");

    String code2 = authorizationResponse2.getCode();

    // TV sends the code to the Backend
    // We don't use httpClient and cookieStore during this call

    ////////////////////////////////////////////////
    //             Backend  2 side. Code 2        //
    ////////////////////////////////////////////////

    // Get the access token
    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse2 = tokenClient2.execAuthorizationCode(code2, redirectUri, clientId,
            clientSecret);

    showClient(tokenClient2);
    assertEquals(tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse2.getEntity(), "The entity is null");
    assertNotNull(tokenResponse2.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse2.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse2.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null");

    String accessToken2 = tokenResponse2.getAccessToken();

    // Get the user's claims
    UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken2);

    showClient(userInfoClient2);
    assertEquals(userInfoResponse2.getStatus(), 200,
            "Unexpected response code: " + userInfoResponse2.getStatus());
    assertNotNull(userInfoResponse2.getClaim(JwtClaimName.SUBJECT_IDENTIFIER),
            "Unexpected result: subject not found");
    assertNotNull(userInfoResponse2.getClaim(JwtClaimName.NAME), "Unexpected result: name not found");
    assertNotNull(userInfoResponse2.getClaim(JwtClaimName.GIVEN_NAME),
            "Unexpected result: given_name not found");
    assertNotNull(userInfoResponse2.getClaim(JwtClaimName.FAMILY_NAME),
            "Unexpected result: family_name not found");
    assertNotNull(userInfoResponse2.getClaim(JwtClaimName.EMAIL), "Unexpected result: email not found");
}

From source file:org.xdi.oxauth.ws.rs.SSOWithMultipleBackendServicesHttpTest.java

@Parameters({ "redirectUris", "redirectUri", "userInum", "userEmail", "hostnameVerifier" })
@Test/*from ww w .ja  v a 2s .  c o  m*/
public void sessionWorkFlow2(final String redirectUris, final String redirectUri, final String userInum,
        final String userEmail, final String hostnameVerifier) throws Exception {
    showTitle("sessionWorkFlow2");

    // Register client
    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    RegisterClient registerClient = new RegisterClient(registrationEndpoint);
    registerClient.setRequest(registerRequest);
    RegisterResponse registerResponse = registerClient.exec();

    showClient(registerClient);
    assertEquals(registerResponse.getStatus(), 200,
            "Unexpected response code: " + registerResponse.getEntity());
    assertNotNull(registerResponse.getClientId());
    assertNotNull(registerResponse.getClientSecret());
    assertNotNull(registerResponse.getRegistrationAccessToken());
    assertNotNull(registerResponse.getClientIdIssuedAt());
    assertNotNull(registerResponse.getClientSecretExpiresAt());

    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();

    DefaultHttpClient httpClient = createHttpClient(HostnameVerifierType.fromString(hostnameVerifier));
    CookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);

    // Authorization code flow to authenticate on B1

    AuthorizationRequest authorizationRequest1 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest1.addCustomParameter("mail", userEmail);
    authorizationRequest1.addCustomParameter("inum", userInum);
    authorizationRequest1.getPrompts().add(Prompt.NONE);
    authorizationRequest1.setState("af0ifjsldkj");
    authorizationRequest1.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);
    authorizationRequest1.setRequestSessionId(true);

    AuthorizeClient authorizeClient1 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient1.setRequest(authorizationRequest1);
    AuthorizationResponse authorizationResponse1 = authorizeClient1.exec(clientExecutor);

    showClient(authorizeClient1);
    assertEquals(authorizationResponse1.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse1.getStatus());
    assertNotNull(authorizationResponse1.getLocation(), "The location is null");
    assertNotNull(authorizationResponse1.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse1.getSessionId(), "The session id is null");
    assertNotNull(authorizationResponse1.getState(), "The state is null");
    assertNotNull(authorizationResponse1.getScope(), "The scope is null");

    String authorizationCode1 = authorizationResponse1.getCode();
    String sessionId = authorizationResponse1.getSessionId();

    TokenRequest tokenRequest1 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest1.setCode(authorizationCode1);
    tokenRequest1.setRedirectUri(redirectUri);
    tokenRequest1.setAuthUsername(clientId);
    tokenRequest1.setAuthPassword(clientSecret);
    tokenRequest1.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest1);
    TokenResponse tokenResponse1 = tokenClient1.exec();

    showClient(tokenClient1);
    assertEquals(tokenResponse1.getStatus(), 200, "Unexpected response code: " + tokenResponse1.getStatus());
    assertNotNull(tokenResponse1.getEntity(), "The entity is null");
    assertNotNull(tokenResponse1.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse1.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse1.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse1.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B2 (without sending its credentials)

    AuthorizationRequest authorizationRequest2 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest2.getPrompts().add(Prompt.NONE);
    authorizationRequest2.setState("af0ifjsldkj");
    authorizationRequest2.setSessionId(sessionId);

    AuthorizeClient authorizeClient2 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient2.setRequest(authorizationRequest2);
    AuthorizationResponse authorizationResponse2 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient2);
    assertEquals(authorizationResponse2.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse2.getStatus());
    assertNotNull(authorizationResponse2.getLocation(), "The location is null");
    assertNotNull(authorizationResponse2.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse2.getState(), "The state is null");
    assertNotNull(authorizationResponse2.getScope(), "The scope is null");

    String authorizationCode2 = authorizationResponse2.getCode();

    TokenRequest tokenRequest2 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest2.setCode(authorizationCode2);
    tokenRequest2.setRedirectUri(redirectUri);
    tokenRequest2.setAuthUsername(clientId);
    tokenRequest2.setAuthPassword(clientSecret);
    tokenRequest2.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    tokenClient2.setRequest(tokenRequest2);
    TokenResponse tokenResponse2 = tokenClient2.exec();

    showClient(tokenClient2);
    assertEquals(tokenResponse2.getStatus(), 200, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse2.getEntity(), "The entity is null");
    assertNotNull(tokenResponse2.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse2.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse2.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse2.getRefreshToken(), "The refresh token is null");

    // User wants to authenticate on B3 (without sending its credentials)

    AuthorizationRequest authorizationRequest3 = new AuthorizationRequest(Arrays.asList(ResponseType.CODE),
            clientId, Arrays.asList("openid", "profile", "email"), redirectUri, null);

    authorizationRequest3.getPrompts().add(Prompt.NONE);
    authorizationRequest3.setState("af0ifjsldkj");
    authorizationRequest3.setSessionId(sessionId);

    AuthorizeClient authorizeClient3 = new AuthorizeClient(authorizationEndpoint);
    authorizeClient3.setRequest(authorizationRequest3);
    AuthorizationResponse authorizationResponse3 = authorizeClient2.exec(clientExecutor);

    showClient(authorizeClient3);
    assertEquals(authorizationResponse3.getStatus(), 302,
            "Unexpected response code: " + authorizationResponse3.getStatus());
    assertNotNull(authorizationResponse3.getLocation(), "The location is null");
    assertNotNull(authorizationResponse3.getCode(), "The authorization code is null");
    assertNotNull(authorizationResponse3.getState(), "The state is null");
    assertNotNull(authorizationResponse3.getScope(), "The scope is null");

    String authorizationCode3 = authorizationResponse3.getCode();

    TokenRequest tokenRequest3 = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest3.setCode(authorizationCode3);
    tokenRequest3.setRedirectUri(redirectUri);
    tokenRequest3.setAuthUsername(clientId);
    tokenRequest3.setAuthPassword(clientSecret);
    tokenRequest3.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);

    TokenClient tokenClient3 = new TokenClient(tokenEndpoint);
    tokenClient3.setRequest(tokenRequest3);
    TokenResponse tokenResponse3 = tokenClient3.exec();

    showClient(tokenClient3);
    assertEquals(tokenResponse3.getStatus(), 200, "Unexpected response code: " + tokenResponse3.getStatus());
    assertNotNull(tokenResponse3.getEntity(), "The entity is null");
    assertNotNull(tokenResponse3.getAccessToken(), "The access token is null");
    assertNotNull(tokenResponse3.getExpiresIn(), "The expires in value is null");
    assertNotNull(tokenResponse3.getTokenType(), "The token type is null");
    assertNotNull(tokenResponse3.getRefreshToken(), "The refresh token is null");
}

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

/**
 * @return//from  w  w w  . ja  v  a2 s. co  m
 */
private LoginTicketContainer processInitRequest() {
    LoginTicketContainer processInitRequest = 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();
    HttpPost post = new HttpPost(getURL("login"));
    client.setCookieStore(cs);
    localContext.setAttribute(ClientContext.COOKIE_STORE, cs);
    try {
        res = client.execute(post, localContext);
    } 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;
    }
    InputStream is = null;
    try {
        is = res.getEntity().getContent();
    } catch (IllegalStateException e) {
        AuriusAuthException ex = new AuriusAuthException("IllegalStateException",
                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;
    }
    byte[] buffer = new byte[1024];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int leido = 0;
    try {
        while ((leido = is.read(buffer)) > 0) {
            baos.write(buffer, 0, leido);
        }
    } catch (IOException e) {
        AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e));
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    String html = baos.toString().replace("\n", "").replace("\r", "");
    /*
     * Buscamos los tipos de "input"
     */
    String[] inputs = html.split("<\\s*input\\s+");
    processInitRequest = new LoginTicketContainer();
    for (String input : inputs) {
        String value = null;
        if (null != (value = search(input, "lt"))) {
            processInitRequest.setLoginTicket(value);
        } else if (null != (value = search(input, "execution"))) {
            processInitRequest.setExecution(value);
        }
    }
    /*
     * Obtenemos la session Cookie
     */
    if (client.getCookieStore().getCookies() != null) {
        for (Cookie c : client.getCookieStore().getCookies()) {
            if (getJSessionCookieName().equals(c.getName())) {
                processInitRequest.setSessionCookie(c);
            }
        }
    }
    if (null != baos) {
        try {
            baos.close();
        } catch (IOException e) {
            logger.error("Error al cerrar el OutputStream", e);
        }
    }
    if (null != is) {
        try {
            is.close();
        } catch (IOException e) {
            logger.error("Error al cerrar el InputStream", e);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Obtenido: " + processInitRequest);
    }
    return processInitRequest;
}

From source file:gov.medicaid.screening.dao.impl.NursingLicenseDAOBean.java

/**
 * Performs a search for all possible results.
 *
 * @param criteria The search criteria./*from   w  ww.j  av  a 2 s. c  om*/
 * @param byName flag indicating it is a name search
 * @return the search result for licenses
 *
 * @throws URISyntaxException if an error occurs while building the URL.
 * @throws ClientProtocolException if client does not support protocol used.
 * @throws IOException if an error occurs while parsing response.
 * @throws ParseException if an error occurs while parsing response.
 * @throws ServiceException for any other problems encountered
 */
private SearchResult<License> getAllResults(NursingLicenseSearchCriteria criteria, boolean byName)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient(getLaxSSLConnectionManager());
    client.setRedirectStrategy(new LaxRedirectStrategy());
    client.setCookieStore(loginAsPublicUser());

    HttpGet getSearch = new HttpGet(new URIBuilder(getSearchURL()).build());
    HttpResponse response = client.execute(getSearch);
    verifyAndAuditCall(getSearchURL(), response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));

    HttpPost search = new HttpPost(new URIBuilder(getSearchURL()).build());

    List<License> allLicenses = new ArrayList<License>();

    // switch to search by name screen
    if (byName) {
        HttpEntity entity = postForm(getSearchURL(), client, search,
                new String[][] { { "__EVENTTARGET", "_ctl7_rbtnSearch_1" }, { "__EVENTARGUMENT", "" },
                        { "_ctl7:ddlbLicenseType", "R" }, { "_ctl7:rbtnSearch", "2" },
                        { "_ctl7:txtCheckDigit", "" }, { "_ctl7:txtLicenseNumber", "" },
                        { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() } },
                true);

        page = Jsoup.parse(EntityUtils.toString(entity));
        entity = getResultPage(criteria, client, page, search, "_ctl7:cmdSearch", getSearchURL());
        page = Jsoup.parse(EntityUtils.toString(entity));

        // get the data grid entries
        if (page.select("table#_ctl7_grdSearchResults").size() < 1) {
            throw new ParsingException(ErrorCode.MITA50002.getDesc());
        }

        Elements rows = page.select(GRID_ROW_SELECTOR);
        while (rows.size() > 0) {
            for (Element row : rows) {
                String url = row.select("a").first().attr("href");
                String licenseNo = row.select("td:eq(4)").text();
                HttpGet getDetail = new HttpGet(Util.replaceLastURLPart(getSearchURL(), url));
                response = client.execute(getDetail);
                verifyAndAuditCall(getSearchURL(), response);
                Document licenseDetails = Jsoup.parse(EntityUtils.toString(response.getEntity()));
                allLicenses.add(parseLicense(licenseDetails, licenseNo.substring(0, 1)));
            }
            rows.clear();

            // check for next page
            Element currentPage = page.select("#_ctl7_grdSearchResults tr.TablePager span").first();
            if (getLog() != null) {
                getLog().log(Level.DEBUG, "Current page is: " + currentPage.text());
            }
            Element pageLink = currentPage.nextElementSibling();
            if (pageLink != null && pageLink.hasAttr("href")) {
                if (getLog() != null) {
                    getLog().log(Level.DEBUG, "There are more results, getting the next page.");
                }

                String target = parseEventTarget(pageLink.attr("href"));
                entity = getResultPage(criteria, client, page, search, target, getSearchURL());
                page = Jsoup.parse(EntityUtils.toString(entity));
                rows = page.select(GRID_ROW_SELECTOR);
            }
        }

    } else { // search by license number (site supports only exact match)

        HttpEntity entity = postForm(getSearchURL(), client, search,
                new String[][] { { "__EVENTTARGET", "_ctl7:cmdSearch" }, { "__EVENTARGUMENT", "" },
                        { "_ctl7:ddlbLicenseType", Util.defaultString(criteria.getLicenseType().getName()) },
                        { "_ctl7:rbtnSearch", "1" },
                        { "_ctl7:txtCheckDigit", Util.defaultString(criteria.getCheckDigit()) },
                        { "_ctl7:txtLicenseNumber", Util.defaultString(criteria.getIdentifier()) },
                        { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() } },
                true);

        page = Jsoup.parse(EntityUtils.toString(entity));
        if (page.select("span#lblFormTitle").text().equals("License Details")) {
            String prefLicenseType = criteria.getLicenseType().getName();
            allLicenses.add(parseLicense(page, prefLicenseType));
        }
    }

    SearchResult<License> searchResult = new SearchResult<License>();
    searchResult.setItems(allLicenses);
    return searchResult;
}

From source file:com.nineash.hutsync.client.NetworkUtilities.java

/**
 * Perform 2-way sync with the server-side contacts. We send a request that
 * includes all the locally-dirty contacts so that the server can process
 * those changes, and we receive (and return) a list of contacts that were
 * updated on the server-side that need to be updated locally.
 *
 * @param account The account being synced
 * @param authtoken The authtoken stored in the AccountManager for this
 *            account// w  w  w  .j ava2  s  .c  o  m
 * @param serverSyncState A token returned from the server on the last sync
 * @param dirtyContacts A list of the contacts to send to the server
 * @return A list of contacts that we need to update locally
 */
public static void syncCalendar(Context context, Account account, String authtoken, long serverSyncState)
        throws JSONException, ParseException, IOException, AuthenticationException {
    ArrayList<SerializableCookie> myCookies;
    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient hClient = getHttpClient(context);
    mContentResolver = context.getContentResolver();
    final String[] weeknames = { "rota_this_week", "rota_next_week" };

    long calendar_id = getCalendar(account);
    if (calendar_id == -1) {
        Log.e("CalendarSyncAdapter", "Unable to create HutSync event calendar");
        return;
    }

    try {
        myCookies = (ArrayList<SerializableCookie>) fromString(authtoken);
    } catch (final IOException e) {
        Log.e(TAG, "IOException when expanding authtoken", e);
        return;
    } catch (final ClassNotFoundException e) {
        Log.e(TAG, "ClassNotFoundException when expanding authtoken", e);
        return;
    }

    for (SerializableCookie cur_cookie : myCookies) {
        cookieStore.addCookie(cur_cookie.getCookie());
    }

    hClient.setCookieStore(cookieStore);
    Log.i(TAG, "Syncing to: " + SYNC_CONTACTS_URI);
    HttpGet httpget = new HttpGet(SYNC_CONTACTS_URI);
    final HttpResponse resp = hClient.execute(httpget);
    final String response = EntityUtils.toString(resp.getEntity());
    HashMap<Long, SyncEntry> localEvents = new HashMap<Long, SyncEntry>();
    ArrayList<Event> events = new ArrayList<Event>();
    Pattern p = Pattern.compile("background-color:(#[[a-f][A-F][0-9]]{6})");
    Pattern ps = Pattern
            .compile(".calendar-key span.(\\S+) \\{ background-color:(#[[a-f][A-F][0-9]]{6}); color:#fff; \\}");

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        //check we are still logged in
        //if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        //    Log.e(TAG, "Authentication exception in sending dirty contacts");
        //    throw new AuthenticationException();
        //}

        //if we are logged in
        Map<String, String> shift_types = new HashMap<String, String>();
        int length = weeknames.length;
        Document doc = Jsoup.parse(response);
        String full_name = doc.select("a[href*=" + account.name + "/profile]").first().text();

        AccountManager mAccountManager = AccountManager.get(context);
        Account[] the_accounts = mAccountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
        boolean multiple_accounts = (the_accounts.length > 1);

        Elements the_styles = doc.select("style");
        for (Element the_style : the_styles) {
            String st_txt = the_style.html();
            Matcher ms = ps.matcher(st_txt);
            while (ms.find()) { // Find each match in turn; String can't do this.
                String cname = ms.group(1); // Access a submatch group; String can't do this.
                String ccol = ms.group(2);
                String rname = doc.select("span." + cname).first().text();
                Log.i(TAG, "LOOK: " + cname + ", " + ccol + ", " + rname);
                shift_types.put(ccol, rname);
            }
        }

        for (int w = 0; w < weeknames.length; w++) {

            Elements the_dates = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                    + "] tr.heading th:not(.skipStyles)");
            //for (Element hidden : the_dates) { //0 is Mon, 6 is Sun
            Element the_date = the_dates.first(); //figure out the year for the Monday.
            String str_v = the_date.text();
            String[] str_sub = str_v.split(" ");
            str_sub[1] = str_sub[1].trim();
            String[] date_split = str_sub[1].split("/");
            Calendar c = Calendar.getInstance();
            int this_month = c.get(Calendar.MONTH) + 1;
            int monday_month = Integer.parseInt(date_split[1]);
            int this_year = c.get(Calendar.YEAR);
            int monday_year = this_year;
            if (this_month > monday_month) {
                monday_year++;
            } else if (this_month < monday_month) {
                monday_year--;
            }

            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
            Date date = new Date();
            if (str_v != null && !str_v.isEmpty()) {
                String this_date = str_sub[1] + "/" + monday_year; //we need to figure out the year - sometimes its next year

                try {
                    date = format.parse(this_date);
                } catch (Exception e) {
                    // TODO Auto-generated catch block  
                    e.printStackTrace();
                }
                Log.i(TAG, "Dates: " + this_date + " - " + date);
            }
            //}

            for (int i = 1; i < 8; ++i) { //1 is monday, 7 is sunday
                Elements hiddens = doc.select("div.homepage div.accord-content table[id=" + weeknames[w]
                        + "] td:eq(" + Integer.toString(i) + "):not(.skipStyles) div.timeElem");
                int add_days = i - 1;
                for (Element hidden : hiddens) {
                    String str = hidden.text();
                    if (str != null && !str.isEmpty()) {
                        String style = hidden.attr("style");
                        String bg_col = "";
                        Matcher m = p.matcher(style);
                        if (m.find()) {
                            bg_col = m.group(1); // Access a submatch group; String can't do this.
                        }

                        Log.i(TAG, "Time: " + str + "(" + bg_col + ")");
                        String ev_description = ""; //Location too?
                        if (multiple_accounts)
                            ev_description += full_name + "\n\n";
                        String[] times = str.split(" - ");
                        String[] start_time = times[0].split(":");
                        String[] end_time = times[1].split(":");
                        int add_start_hours = Integer.parseInt(start_time[0]);
                        int add_start_minutes = Integer.parseInt(start_time[1]);
                        int add_finish_hours = Integer.parseInt(end_time[0]);
                        int add_finish_minutes = Integer.parseInt(end_time[1]);
                        String ev_shiftType = "";
                        if (bg_col != null && !bg_col.isEmpty()) {
                            ev_shiftType = (String) shift_types.get(bg_col);
                        } else {
                            ev_shiftType = "Other";
                        }
                        String ev_title = ev_shiftType + " Shift";

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        c.add(Calendar.HOUR_OF_DAY, add_start_hours);
                        c.add(Calendar.MINUTE, add_start_minutes);
                        Date startDate = c.getTime();
                        long ev_id = startDate.getTime();

                        c.setTime(date);
                        c.add(Calendar.DATE, add_days);
                        if (add_finish_hours < add_start_hours) { //shift rolls to next day
                            c.add(Calendar.HOUR_OF_DAY, 24);
                            ev_description += "Shift finishes at " + times[1] + " on the next day\n\n";
                        } else {
                            c.add(Calendar.HOUR_OF_DAY, add_finish_hours);
                            c.add(Calendar.MINUTE, add_finish_minutes);
                        }
                        Date endDate = c.getTime();

                        Event ev = new Event(ev_id, ev_title, startDate, endDate, ev_description, ev_shiftType);
                        events.add(ev);
                        Log.i(TAG, "Event: " + ev);
                    }
                }
            }
        }

        //next merge adjacent shifts
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        Event prev_event = null;
        for (Iterator<Event> it = events.iterator(); it.hasNext();) {
            Event cur_event = it.next();
            if (prev_event != null) {
                if (prev_event.getEndDate().compareTo(cur_event.getStartDate()) == 0) {
                    prev_event.setDescription(prev_event.getDescription() + "Merged consecutive shifts:\n"
                            + timeFormat.format(prev_event.getStartDate()) + " to "
                            + timeFormat.format(prev_event.getEndDate()) + " (" + prev_event.getShiftType()
                            + ")\n" + timeFormat.format(cur_event.getStartDate()) + " to "
                            + timeFormat.format(cur_event.getEndDate()) + " (" + cur_event.getShiftType()
                            + ")\n\n");
                    prev_event.setEndDate(cur_event.getEndDate()); //TODO: only merge if other + FOH/BOH, note times in new description
                    it.remove();
                }
            }
            prev_event = cur_event;
        }

        //next, load local events
        Cursor c1 = mContentResolver.query(
                Events.CONTENT_URI.buildUpon().appendQueryParameter(Events.ACCOUNT_NAME, account.name)
                        .appendQueryParameter(Events.ACCOUNT_TYPE, account.type).build(),
                new String[] { Events._ID, Events._SYNC_ID }, Events.CALENDAR_ID + "=?",
                new String[] { String.valueOf(calendar_id) }, null);
        while (c1 != null && c1.moveToNext()) {
            //if(is_full_sync) {
            //   deleteEvent(context, account, c1.getLong(0));
            //} else {
            SyncEntry entry = new SyncEntry();
            entry.raw_id = c1.getLong(0);
            localEvents.put(c1.getLong(1), entry);
            //}
        }
        c1.close();
        try {
            ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
            for (Event event : events) {

                if (localEvents.containsKey(Long.valueOf(event.getId()))) {
                    SyncEntry entry = localEvents.get(Long.valueOf(event.getId()));
                    operationList.add(updateEvent(calendar_id, account, event, entry.raw_id));
                } else {
                    operationList.add(updateEvent(calendar_id, account, event, -1));
                }

                if (operationList.size() >= 50) {
                    try {
                        mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    operationList.clear();
                }
            }

            if (operationList.size() > 0) {
                try {
                    mContentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return;
        }

    } else {
        Log.e(TAG, "Server error in sending dirty contacts: " + resp.getStatusLine());
        throw new IOException();
    }
}

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

/**
 * @param lt/*from   w w w.ja  va2  s.  c om*/
 * @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:sand.actionhandler.weibo.UdaClient.java

public static String syn(String method, String machineno, String params) {
    String content = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from w w w  .  j  a  v  a2s .  c o m
        httpclient = createHttpClient();
        //      HttpGet httpget = new HttpGet("http://www.broken-server.com/");
        // 

        HttpGet httpget = new HttpGet(SERVER + method + "?no=" + machineno + "&" + params);

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        //           httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        // Execute HTTP request
        //System.out.println("executing request " + httpget.getURI());

        // DefaultHttpClient httpclient = new DefaultHttpClient();
        // cookie store
        CookieStore cookieStore = new BasicCookieStore();

        addCookie(cookieStore);
        // 
        httpclient.setCookieStore(cookieStore);

        logger.info("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

        //            System.out.println("----------------------------------------");
        //            System.out.println(response.getStatusLine());
        //            System.out.println(response.getLastHeader("Content-Encoding"));
        //            System.out.println(response.getLastHeader("Content-Length"));
        //            System.out.println("----------------------------------------");

        HttpEntity entity = response.getEntity();
        //System.out.println(entity.getContentType());

        if (entity != null) {
            content = EntityUtils.toString(entity);
            //                System.out.println(content);
            //                System.out.println("----------------------------------------");
            //                System.out.println("Uncompressed size: "+content.length());
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return content;
}

From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java

public void connect() throws IOException {
    if (!connected) {
        final String userInfo = url.getUserInfo();
        final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals("");

        // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight)
        final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
        final HttpContext httpContext = new BasicHttpContext();

        // Set cookie store, creating a new one if none was provided to us
        if (cookieStore == null)
            cookieStore = new BasicCookieStore();
        httpClient.setCookieStore(cookieStore);

        // Set proxy and host authentication
        if (proxyAuthState != null)
            httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
        if (userInfo != null || isAuthenticationRequestedWithUsername) {

            // Make authentication preemptive; interceptor is added first, as the Authentication header is added
            // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor
            // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find
            // the appropriate AuthState/AuthScheme/Credentials in the HttpContext

            // Don't add the interceptor if we don't want preemptive authentication!
            if (!"false".equals(preemptiveAuthentication)) {
                httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0);
            }//from   ww w.j a  v  a 2  s. com

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            final AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            final Credentials credentials;
            if (userInfo != null) {
                // Set username and optional password specified on URL
                final int separatorPosition = userInfo.indexOf(":");
                String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition);
                String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1);
                // If the username/password contain special character, those character will be encoded, since we
                // are getting this from a URL. Now do the decoding.
                username = URLDecoder.decode(username, "utf-8");
                password = URLDecoder.decode(password, "utf-8");
                credentials = new UsernamePasswordCredentials(username, password);
            } else {
                // Set username and password specified externally
                credentials = domain == null
                        ? new UsernamePasswordCredentials(username, password == null ? "" : password)
                        : new NTCredentials(username, password, url.getHost(), domain);
            }
            credentialsProvider.setCredentials(authScope, credentials);
        }

        // If method has not been set, use GET
        // This can happen e.g. when this connection handler is used from URLFactory
        if (method == null)
            setRequestMethod("GET");

        // Set all headers,
        final boolean skipAuthorizationHeader = userInfo != null || username != null;
        for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) {
            final String currentHeaderName = currentEntry.getKey();
            final String[] currentHeaderValues = currentEntry.getValue();
            for (final String currentHeaderValue : currentHeaderValues) {
                // Skip over Authorization header if user authentication specified
                if (skipAuthorizationHeader && currentHeaderName.toLowerCase()
                        .equals(Connection.AUTHORIZATION_HEADER.toLowerCase()))
                    continue;
                method.addHeader(currentHeaderName, currentHeaderValue);
            }
        }

        // Create request entity with body
        if (method instanceof HttpEntityEnclosingRequest) {

            // Use the body that was set directly, or the result of writing to the OutputStream
            final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null;

            if (body != null) {
                final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison
                if (contentTypeHeader == null)
                    throw new ProtocolException("Can't set request entity: Content-Type header is missing");
                final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body);
                byteArrayEntity.setContentType(contentTypeHeader);
                ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity);
            }
        }

        // Make request
        httpResponse = httpClient.execute(method, httpContext);
        connected = true;
    }
}