List of usage examples for org.apache.http.client AuthCache put
void put(HttpHost host, AuthScheme authScheme);
From source file:org.switchyard.component.resteasy.util.ClientInvoker.java
/** * Create a RESTEasy invoker client./*from w ww . ja va2s.c o m*/ * * @param basePath The base path for the class * @param resourceClass The JAX-RS Resource Class * @param method The JAX-RS Resource Class's method * @param model Configuration model */ public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) { Set<String> httpMethods = IsHttpMethod.getHttpMethods(method); _baseUri = createUri(basePath); if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) { _subResourcePath = createSubResourcePath(basePath, method); } else if (httpMethods == null || httpMethods.size() != 1) { throw RestEasyMessages.MESSAGES .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString()); } _httpMethod = httpMethods.iterator().next(); _resourceClass = resourceClass; _method = method; try { _uri = (UriBuilder) URIBUILDER_CLASS.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException(ie); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } _uri.uri(_baseUri); if (_resourceClass.isAnnotationPresent(Path.class)) { _uri.path(_resourceClass); } if (_method.isAnnotationPresent(Path.class)) { _uri.path(_method); } _providerFactory = new ResteasyProviderFactory(); boolean useBuiltins = true; // use builtin @Provider classes by default if (model.getContextParamsConfig() != null) { Map<String, String> contextParams = model.getContextParamsConfig().toMap(); // Set use builtin @Provider classes String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); if (registerBuiltins != null) { useBuiltins = Boolean.parseBoolean(registerBuiltins); } // Register @Provider classes List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); if (providerClasses != null) { for (Class<?> pc : providerClasses) { _providerFactory.registerProvider(pc); } } List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams); if (interceptors != null) { for (ClientErrorInterceptor interceptor : interceptors) { _providerFactory.addClientErrorInterceptor(interceptor); } } } if (useBuiltins) { _providerFactory.setRegisterBuiltins(true); RegisterBuiltin.register(_providerFactory); } _extractorFactory = new DefaultEntityExtractorFactory(); _extractor = _extractorFactory.createExtractor(_method); _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null); _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null); ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method); // Client executor SchemeRegistry schemeRegistry = new SchemeRegistry(); int port = _baseUri.getPort(); if (_baseUri.getScheme().startsWith("https")) { if (port == -1) { port = 443; } SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig()); if (sslFactory == null) { sslFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory)); } else { if (port == -1) { port = 80; } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory())); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpClient httpClient = new DefaultHttpClient(cm); _executor = new ApacheHttpClient4Executor(httpClient); // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0]; _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType); // Authentication settings if (model.hasAuthentication()) { // Set authentication AuthScope authScope = null; Credentials credentials = null; if (model.isBasicAuth()) { authScope = createAuthScope(model.getBasicAuthConfig().getHost(), model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm()); credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(), model.getBasicAuthConfig().getPassword()); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } else { authScope = createAuthScope(model.getNtlmAuthConfig().getHost(), model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm()); credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(), model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain()); } ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { ProxyModel proxy = model.getProxyConfig(); if (proxy != null) { HttpHost proxyHost = null; if (proxy.getPort() != null) { proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue()); } else { proxyHost = new HttpHost(proxy.getHost(), -1); } if (proxy.getUser() != null) { AuthScope authScope = new AuthScope(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()); AuthCache authCache = new BasicAuthCache(); authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY)); ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } Integer timeout = model.getTimeout(); if (timeout != null) { HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); } }
From source file:com.granita.icloudcalsync.webdav.WebDavResource.java
public WebDavResource(CloseableHttpClient httpClient, URI baseURI, String username, String password, boolean preemptive) { this(httpClient, baseURI); context.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); if (preemptive) { HttpHost host = new HttpHost(baseURI.getHost(), baseURI.getPort(), baseURI.getScheme()); Log.d(TAG, "Using preemptive authentication (not compatible with Digest auth)"); AuthCache authCache = context.getAuthCache(); if (authCache == null) authCache = new BasicAuthCache(); authCache.put(host, new BasicSchemeHC4()); context.setAuthCache(authCache); }//from w ww . jav a 2s . c o m }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {/*w ww . j a v a2s . co m*/ CloseableHttpClient httpclient = HttpClientProperties.createHttpClient(); try { // Read content of config pipe Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG); Node configNode = configDocument.selectSingleNode("//config"); URL theURL = new URL(configNode.valueOf("url")); if (configNode.valueOf("auth-method").equals("basic")) { HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol()); //Authentication support CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configNode.valueOf("username"), configNode.valueOf("password"))); // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context httpContext = HttpClientContext.create(); httpContext.setCredentialsProvider(credsProvider); httpContext.setAuthCache(authCache); } else if (configNode.valueOf("auth-method").equals("form")) { //Sign in. Cookie will be remembered bij httpclient HttpPost authpost = new HttpPost(configNode.valueOf("auth-url")); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username"))); nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password"))); authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse httpResponse = httpclient.execute(authpost); // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode())); } CloseableHttpResponse response; if (configNode.valueOf("method").equals("post")) { // POST HttpPost httpRequest = new HttpPost(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("put")) { // PUT HttpPut httpRequest = new HttpPut(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("delete")) { //DELETE HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("head")) { //HEAD HttpHead httpRequest = new HttpHead(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("options")) { //OPTIONS HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else { //Default = GET HttpGet httpRequest = new HttpGet(configNode.valueOf("url")); String acceptHeader = configNode.valueOf("accept"); if (!acceptHeader.isEmpty()) { httpRequest.addHeader("accept", configNode.valueOf("accept")); } //Add proxy route if needed HttpClientProperties.setProxy(httpRequest, theURL.getHost()); response = executeRequest(httpRequest, httpclient); } try { contentHandler.startDocument(); int status = response.getStatusLine().getStatusCode(); AttributesImpl statusAttr = new AttributesImpl(); statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status)); contentHandler.startElement("", "response", "response", statusAttr); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); if (entity != null && contentType != null) { //logger.info("Contenttype: " + contentType.getValue()); //Read content into inputstream InputStream inStream = entity.getContent(); // output-type = json means: response is json, convert to xml if (configNode.valueOf("output-type").equals("json")) { //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!! //javax.json contains readers to read from an inputstream StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer, "UTF-8"); JSONObject json = JSONObject.fromObject(writer.toString()); parseJSONObject(contentHandler, json); // output-type = xml means: response is xml, keep it } else if (configNode.valueOf("output-type").equals("xml")) { try { XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml } else if (configNode.valueOf("output-type").equals("jsonld")) { try { Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response! Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback()); Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource((String) nquads, configNode.valueOf("url")); ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inJsonStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml } else if (configNode.valueOf("output-type").equals("rdf")) { try { Any23 runner = new Any23(); DocumentSource source; //If contentType = text/html than convert from html to xhtml to handle non-xml style html! logger.info("Contenttype: " + contentType.getValue()); if (configNode.valueOf("tidy").equals("yes") && contentType.getValue().startsWith("text/html")) { org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8", configNode.valueOf("url")); //TODO UTF-8 should be read from response! RDFCleaner cleaner = new RDFCleaner(); org.jsoup.nodes.Document cleandoc = cleaner.clean(doc); cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); cleandoc.outputSettings() .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); cleandoc.outputSettings().charset("UTF-8"); source = new StringDocumentSource(cleandoc.html(), configNode.valueOf("url"), contentType.getValue()); } else { source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"), contentType.getValue()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inAnyStream)); } catch (Exception e) { throw new OXFException(e); } } else { CharArrayWriter writer = new CharArrayWriter(); IOUtils.copy(inStream, writer, "UTF-8"); contentHandler.characters(writer.toCharArray(), 0, writer.size()); } } } contentHandler.endElement("", "response", "response"); contentHandler.endDocument(); } finally { response.close(); } } finally { httpclient.close(); } } catch (Exception e) { throw new OXFException(e); } }
From source file:org.lightcouch.CouchDbClientBase.java
/** * @return {@link DefaultHttpClient} instance. *//*from w w w.j av a 2s . c om*/ private HttpClient createHttpClient(CouchDbProperties props) { DefaultHttpClient httpclient = null; try { SchemeSocketFactory ssf = null; if (props.getProtocol().equals("https")) { TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { trustManager }, null); ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SSLSocket socket = (SSLSocket) ssf.createSocket(null); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); } else { ssf = PlainSocketFactory.getSocketFactory(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf)); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(ccm); host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol()); context = new BasicHttpContext(); // Http params httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout()); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout()); int maxConnections = props.getMaxConnections(); if (maxConnections != 0) { ccm.setMaxTotal(maxConnections); ccm.setDefaultMaxPerRoute(maxConnections); } if (props.getProxyHost() != null) { HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // basic authentication if (props.getUsername() != null && props.getPassword() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()), new UsernamePasswordCredentials(props.getUsername(), props.getPassword())); props.clearPassword(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } // request interceptor httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { if (log.isInfoEnabled()) log.info(">> " + request.getRequestLine()); } }); // response interceptor httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { validate(response); if (log.isInfoEnabled()) log.info("<< Status: " + response.getStatusLine().getStatusCode()); } }); } catch (Exception e) { log.error("Error Creating HTTP client. " + e.getMessage()); throw new IllegalStateException(e); } return httpclient; }
From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java
@Override public String acquire() { // prepare a JSON query to the given TAFMS server JSONObject query = new JSONObject(); try {/* ww w . j a v a 2 s . co m*/ query.put("resourceType", "selenium"); query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0)); String jobName = configuration.getStringValue("tafms.jobName"); if (jobName != null && !"".equals(jobName)) { query.put("jobName", jobName); } } catch (JSONException e) { } // prepare authentication BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password"))); CloseableHttpClient client = HttpClientBuilder.create() .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState() .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build(); String message = null; try { boolean wait; // use preemptive authentication to avoid double connection count AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); URL url = new URL(getTafmsUrl()); HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(), url.getProtocol()); authCache.put(host, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); do { // send a POST request to resource URL HttpPost request = new HttpPost(getTafmsUrl() + "resource"); // attach query as JSON string data request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = null; // fire request response = client.execute(request, localcontext); try { if (response.getStatusLine() == null) { throw new ClientProtocolException("No HTTP status line transmitted"); } message = extractMessage(response); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { LOG.error("Exception when querying TAFMS server for resource. HTTP Status: " + response.getStatusLine().getStatusCode() + ", message: " + message); return null; } JSONObject object = new JSONObject(message); if (object.has("errorMessage")) { LOG.error("TAFMS server reported an error: " + object.get("errorMessage")); return null; } // continue wait? if (object.has("waiting") && object.getBoolean("waiting")) { wait = true; query.put("requestId", object.getString("requestId")); } else { JSONObject resource = object.optJSONObject("resource"); if (resource == null) { LOG.error("TAFMS server response did not provide a resource. Message was: " + message); return null; } String sUrl = resource.getString("url"); hostResourceIds.put(sUrl, object.getString("requestId")); return sUrl; } } finally { IOUtils.closeQuietly(response); } } while (wait); // should never come here return null; } catch (ClientProtocolException e) { LOG.error("Exception in HTTP transmission", e); return null; } catch (IOException e) { LOG.error("Exception in communication with TAFMS server", e); return null; } catch (JSONException e) { LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e); return null; } finally { IOUtils.closeQuietly(client); } }
From source file:de.betterform.connector.http.AbstractHTTPConnector.java
protected void execute(HttpRequestBase httpRequestBase) throws Exception { // (new HttpClient()).executeMethod(httpMethod); //HttpClient client = new HttpClient(); HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams); if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("SSL_CUSTOM_SCHEME"); LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: " + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT)); String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT); if (contextPath != null) { initSSLScheme(contextPath);/*from w w w. j a va 2s . c om*/ } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("context params>>>"); Map map = getContext(); Iterator keys = map.keySet().iterator(); while (keys.hasNext()) { String key = keys.next().toString(); Object value = map.get(key); if (value != null) LOGGER.debug(key + "=" + value.toString()); } LOGGER.debug("<<<end params"); } String username = null; String password = null; String realm = null; //add custom header to signal XFormsFilter to not process this internal request //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true"); httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true"); /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders if (getContext().containsKey(HTTP_REQUEST_HEADERS)) { RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS); // Iterator it = Map headersToAdd = new HashMap(); for (RequestHeader header : httpRequestHeaders.getAllHeaders()) { String headername = header.getName(); String headervalue = header.getValue(); if (headername.equals("username")) { username = headervalue; } else if (headername.equals("password")) { password = headervalue; } else if (headername.equals("realm")) { realm = headervalue; } else { if (headersToAdd.containsKey(headername)) { String formerValue = (String) headersToAdd.get(headername); headersToAdd.put(headername, formerValue + "," + headervalue); } else { if (headername.equals("accept-encoding")) { // do nothing LOGGER.debug("do not add accept-encoding:" + headervalue + " for request"); } else { headersToAdd.put(headername, headervalue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("setting header: " + headername + " value: " + headervalue); } } } } } Iterator keyIterator = headersToAdd.keySet().iterator(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key))); httpRequestBase.setHeader(key, (String) headersToAdd.get(key)); //httpRequestBase.addHeader(key, (String) headersToAdd.get(key)); } } if (httpRequestBase.containsHeader("Content-Length")) { //remove content-length if present httpclient will recalucalte the value. httpRequestBase.removeHeaders("Content-Length"); } if (username != null && password != null) { URI targetURI = null; //targetURI = httpMethod.getURI(); targetURI = httpRequestBase.getURI(); //client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); if (realm == null) { realm = AuthScope.ANY_REALM; } //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); client.getCredentialsProvider() .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(targetURI.getHost()), basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); //Needed? httpMethod.setDoAuthentication(true); } //alternative method for non-tomcat servers if (getContext().containsKey(REQUEST_COOKIE)) { //HttpState state = client.getState(); HttpParams state = client.getParams(); //state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) { Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE); if (cookiesIn[0] != null) { for (int i = 0; i < cookiesIn.length; i++) { Cookie cookie = cookiesIn[i]; //state.addCookie(cookie); client.getCookieStore().addCookie(cookie); } /* Cookie[] cookies = state.getCookies(); Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies); httpMethod.setRequestHeader(cookieOut); client.setState(state); */ List<Cookie> cookies = client.getCookieStore().getCookies(); List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies); Header[] headers = cookieHeaders.toArray(new Header[0]); for (int i = 0; i < headers.length; i++) { httpRequestBase.addHeader(headers[i]); } client.setParams(state); } } else { throw new MalformedCookieException( "Cookies must be passed as org.apache.commons.httpclient.Cookie objects."); } } if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("Using customSSL-Protocol-Handler"); Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) .iterator(); while (schemes.hasNext()) { client.getConnectionManager().getSchemeRegistry().register(schemes.next()); } } if (httpRequestBase.getURI().isAbsolute()) { httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost()); } HttpResponse httpResponse = client.execute(httpRequestBase); statusCode = httpResponse.getStatusLine().getStatusCode(); reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); try { if (statusCode >= 300) { // Allow 302 only if (statusCode != 302) { throw new XFormsInternalSubmitException(statusCode, reasonPhrase, EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } } this.handleHttpMethod(httpResponse); } catch (Exception e) { LOGGER.trace("AbstractHTTPConnector Exception: ", e); try { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } catch (IOException e1) { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR); } } }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java
protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final String url) throws DSSException { final HttpClient client = getHttpClient(url); final String host = httpRequest.getURI().getHost(); final int port = httpRequest.getURI().getPort(); final String scheme = httpRequest.getURI().getScheme(); final HttpHost targetHost = new HttpHost(host, port, scheme); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); try {/*from w w w. j a v a2 s. com*/ final HttpResponse response = client.execute(targetHost, httpRequest, localContext); return response; } catch (IOException e) { throw new DSSException(e); } }
From source file:com.adobe.aem.demo.communities.Loader.java
private static void doDelete(String hostname, String port, String url, String user, String password) { try {//from w w w . j a v a 2 s . c om HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { // Adding the Basic Authentication data to the context for this command AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Composing the root URL for all subsequent requests String postUrl = "http://" + hostname + ":" + port + url; logger.debug("Deleting request as " + user + " with password " + password + " to " + postUrl); HttpDelete request = new HttpDelete(postUrl); httpClient.execute(target, request, localContext); } catch (Exception ex) { logger.error(ex.getMessage()); } finally { httpClient.close(); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java
private Integer doRequest(final HttpRequestBase request) throws ClientProtocolException, IOException, InterruptedException { final CountDownLatch waitForCompletion = new CountDownLatch(1); final URI uri = request.getURI(); final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin")); AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache);/*w w w.j a v a 2 s. c o m*/ final CloseableHttpClient client = HttpClients.createDefault(); final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() { @Override public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { try { final int status = response.getStatusLine().getStatusCode(); // 400 because we return that if you try to delete something that is already deleted // 404 because it's OK if it's already not there if (status >= 200 && status < 300 || status == 400 || status == 404) { EntityUtils.consume(response.getEntity()); return status; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } finally { waitForCompletion.countDown(); } } }; final Integer status = client.execute(targetHost, request, responseHandler, context); waitForCompletion.await(); client.close(); return status; }
From source file:com.ibm.ws.lars.rest.RepositoryContext.java
@Override protected void before() throws InvalidJsonAssetException, IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException { targetHost = new HttpHost(hostname, portNumber, protocol); /* Create the HTTPClient that we use to make all HTTP calls */ HttpClientBuilder b = HttpClientBuilder.create(); // Trust all certificates SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override/*from ww w . ja va2 s.com*/ public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSslcontext(sslContext); // By default, it will verify the hostname in the certificate, which should be localhost // and therefore should match. If we start running these tests against a LARS server on // a different host then we may need disable hostname verification. context = HttpClientContext.create(); httpClient = b.build(); /* * Create the HTTPClientContext with the appropriate credentials. We'll use this whenever we * make an HTTP call. */ if (user != null && password != null) { credentials = new UsernamePasswordCredentials(user, password); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); } /* Clean the repository but only if the client asked us to. */ if (cleanRepository) { cleanRepo(); } }