List of usage examples for org.apache.http.impl.client LaxRedirectStrategy LaxRedirectStrategy
LaxRedirectStrategy
From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(/*from w ww . ja v a2 s .c o m*/ new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider).build(); }
From source file:gov.medicaid.screening.dao.impl.MedicaidCertifiedProvidersDAOBean.java
/** * Retrieves all results from the source site. * * @param criteria the search criteria./* w ww . j a va 2 s .co m*/ * @return the providers matched * @throws URISyntaxException if the URL could not be correctly constructed * @throws IOException for any I/O related errors * @throws ServiceException for any other errors encountered */ private SearchResult<ProviderProfile> getAllResults(MedicaidCertifiedProviderSearchCriteria criteria) throws URISyntaxException, IOException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy()); // we need to get a token from the start page, this will be stored in the client HttpGet getFrontPage = new HttpGet(new URIBuilder(getSearchURL()).build()); HttpResponse response = client.execute(getFrontPage); verifyAndAuditCall(getSearchURL(), response); EntityUtils.consume(response.getEntity()); // releases the connection // our client is now valid, pass the criteria to the search page String postSearchURL = Util.replaceLastURLPart(getSearchURL(), "showprovideroutput.cfm"); HttpPost searchPage = new HttpPost(new URIBuilder(postSearchURL).build()); HttpEntity entity = postForm(postSearchURL, client, searchPage, new String[][] { { "ProviderCatagory", criteria.getType() }, { "WhichArea", criteria.getCriteria() }, { "Submit", "Submit" }, { "SelectCounty", "All".equals(criteria.getCriteria()) ? "0" : criteria.getValue() }, { "CityToFind", "All".equals(criteria.getCriteria()) ? "" : criteria.getValue() }, { "ProviderToFind", "All".equals(criteria.getCriteria()) ? "" : criteria.getValue() } }, true); // this now holds the search results, parse every row Document page = Jsoup.parse(EntityUtils.toString(entity)); List<ProviderProfile> allProviders = new ArrayList<ProviderProfile>(); Elements rows = page.select("div#body table tbody tr:gt(0)"); for (Element row : rows) { ProviderProfile profile = parseProfile(row.children()); if (profile != null) { allProviders.add(profile); } } SearchResult<ProviderProfile> results = new SearchResult<ProviderProfile>(); results.setItems(allProviders); return results; }
From source file:com.ittm_solutions.ipacore.IpaApi.java
/** * Returns a http client with reusing connections. * <p>/*from ww w.ja va 2 s. c om*/ * This method uses the http client context and the connection manager to * create a http client. * * @return http client */ private CloseableHttpClient httpClient() { PoolingHttpClientConnectionManager cm = this.connectionManager(); LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy(); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm) .setRedirectStrategy(redirectStrategy).build(); return httpClient; }
From source file:org.fao.geonet.utils.GeonetHttpRequestFactory.java
public HttpClientBuilder getDefaultHttpClientBuilder() { final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setRedirectStrategy(new LaxRedirectStrategy()); builder.disableContentCompression(); synchronized (this) { if (connectionManager == null) { connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(this.numberOfConcurrentRequests); nonShutdownableConnectionManager = new HttpClientConnectionManager() { public void closeExpiredConnections() { connectionManager.closeExpiredConnections(); }/* w ww .j av a2s .com*/ public ConnectionRequest requestConnection(HttpRoute route, Object state) { return connectionManager.requestConnection(route, state); } public void releaseConnection(HttpClientConnection managedConn, Object state, long keepalive, TimeUnit tunit) { connectionManager.releaseConnection(managedConn, state, keepalive, tunit); } public void connect(HttpClientConnection managedConn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException { connectionManager.connect(managedConn, route, connectTimeout, context); } public void upgrade(HttpClientConnection managedConn, HttpRoute route, HttpContext context) throws IOException { connectionManager.upgrade(managedConn, route, context); } public void routeComplete(HttpClientConnection managedConn, HttpRoute route, HttpContext context) throws IOException { connectionManager.routeComplete(managedConn, route, context); } public void shutdown() { // don't shutdown pool } public void closeIdleConnections(long idleTimeout, TimeUnit tunit) { connectionManager.closeIdleConnections(idleTimeout, tunit); } }; } connectionManager.setDefaultSocketConfig( SocketConfig.custom().setSoTimeout((int) TimeUnit.MINUTES.toMillis(3)).build()); builder.setConnectionManager(nonShutdownableConnectionManager); } return builder; }
From source file:cz.opendata.unifiedviews.dpus.ckan.CKANLoader.java
@Override protected void innerExecute() throws DPUException { logger.debug("Querying metadata"); String datasetID = config.getDatasetID(); String orgID = config.getOrgID(); String apiURI = config.getApiUri(); String datasetURI = executeSimpleSelectQuery( "SELECT ?d WHERE {?d a <" + CKANLoaderVocabulary.DCAT_DATASET_CLASS + ">}", "d"); String title = executeSimpleSelectQuery("SELECT ?title WHERE {<" + datasetURI + "> <" + DCTERMS.TITLE + "> ?title FILTER(LANGMATCHES(LANG(?title), \"cs\"))}", "title"); String description = executeSimpleSelectQuery("SELECT ?description WHERE {<" + datasetURI + "> <" + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \"cs\"))}", "description"); String periodicity = executeSimpleSelectQuery("SELECT ?periodicity WHERE {<" + datasetURI + "> <" + DCTERMS.ACCRUAL_PERIODICITY + "> ?periodicity }", "periodicity"); String temporalStart = executeSimpleSelectQuery("SELECT ?temporalStart WHERE {<" + datasetURI + "> <" + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }", "temporalStart"); String temporalEnd = executeSimpleSelectQuery("SELECT ?temporalEnd WHERE {<" + datasetURI + "> <" + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }", "temporalEnd"); String spatial = executeSimpleSelectQuery( "SELECT ?spatial WHERE {<" + datasetURI + "> <" + DCTERMS.SPATIAL + "> ?spatial }", "spatial"); String schemaURL = executeSimpleSelectQuery( "SELECT ?schema WHERE {<" + datasetURI + "> <" + DCTERMS.REFERENCES + "> ?schema }", "schema"); String contactPoint = executeSimpleSelectQuery( "SELECT ?contact WHERE {<" + datasetURI + "> <" + CKANLoaderVocabulary.ADMS_CONTACT_POINT + ">/<" + CKANLoaderVocabulary.VCARD_HAS_EMAIL + "> ?contact }", "contact"); String issued = executeSimpleSelectQuery( "SELECT ?issued WHERE {<" + datasetURI + "> <" + DCTERMS.ISSUED + "> ?issued }", "issued"); String modified = executeSimpleSelectQuery( "SELECT ?modified WHERE {<" + datasetURI + "> <" + DCTERMS.MODIFIED + "> ?modified }", "modified"); String license = executeSimpleSelectQuery( "SELECT ?license WHERE {<" + datasetURI + "> <" + DCTERMS.LICENSE + "> ?license }", "license"); LinkedList<String> themes = new LinkedList<String>(); for (Map<String, Value> map : executeSelectQuery( "SELECT ?theme WHERE {<" + datasetURI + "> <" + CKANLoaderVocabulary.DCAT_THEME + "> ?theme }")) { themes.add(map.get("theme").stringValue()); }//from w ww. ja v a 2 s . c o m LinkedList<String> keywords = new LinkedList<String>(); for (Map<String, Value> map : executeSelectQuery("SELECT ?keyword WHERE {<" + datasetURI + "> <" + CKANLoaderVocabulary.DCAT_KEYWORD + "> ?keyword }")) { keywords.add(map.get("keyword").stringValue()); } LinkedList<String> distributions = new LinkedList<String>(); for (Map<String, Value> map : executeSelectQuery("SELECT ?distribution WHERE {<" + datasetURI + "> <" + CKANLoaderVocabulary.DCAT_DISTRIBUTION + "> ?distribution }")) { distributions.add(map.get("distribution").stringValue()); } boolean exists = false; Map<String, String> resUrlIdMap = new HashMap<String, String>(); Map<String, String> resDistroIdMap = new HashMap<String, String>(); logger.debug("Querying for the dataset in CKAN"); CloseableHttpClient queryClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()) .build(); HttpGet httpGet = new HttpGet(apiURI + "/" + datasetID); CloseableHttpResponse queryResponse = null; try { queryResponse = queryClient.execute(httpGet); if (queryResponse.getStatusLine().getStatusCode() == 200) { logger.info("Dataset found"); exists = true; JSONObject response = new JSONObject(EntityUtils.toString(queryResponse.getEntity())); JSONArray resourcesArray = response.getJSONArray("resources"); for (int i = 0; i < resourcesArray.length(); i++) { try { String id = resourcesArray.getJSONObject(i).getString("id"); String url = resourcesArray.getJSONObject(i).getString("url"); resUrlIdMap.put(url, id); if (resourcesArray.getJSONObject(i).has("distro_url")) { String distro = resourcesArray.getJSONObject(i).getString("distro_url"); resDistroIdMap.put(distro, id); } } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } } } else { String ent = EntityUtils.toString(queryResponse.getEntity()); logger.info("Dataset not found: " + ent); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } catch (ParseException e) { logger.error(e.getLocalizedMessage(), e); } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (queryResponse != null) { try { queryResponse.close(); queryClient.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } } } logger.debug("Creating JSON"); try { JSONObject root = new JSONObject(); JSONArray tags = new JSONArray(); //tags.put(keywords); for (String keyword : keywords) tags.put(keyword); JSONArray resources = new JSONArray(); //JSONObject extras = new JSONObject(); if (!datasetID.isEmpty()) root.put("name", datasetID); root.put("url", datasetURI); root.put("title", title); root.put("notes", description); root.put("maintainer_email", contactPoint); root.put("metadata_created", issued); root.put("metadata_modified", modified); //TODO: Matching? root.put("license_id", "other-open"); root.put("license_link", license); root.put("temporalStart", temporalStart); root.put("temporalEnd", temporalEnd); root.put("accrualPeriodicity", periodicity); root.put("schema", schemaURL); root.put("spatial", spatial); String concatThemes = ""; for (String theme : themes) { concatThemes += theme + " "; } root.put("themes", concatThemes); //Distributions for (String distribution : distributions) { JSONObject distro = new JSONObject(); String dtitle = executeSimpleSelectQuery("SELECT ?title WHERE {<" + distribution + "> <" + DCTERMS.TITLE + "> ?title FILTER(LANGMATCHES(LANG(?title), \"cs\"))}", "title"); String ddescription = executeSimpleSelectQuery("SELECT ?description WHERE {<" + distribution + "> <" + DCTERMS.DESCRIPTION + "> ?description FILTER(LANGMATCHES(LANG(?description), \"cs\"))}", "description"); String dtemporalStart = executeSimpleSelectQuery( "SELECT ?temporalStart WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_STARTDATE + "> ?temporalStart }", "temporalStart"); String dtemporalEnd = executeSimpleSelectQuery("SELECT ?temporalEnd WHERE {<" + distribution + "> <" + DCTERMS.TEMPORAL + ">/<" + CKANLoaderVocabulary.SCHEMA_ENDDATE + "> ?temporalEnd }", "temporalEnd"); String dspatial = executeSimpleSelectQuery( "SELECT ?spatial WHERE {<" + distribution + "> <" + DCTERMS.SPATIAL + "> ?spatial }", "spatial"); String dschemaURL = executeSimpleSelectQuery("SELECT ?schema WHERE {<" + distribution + "> <" + CKANLoaderVocabulary.WDRS_DESCRIBEDBY + "> ?schema }", "schema"); String dschemaType = executeSimpleSelectQuery("SELECT ?schema WHERE {<" + distribution + "> <" + CKANLoaderVocabulary.POD_DISTRIBUTION_DESCRIBREBYTYPE + "> ?schema }", "schema"); String dissued = executeSimpleSelectQuery( "SELECT ?issued WHERE {<" + distribution + "> <" + DCTERMS.ISSUED + "> ?issued }", "issued"); String dmodified = executeSimpleSelectQuery( "SELECT ?modified WHERE {<" + distribution + "> <" + DCTERMS.MODIFIED + "> ?modified }", "modified"); String dlicense = executeSimpleSelectQuery( "SELECT ?license WHERE {<" + distribution + "> <" + DCTERMS.LICENSE + "> ?license }", "license"); String dformat = executeSimpleSelectQuery( "SELECT ?format WHERE {<" + distribution + "> <" + DCTERMS.FORMAT + "> ?format }", "format"); String dwnld = executeSimpleSelectQuery("SELECT ?dwnld WHERE {<" + distribution + "> <" + CKANLoaderVocabulary.DCAT_DOWNLOADURL + "> ?dwnld }", "dwnld"); // RDF SPECIFIC - VOID String sparqlEndpoint = executeSimpleSelectQuery( "SELECT ?sparqlEndpoint WHERE {<" + distribution + "> <" + CKANLoaderVocabulary.VOID_SPARQLENDPOINT + "> ?sparqlEndpoint }", "sparqlEndpoint"); LinkedList<String> examples = new LinkedList<String>(); for (Map<String, Value> map : executeSelectQuery("SELECT ?exampleResource WHERE {<" + distribution + "> <" + CKANLoaderVocabulary.VOID_EXAMPLERESOURCE + "> ?exampleResource }")) { examples.add(map.get("exampleResource").stringValue()); } if (!sparqlEndpoint.isEmpty()) { //Start of Sparql Endpoint resource JSONObject sparqlEndpointJSON = new JSONObject(); sparqlEndpointJSON.put("name", "SPARQL Endpoint"); sparqlEndpointJSON.put("url", sparqlEndpoint); sparqlEndpointJSON.put("format", "api/sparql"); sparqlEndpointJSON.put("resource_type", "api"); if (resUrlIdMap.containsKey(sparqlEndpoint)) sparqlEndpointJSON.put("id", resUrlIdMap.get(sparqlEndpoint)); resources.put(sparqlEndpointJSON); // End of Sparql Endpoint resource } for (String example : examples) { // Start of Example resource text/turtle JSONObject exTurtle = new JSONObject(); exTurtle.put("format", "example/turtle"); exTurtle.put("resource_type", "file"); //exTurtle.put("description","Generated by Virtuoso FCT"); exTurtle.put("name", "Example resource in Turtle"); String exUrl; try { if (sparqlEndpoint.isEmpty()) exUrl = example; else exUrl = sparqlEndpoint + "?query=" + URLEncoder.encode("DESCRIBE <" + example + ">", "UTF-8") + "&output=" + URLEncoder.encode("text/turtle", "UTF-8"); } catch (UnsupportedEncodingException e) { exUrl = ""; logger.error(e.getLocalizedMessage(), e); } exTurtle.put("url", exUrl); if (resUrlIdMap.containsKey(exUrl)) exTurtle.put("id", resUrlIdMap.get(exUrl)); resources.put(exTurtle); // End of text/turtle resource // Start of Example resource html JSONObject exHTML = new JSONObject(); exHTML.put("format", "HTML"); exHTML.put("resource_type", "file"); //exHTML.put("description","Generated by Virtuoso FCT"); exHTML.put("name", "Example resource"); exHTML.put("url", example); if (resUrlIdMap.containsKey(example)) exHTML.put("id", resUrlIdMap.get(example)); resources.put(exHTML); // End of html resource } // END OF RDF VOID SPECIFICS distro.put("name", dtitle); distro.put("description", ddescription); distro.put("license_link", dlicense); distro.put("temporalStart", dtemporalStart); distro.put("temporalEnd", dtemporalEnd); distro.put("describedBy", dschemaURL); distro.put("describedByType", dschemaType); distro.put("format", dformat); distro.put("url", dwnld); distro.put("distro_url", distribution); if (resDistroIdMap.containsKey(distribution)) distro.put("id", resDistroIdMap.get(distribution)); else if (resUrlIdMap.containsKey(dwnld)) distro.put("id", resUrlIdMap.get(dwnld)); distro.put("created", dissued); distro.put("last_modified", dmodified); distro.put("spatial", dspatial); resources.put(distro); } root.put("tags", tags); root.put("resources", resources); //root.put("extras", extras); if (!exists && config.isLoadToCKAN()) { JSONObject createRoot = new JSONObject(); createRoot.put("name", datasetID); createRoot.put("title", title); createRoot.put("owner_org", orgID); logger.debug("Creating dataset in CKAN"); CloseableHttpClient client = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpPost httpPost = new HttpPost(apiURI); httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey())); String json = createRoot.toString(); logger.debug("Creating dataset with: " + json); httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8"))); CloseableHttpResponse response = null; try { response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 201) { logger.info("Dataset created OK"); logger.info("Response: " + EntityUtils.toString(response.getEntity())); } else if (response.getStatusLine().getStatusCode() == 409) { String ent = EntityUtils.toString(response.getEntity()); logger.error("Dataset already exists: " + ent); ContextUtils.sendError(ctx, "Dataset already exists", "Dataset already exists: {0}: {1}", response.getStatusLine().getStatusCode(), ent); } else { String ent = EntityUtils.toString(response.getEntity()); logger.error("Response:" + ent); ContextUtils.sendError(ctx, "Error creating dataset", "Response while creating dataset: {0}: {1}", response.getStatusLine().getStatusCode(), ent); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (response != null) { try { response.close(); client.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); ContextUtils.sendError(ctx, "Error creating dataset", e.getLocalizedMessage()); } } } } String json = root.toString(); File outfile = outFileSimple.create(config.getFilename()); try { FileUtils.writeStringToFile(outfile, json, "UTF-8"); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } if (!ctx.canceled() && config.isLoadToCKAN()) { logger.debug("Posting to CKAN"); CloseableHttpClient client = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder(apiURI + "/" + datasetID); HttpPost httpPost = new HttpPost(uriBuilder.build().normalize()); httpPost.addHeader(new BasicHeader("Authorization", config.getApiKey())); logger.trace(json); httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8"))); CloseableHttpResponse response = null; try { response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { logger.info("Response:" + EntityUtils.toString(response.getEntity())); } else { String ent = EntityUtils.toString(response.getEntity()); logger.error("Response:" + ent); ContextUtils.sendError(ctx, "Error updating dataset", "Response while updating dataset: {0}: {1}", response.getStatusLine().getStatusCode(), ent); } } catch (ClientProtocolException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } finally { if (response != null) { try { response.close(); client.close(); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); ContextUtils.sendError(ctx, "Error updating dataset", e.getLocalizedMessage()); } } } } } catch (JSONException e) { logger.error(e.getLocalizedMessage(), e); } catch (URISyntaxException e) { logger.error(e.getLocalizedMessage(), e); } }
From source file:gov.medicaid.screening.dao.impl.BusinessLienDAOBean.java
/** * Performs a search for all possible results. * * @param criteria The search criteria./*from w w w . j a va 2 s. c om*/ * @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<ProviderProfile> getAllResults(BusinessLienSearchCriteria criteria) throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy()); HttpGet getSearch = new HttpGet(new URIBuilder(getSearchURL()).build()); // to get the cookie HttpResponse response = client.execute(getSearch); verifyAndAuditCall(getSearchURL(), response); Document page = Jsoup.parse(EntityUtils.toString(response.getEntity())); String fullSearchURL = getSearchURL() + "/Business/Search"; HttpPost search = new HttpPost(new URIBuilder(fullSearchURL).build()); List<ProviderProfile> allProfiles = new ArrayList<ProviderProfile>(); HttpEntity entity = postForm(fullSearchURL, client, search, new String[][] { { "BusinessName", Util.defaultString(criteria.getBusinessName()) }, { "FileNumber", Util.defaultString(criteria.getFileNumber()) }, { "Status", criteria.getFilingStatus() == FilingStatus.INACTIVE ? "Inactive" : "Active" }, { "Type", criteria.getScope() == SearchScope.CONTAINS ? "Contains" : "BeginsWith" }, { "submit", "Search" } }, true); page = Jsoup.parse(EntityUtils.toString(entity)); Elements detailLinks = page.select("table.results tr td a"); for (Element detailLink : detailLinks) { String href = detailLink.attr("href"); String detailUrl = getSearchURL() + href; HttpGet getDetail = new HttpGet(detailUrl); response = client.execute(getDetail); verifyAndAuditCall(detailUrl, response); Document profileDetails = Jsoup.parse(EntityUtils.toString(response.getEntity())); allProfiles.add(parseProfile(profileDetails)); } SearchResult<ProviderProfile> searchResult = new SearchResult<ProviderProfile>(); searchResult.setItems(allProfiles); return searchResult; }
From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java
protected CloseableHttpClient constructHttpClient() throws IOException { RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000) .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build(); URL mmsc = new URL(apn.getMmsc()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (apn.hasAuthentication()) { credsProvider.setCredentials(//w w w. j a va 2s .co m new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword())); } return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()) .setRedirectStrategy(new LaxRedirectStrategy()) .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT)) .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config) .setDefaultCredentialsProvider(credsProvider).build(); }
From source file:gov.medicaid.screening.dao.impl.DentistryLicenseDAOBean.java
/** * Performs a search for all possible results. * * @param criteria The search criteria./*from w ww . j a va2s. co m*/ * @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(DentistryLicenseSearchCriteria criteria) throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy()); 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>(); HttpEntity entity = postForm(getSearchURL(), client, search, new String[][] { { "vFirstName", Util.defaultString(criteria.getFirstName()) }, { "vMiddleName", Util.defaultString(criteria.getMiddleName()) }, { "vLastName", Util.defaultString(criteria.getLastName()) }, { "vLicenseNumber", Util.defaultString(criteria.getIdentifier()) }, { "vCity", Util.defaultString(criteria.getCity()) }, { "vLicenseType", criteria.getLicenseType().getName() }, { "ObjectTypeID", "1059" }, { "ObjectID", "40" }, { "__VIEWSTATE", page.select("input[name=__VIEWSTATE]").first().val() }, { "__EVENTVALIDATION", page.select("input[name=__EVENTVALIDATION]").first().val() } }, true); page = Jsoup.parse(EntityUtils.toString(entity)); Elements detailButtons = page.select("table#DataTable table input[type=button]"); for (Element detailButton : detailButtons) { String url = detailButton.attr("onclick"); url = url.replaceFirst("javascript:window.location='./", ""); url = url.substring(0, url.length() - 2); url = url.replaceAll(" ", "+"); // replace spaces 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)); } SearchResult<License> searchResult = new SearchResult<License>(); searchResult.setItems(allLicenses); return searchResult; }
From source file:gov.medicaid.screening.dao.impl.PodiatricMedicineLicenseDAOBean.java
/** * Retrieves all results from the source site. * * @param criteria the search criteria./*from w w w . jav a 2s. c o m*/ * @return the providers matched * @throws URISyntaxException if the URL could not be correctly constructed * @throws IOException for any I/O related errors * @throws ServiceException for any other errors encountered */ private SearchResult<License> getAllResults(String criteria) throws URISyntaxException, IOException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy()); HttpGet getFrontPage = new HttpGet(new URIBuilder(getSearchURL()).build()); HttpResponse response = client.execute(getFrontPage); verifyAndAuditCall(getSearchURL(), response); Document page = Jsoup.parse(EntityUtils.toString(response.getEntity())); HttpPost getSearchPage = new HttpPost(new URIBuilder(getSearchURL()).build()); HttpEntity entity = postForm(getSearchURL(), client, getSearchPage, new String[][] { { "_ctl2:dropAgencyCode", "H7Q" }, { "_ctl2:btnLogin", "Login" }, { "__VIEWSTATE", page.select("#__aspnetForm input[name=__VIEWSTATE]").first().val() } }, true); page = Jsoup.parse(EntityUtils.toString(entity)); HttpPost search = new HttpPost(new URIBuilder(getSearchURL()).build()); entity = postForm(getSearchURL(), client, search, new String[][] { { "_ctl2:txtCriteria", criteria }, { "_ctl2:btnSearch", "Search" }, { "__VIEWSTATE", page.select("#__aspnetForm input[name=__VIEWSTATE]").first().val() } }, true); page = Jsoup.parse(EntityUtils.toString(entity)); List<License> allLicenses = new ArrayList<License>(); Elements rows = page.select("table#_ctl2_dgrdResults tr.DataGrid"); for (Element row : rows) { License license = parseLicense(row.children()); if (license != null) { allLicenses.add(license); } } SearchResult<License> results = new SearchResult<License>(); results.setItems(allLicenses); return results; }
From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java
@Test public void concurrentLoginMultipleUsers() throws Throwable { log.info("*********************************************"); long start = System.currentTimeMillis(); AtomicReference<String> userSessionId = new AtomicReference<>(); LoginTask loginTask = null;//from ww w. j av a2s . c o m try (CloseableHttpClient httpClient = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()).build()) { loginTask = new LoginTask(httpClient, userSessionId, 100, 1, false, Arrays.asList(createHttpClientContextForUser(httpClient, "test-user@localhost", "password"), createHttpClientContextForUser(httpClient, "john-doh@localhost", "password"), createHttpClientContextForUser(httpClient, "roleRichUser", "password"))); run(DEFAULT_THREADS, DEFAULT_CLIENTS_COUNT, loginTask); int clientSessionsCount = testingClient.testing().getClientSessionsCountInUserSession("test", userSessionId.get()); Assert.assertEquals(1 + DEFAULT_CLIENTS_COUNT / 3 + (DEFAULT_CLIENTS_COUNT % 3 <= 0 ? 0 : 1), clientSessionsCount); } finally { long end = System.currentTimeMillis() - start; log.infof("Statistics: %s", loginTask == null ? "??" : loginTask.getHistogram()); log.info("concurrentLoginMultipleUsers took " + (end / 1000) + "s"); log.info("*********************************************"); } }