List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java
private void createClient() { log.info("Connecting to Opal: {}", opalURI); DefaultHttpClient httpClient = new DefaultHttpClient(); if (keyStore == null) httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, Boolean.TRUE); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, Collections.singletonList(OpalAuth.CREDENTIALS_HEADER)); httpClient.getParams().setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, OpalClientConnectionManagerFactory.class.getName()); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_MAX_ATTEMPT, false)); httpClient.getAuthSchemes().register(OpalAuth.CREDENTIALS_HEADER, new OpalAuthScheme.Factory()); try {// w ww . j a v a 2 s . c om httpClient.getConnectionManager().getSchemeRegistry() .register(new Scheme("https", HTTPS_PORT, getSocketFactory())); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } client = enableCaching(httpClient); ctx = new BasicHttpContext(); ctx.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore()); }
From source file:org.oscarehr.fax.core.FaxStatusUpdater.java
public void updateStatus() { List<FaxJob> faxJobList = faxJobDao.getInprogressFaxesByJobId(); FaxConfig faxConfig;//from w w w . ja v a2s . com DefaultHttpClient client = new DefaultHttpClient(); FaxJob faxJobUpdated; log.info("CHECKING STATUS OF " + faxJobList.size() + " FAXES"); for (FaxJob faxJob : faxJobList) { faxConfig = faxConfigDao.getConfigByNumber(faxJob.getFax_line()); if (faxConfig == null) { log.error("Could not find faxConfig. Has the fax number changed?"); } else if (faxConfig.isActive()) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(faxConfig.getSiteUser(), faxConfig.getPasswd())); HttpGet mGet = new HttpGet(faxConfig.getUrl() + "/" + faxJob.getJobId()); mGet.setHeader("accept", "application/json"); mGet.setHeader("user", faxConfig.getFaxUser()); mGet.setHeader("passwd", faxConfig.getFaxPasswd()); try { HttpResponse response = client.execute(mGet); log.info("RESPONSE: " + response.getStatusLine().getStatusCode()); mGet.releaseConnection(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = response.getEntity(); String content = EntityUtils.toString(httpEntity); ObjectMapper mapper = new ObjectMapper(); faxJobUpdated = mapper.readValue(content, FaxJob.class); //faxJobUpdated = (FaxJob) JSONObject.toBean(jsonObject, FaxJob.class); faxJob.setStatus(faxJobUpdated.getStatus()); faxJob.setStatusString(faxJobUpdated.getStatusString()); log.info("UPDATED FAX JOB ID " + faxJob.getJobId() + " WITH STATUS " + faxJob.getStatus()); faxJobDao.merge(faxJob); } else { log.error("WEB SERVICE RESPONDED WITH " + response.getStatusLine().getStatusCode(), new IOException()); } } catch (ClientProtocolException e) { log.error("HTTP WS CLIENT ERROR", e); } catch (IOException e) { log.error("IO ERROR", e); } } } }
From source file:org.opencastproject.workflow.handler.mediapackagepost.MediaPackagePostOperationHandler.java
/** * {@inheritDoc}//from www .j a va2 s. c om * * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance, * JobContext) */ public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException { // get configuration WorkflowOperationInstance currentOperation = workflowInstance.getCurrentOperation(); Configuration config = new Configuration(currentOperation); MediaPackage mp = workflowInstance.getMediaPackage(); /* Check if we need to replace the Mediapackage we got with the published * Mediapackage from the Search Service */ if (config.mpFromSearch) { SearchQuery searchQuery = new SearchQuery(); searchQuery.withId(mp.getIdentifier().toString()); SearchResult result = searchService.getByQuery(searchQuery); if (result.size() != 1) { throw new WorkflowOperationException("Received multiple results for identifier" + "\"" + mp.getIdentifier().toString() + "\" from search service. "); } logger.info("Getting Mediapackage from Search Service"); mp = result.getItems()[0].getMediaPackage(); } try { logger.info("Submitting \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") as " + config.getFormat().name() + " to " + config.getUrl().toString()); // serialize MediaPackage to target format OutputStream serOut = new ByteArrayOutputStream(); MediaPackageParser.getAsXml(mp, serOut, false); String mpStr = serOut.toString(); serOut.close(); if (config.getFormat() == Configuration.Format.JSON) { JSONObject json = XML.toJSONObject(mpStr); mpStr = json.toString(); if (mpStr.startsWith("{\"ns2:")) { mpStr = (new StringBuilder()).append("{\"").append(mpStr.substring(6)).toString(); } } // Log mediapackge if (config.debug()) { logger.info(mpStr); } // constrcut message body List<NameValuePair> data = new ArrayList<NameValuePair>(); data.add(new BasicNameValuePair("mediapackage", mpStr)); data.addAll(config.getAdditionalFields()); // construct POST HttpPost post = new HttpPost(config.getUrl()); post.setEntity(new UrlEncodedFormEntity(data, config.getEncoding())); // execute POST DefaultHttpClient client = new DefaultHttpClient(); // Handle authentication if (config.authenticate()) { URL targetUrl = config.getUrl().toURL(); client.getCredentialsProvider().setCredentials( new AuthScope(targetUrl.getHost(), targetUrl.getPort()), config.getCredentials()); } HttpResponse response = client.execute(post); // throw Exception if target host did not return 200 int status = response.getStatusLine().getStatusCode(); if (status == 200) { if (config.debug()) { logger.info("Successfully submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": 200 OK"); } } else if (status == 418) { logger.warn("Submitted \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + ") to " + config.getUrl().toString() + ": The target claims to be a teapot. " + "The Reason for this is probably an insane programmer."); } else { throw new WorkflowOperationException( "Faild to submit \"" + mp.getTitle() + "\" (" + mp.getIdentifier().toString() + "), " + config.getUrl().toString() + " answered with: " + Integer.toString(status)); } } catch (Exception e) { if (e instanceof WorkflowOperationException) { throw (WorkflowOperationException) e; } else { throw new WorkflowOperationException(e); } } return createResult(mp, Action.CONTINUE); }
From source file:cm.aptoide.pt.RssHandler.java
private void getIcon(String uri, String name) { String url = mserver + "/" + uri; String file = mctx.getString(R.string.icons_path) + name; /*File exists = new File(file); if(exists.exists()){/*ww w . j a v a 2 s .c om*/ return; }*/ try { FileOutputStream saveit = new FileOutputStream(file); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(url); if (requireLogin) { URL mUrl = new URL(url); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(usern, passwd)); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { return; } else if (mHttpResponse.getStatusLine().getStatusCode() == 403) { return; } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } } catch (IOException e) { } catch (IllegalArgumentException e) { } }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);//from w w w .ja va 2 s .c om TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }
From source file:fr.eolya.utils.http.HttpLoader.java
private static HttpClient setProxy(DefaultHttpClient httpClient, String url, String proxyHost, String proxyPort, String proxyExclude, String proxyUser, String proxyPassword) { boolean exclude = false; if (StringUtils.isNotEmpty(proxyExclude)) { String[] aProxyExclude = proxyExclude.split(","); for (int i = 0; i < aProxyExclude.length; i++) aProxyExclude[i] = aProxyExclude[i].trim(); try {//from w w w . jav a 2 s . c o m URL u = new URL(url); if (Arrays.asList(aProxyExclude).contains(u.getHost())) { exclude = true; } } catch (MalformedURLException e) { exclude = true; } } if (!exclude && StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)) { if (StringUtils.isNotEmpty(proxyUser) && StringUtils.isNotEmpty(proxyPassword)) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, Integer.valueOf(proxyPort)), new UsernamePasswordCredentials(proxyUser, proxyPassword)); } HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort)); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } else { httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); } return httpClient; }
From source file:org.apache.juddi.v3.client.mapping.wadl.WADL2UDDI.java
/** * Parses a web accessible WADL file//w w w . j a v a2 s.com * @param weburl * @param username * @param password * @param ignoreSSLErrors if true, SSL errors are ignored * @return a non-null "Application" object, represeting a WADL's application root XML * Sample code:<br> * <pre> * Application app = WADL2UDDI.parseWadl(new URL("http://server/wsdl.wsdl"), "username", "password", * clerkManager.getClientConfig().isX_To_Wsdl_Ignore_SSL_Errors() ); * </pre> */ public static Application parseWadl(URL weburl, String username, String password, boolean ignoreSSLErrors) { DefaultHttpClient httpclient = null; Application unmarshal = null; try { String url = weburl.toString(); if (!url.toLowerCase().startsWith("http")) { return parseWadl(weburl); } boolean usessl = false; int port = 80; if (url.toLowerCase().startsWith("https://")) { port = 443; usessl = true; } if (weburl.getPort() > 0) { port = weburl.getPort(); } if (ignoreSSLErrors && usessl) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", port, new MockSSLSocketFactory())); ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(cm); } else { httpclient = new DefaultHttpClient(); } if (username != null && username.length() > 0 && password != null && password.length() > 0) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(weburl.getHost(), port), new UsernamePasswordCredentials(username, password)); } HttpGet httpGet = new HttpGet(url); try { HttpResponse response1 = httpclient.execute(httpGet); //System.out.println(response1.getStatusLine()); // HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed ResponseHandler<String> responseHandler = new BasicResponseHandler(); String handleResponse = responseHandler.handleResponse(response1); StringReader sr = new StringReader(handleResponse); unmarshal = JAXB.unmarshal(sr, Application.class); } finally { httpGet.releaseConnection(); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return unmarshal; }
From source file:com.puppetlabs.geppetto.injectable.eclipse.impl.EclipseHttpClientProvider.java
@Override public HttpClient get() { HttpParams params = new BasicHttpParams(); if (connectonTimeout != null) HttpConnectionParams.setConnectionTimeout(params, connectonTimeout.intValue()); if (soTimeout != null) HttpConnectionParams.setSoTimeout(params, soTimeout.intValue()); DefaultHttpClient httpClient = new DefaultHttpClient(params); final SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); if (sslSocketFactory != null) schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); httpClient.setRoutePlanner(new ProxiedRoutePlanner(schemeRegistry)); for (IProxyData proxyData : Activator.getInstance().getProxyService().getProxyData()) { String user = proxyData.getUserId(); String pwd = proxyData.getPassword(); if (user != null || pwd != null) httpClient.getCredentialsProvider().setCredentials( new AuthScope(proxyData.getHost(), proxyData.getPort()), new UsernamePasswordCredentials(user, pwd)); }//from w w w. jav a2s . c o m return httpClient; }