List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientUtil.java
private static void configureAuthentication(final DefaultHttpClient httpClient, final String ctxPrefix, final RemoteStorageContext ctx, final RemoteAuthenticationSettings ras, final Logger logger, final String authScope) { if (ras != null) { List<String> authorisationPreference = new ArrayList<String>(2); authorisationPreference.add(AuthPolicy.DIGEST); authorisationPreference.add(AuthPolicy.BASIC); Credentials credentials = null;//from w w w . jav a 2s . c o m if (ras instanceof ClientSSLRemoteAuthenticationSettings) { // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras; // TODO - implement this } else if (ras instanceof NtlmRemoteAuthenticationSettings) { final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authorisationPreference.add(0, AuthPolicy.NTLM); logger(logger).info("... {}authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain()); credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()); ctx.putContextObject(ctxPrefix + CTX_KEY_NTLM_IS_IN_USE, Boolean.TRUE); } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; // Using Username/Pwd auth, will not add NTLM logger(logger).info("... {}authentication setup for remote storage with username '{}'", authScope, uras.getUsername()); credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()); } if (credentials != null) { httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authorisationPreference); } }
From source file:org.dasein.cloud.opsource.OpSourceMethod.java
public Document invoke() throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + OpSource.class.getName() + ".invoke()"); }//from w w w.ja v a 2 s .c o m try { URL url = null; try { url = new URL(endpoint); } catch (MalformedURLException e1) { throw new CloudException(e1); } final String host = url.getHost(); final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort(); final String urlStr = url.toString(); DefaultHttpClient httpclient = new DefaultHttpClient(); /** HTTP Authentication */ String uid = new String(provider.getContext().getAccessPublic()); String pwd = new String(provider.getContext().getAccessPrivate()); /** Type of authentication */ List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.BASIC); httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs); httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null), new UsernamePasswordCredentials(uid, pwd)); if (wire.isDebugEnabled()) { wire.debug("--------------------------------------------------------------> " + urlStr); wire.debug(""); } AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr); method.setParams(new BasicHttpParams().setParameter(urlStr, url)); /** Set headers */ method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key)); /** POST/PUT method specific logic */ if (method instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method; String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key); if (requestBody != null) { if (wire.isDebugEnabled()) { wire.debug(requestBody); } AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes()); entity.setContentType(parameters.get(OpSource.Content_Type_Key)); entityEnclosingMethod.setEntity(entity); } else { throw new CloudException("The request body is null for a post request"); } } /** Now parse the xml */ try { HttpResponse httpResponse; int status; if (wire.isDebugEnabled()) { for (org.apache.http.Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } } /** Now execute the request */ APITrace.trace(provider, method.toString() + " " + urlStr); httpResponse = httpclient.execute((HttpUriRequest) method); status = httpResponse.getStatusLine().getStatusCode(); if (wire.isDebugEnabled()) { wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase()); } org.apache.http.Header[] headers = httpResponse.getAllHeaders(); HttpEntity entity = httpResponse.getEntity(); if (wire.isDebugEnabled()) { wire.debug("HTTP xml status code ---------" + status); for (org.apache.http.Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } /** Can not enable this line, otherwise the entity would be empty*/ // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity)); wire.debug("-----------------"); } if (entity == null) { parseError(status, "Empty entity"); } String responseBody = EntityUtils.toString(entity); if (status == HttpStatus.SC_OK) { InputStream input = null; try { input = new ByteArrayInputStream(responseBody.getBytes("UTF-8")); if (input != null) { Document doc = null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input); if (wire.isDebugEnabled()) { try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); String xmlString = sw.toString(); wire.debug(xmlString); } catch (Exception ex) { ex.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); logger.debug(ex.toString(), ex); } return doc; } } catch (IOException e) { logger.error( "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } /* catch( SAXException e ) { throw new CloudException(e); } catch( ParserConfigurationException e ) { throw new InternalException(e); } */ } else if (status == HttpStatus.SC_NOT_FOUND) { throw new CloudException("An internal error occured: The endpoint was not found"); } else { if (responseBody != null) { parseError(status, responseBody); Document parsedError = null; if (!responseBody.contains("<HR")) { parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8"))); if (wire.isDebugEnabled()) { try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(parsedError); trans.transform(source, result); String xmlString = sw.toString(); wire.debug(xmlString); } catch (Exception ex) { ex.printStackTrace(); } } } else logger.debug("Error message was unparsable"); return parsedError; } } } catch (ParseException e) { throw new CloudException(e); } catch (SAXException e) { throw new CloudException(e); } catch (IOException e) { e.printStackTrace(); throw new CloudException(e); } catch (ParserConfigurationException e) { throw new CloudException(e); } finally { httpclient.getConnectionManager().shutdown(); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + OpSource.class.getName() + ".invoke()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------------> " + endpoint); } } return null; }
From source file:org.apache.juddi.v3.client.mapping.wsdl.WSDLLocatorImpl.java
private InputSource getImportFromUrl(String url) { InputSource inputSource = null; DefaultHttpClient httpclient = null; try {/* www . ja v a2s.c om*/ URL url2 = new URL(url); if (!url.toLowerCase().startsWith("http")) { return getImportFromFile(url); } boolean usessl = false; int port = 80; if (url.toLowerCase().startsWith("https://")) { port = 443; usessl = true; } if (url2.getPort() > 0) { port = url2.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(url2.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); inputSource = new InputSource(sr); } finally { httpGet.releaseConnection(); } // InputStream inputStream = importUrl.openStream(); //inputSource = new InputSource(inputStream); latestImportURI = url; } catch (Exception e) { log.error(e.getMessage()); log.debug(e.getMessage(), e); lastException = e; } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return inputSource; }
From source file:org.webservice.fotolia.FotoliaApi.java
/** * Construct and returns a usuable http client * * @param auto_refresh_token//from ww w . j av a 2 s . c om * @return DefaultHttpClient */ private DefaultHttpClient _getHttpClient(final boolean auto_refresh_token) { DefaultHttpClient client; client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(this._api_key, this._getSessionId(auto_refresh_token))); HttpConnectionParams.setConnectionTimeout(client.getParams(), FotoliaApi.API_CONNECT_TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(client.getParams(), FotoliaApi.API_PROCESS_TIMEOUT * 1000); return client; }
From source file:io.github.tavernaextras.biocatalogue.integration.config.BioCataloguePluginConfigurationPanel.java
/** * Saves recent changes to the configuration parameter map. * Some input validation is performed as well. *//*from ww w . ja v a 2s.com*/ private void applyChanges() { // --- BioCatalogue BASE URL --- String candidateBaseURL = tfBioCatalogueAPIBaseURL.getText(); if (candidateBaseURL.length() == 0) { JOptionPane.showMessageDialog(this, "Service Catalogue base URL must not be blank", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } else { try { new URL(candidateBaseURL); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Currently set Service Catalogue instance URL is not valid\n." + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.selectAll(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // check if the base URL has changed from the last saved state if (!candidateBaseURL.equals( configuration.getProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL))) { // Perform various checks on the new URL // Do a GET with "Accept" header set to "application/xml" // We are expecting a 200 OK and an XML doc in return that // contains the BioCataogue version number element. DefaultHttpClient httpClient = new DefaultHttpClient(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).equals("")) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).equals("")) { // Add the proxy username and password to the list of credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } } HttpGet httpGet = new HttpGet(candidateBaseURL); httpGet.setHeader("Accept", APPLICATION_XML_MIME_TYPE); // Execute the request HttpContext localContext = new BasicHttpContext(); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet, localContext); } catch (Exception ex1) { logger.error( "Service Catalogue preferences configuration: Failed to do " + httpGet.getRequestLine(), ex1); // Warn the user JOptionPane.showMessageDialog(this, "Failed to connect to the URL of the Service Catalogue instance.\n" + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); // Release resource httpClient.getConnectionManager().shutdown(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { // HTTP/1.1 200 OK HttpEntity httpEntity = httpResponse.getEntity(); String contentType = httpEntity.getContentType().getValue().toLowerCase().trim(); logger.info( "Service Catalogue preferences configuration: Got 200 OK when testing the Service Catalogue instance by doing " + httpResponse.getStatusLine() + ". Content type of response " + contentType); if (contentType.startsWith(APPLICATION_XML_MIME_TYPE)) { String value = null; Document doc = null; try { value = readResponseBodyAsString(httpEntity).trim(); // Try to read this string into an XML document SAXBuilder builder = new SAXBuilder(); byte[] bytes = value.getBytes("UTF-8"); doc = builder.build(new ByteArrayInputStream(bytes)); } catch (Exception ex2) { logger.error( "Service Catalogue preferences configuration: Failed to build an XML document from the response.", ex2); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response body when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } finally { // Release resource httpClient.getConnectionManager().shutdown(); } // Get the version element from the XML document Attribute apiVersionAttribute = doc.getRootElement().getAttribute(API_VERSION); if (apiVersionAttribute != null) { String apiVersion = apiVersionAttribute.getValue(); String versions[] = apiVersion.split("[.]"); String majorVersion = versions[0]; String minorVersion = versions[1]; try { //String patchVersion = versions[2]; // we are not comparing the patch versions String supportedMajorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[0]; String supportedMinorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[1]; Integer iSupportedMajorVersion = Integer.parseInt(supportedMajorVersion); Integer iMajorVersion = Integer.parseInt(majorVersion); Integer iSupportedMinorVersion = Integer.parseInt(supportedMinorVersion); Integer iMinorVersion = Integer.parseInt(minorVersion); if (!(iSupportedMajorVersion == iMajorVersion && iSupportedMinorVersion <= iMinorVersion)) { // Warn the user JOptionPane.showMessageDialog(this, "The version of the Service Catalogue instance you are trying to connect to is not supported.\n" + "Please change the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } catch (Exception e) { logger.error(e); } } // if null - we'll try to do our best to connect to BioCatalogue anyway } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response content type when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned content type '" + contentType + "'; expected response content type is 'application/xml'."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response content type when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Plugin", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response status code when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned the status code " + httpResponse.getStatusLine().getStatusCode() + "; expected status code is 200 OK."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response status code when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // Warn the user of the changes in the BioCatalogue base URL JOptionPane.showMessageDialog(this, "You have updated the Service Catalogue base URL.\n" + "This does not take effect until you restart Taverna.", "Service catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); } // the new base URL seems to be valid - can save it into config // settings configuration.setProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL, candidateBaseURL); /* // also update the base URL in the BioCatalogueClient BioCatalogueClient.getInstance() .setBaseURL(candidateBaseURL);*/ } }
From source file:com.telefonica.iot.cygnus.backends.http.HttpClientFactory.java
/** * Gets a HTTP client./* w w w .ja v a2 s.co m*/ * @param ssl True if SSL connections are desired. False otherwise * @param krb5Auth. * @return A http client obtained from the (SSL) Connections Manager. */ public DefaultHttpClient getHttpClient(boolean ssl, boolean krb5Auth) { DefaultHttpClient httpClient; if (ssl) { httpClient = new DefaultHttpClient(sslConnectionsManager); } else { httpClient = new DefaultHttpClient(connectionsManager); } // if else if (krb5Auth) { // http://stackoverflow.com/questions/21629132/httpclient-set-credentials-for-kerberos-authentication System.setProperty("java.security.auth.login.config", loginConfFile); System.setProperty("java.security.krb5.conf", krb5ConfFile); System.setProperty("sun.security.krb5.debug", "false"); System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); Credentials jaasCredentials = new Credentials() { @Override public String getPassword() { return null; } // getPassword @Override public Principal getUserPrincipal() { return null; } // getUserPrincipal }; // 'true' means the port is stripped from the principal names SPNegoSchemeFactory spnegoSchemeFactory = new SPNegoSchemeFactory(true); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory); httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), jaasCredentials); } // if return httpClient; }
From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java
private static void addProxyConfig(DefaultHttpClient httpClient) { Properties prop = System.getProperties(); String proxyHost = prop.getProperty("http.proxyHost"); Integer proxyPort = null;/*from w ww. j a v a 2 s. c o m*/ if (prop.getProperty("http.proxyPort") != null) { proxyPort = Integer.parseInt(prop.getProperty("http.proxyPort")); } String proxyUserName = prop.getProperty("http.proxyUser"); String proxyPassword = prop.getProperty("http.proxyPassword"); String proxyDomain = prop.getProperty("http.proxyDomain"); if (proxy != null) { proxyHost = proxy.getProxyHost(); proxyPort = proxy.getProxyPort(); proxyUserName = proxy.getProxyUsername(); proxyPassword = proxy.getProxyPassword(); proxyDomain = proxy.getProxyDomainname(); } if (proxyHost != null && proxyPort > 0) { Logger.debug(String.format("Using the proxy, proxyHost %s and proxyPort %d", proxyHost, proxyPort)); HttpHost proxyServer = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer); if (proxyUserName != null && proxyUserName.trim().length() > 0 && proxyPassword != null && proxyPassword.length() > 0) { Logger.debug("Proxy Username:" + proxyUserName); Logger.debug("Proxy Domain:" + proxyDomain); AuthScope authScope = new AuthScope(proxyHost, proxyPort, null); NTCredentials credentials = new NTCredentials(proxyUserName, proxyPassword, "", proxyDomain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); // Set NTLM authentication List<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPrefs); } } }