List of usage examples for org.apache.commons.httpclient HttpClient getParams
public HttpClientParams getParams()
From source file:org.archive.modules.credential.HttpAuthenticationCredential.java
@Override public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method, Map<String, String> httpAuthChallenges) { boolean result = false; AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(http.getParams()); try {/*from w w w . ja v a 2 s .c om*/ AuthScheme authScheme = authChallengeProcessor.processChallenge(method.getHostAuthState(), httpAuthChallenges); method.getHostAuthState().setAuthScheme(authScheme); } catch (MalformedChallengeException e) { return result; } catch (AuthenticationException e) { return result; } // Always add the credential to HttpState. Doing this because no way of // removing the credential once added AND there is a bug in the // credentials management system in that it always sets URI root to // null: it means the key used to find a credential is NOT realm + root // URI but just the realm. Unless I set it everytime, there is // possibility that as this thread progresses, it might come across a // realm already loaded but the login and password are from another // server. We'll get a failed authentication that'd be difficult to // explain. // // Have to make a UsernamePasswordCredentials. The httpclient auth code // does an instanceof down in its guts. UsernamePasswordCredentials upc = null; try { upc = new UsernamePasswordCredentials(getLogin(), getPassword()); http.getState().setCredentials( new AuthScope(curi.getUURI().getHost(), curi.getUURI().getPort(), getRealm()), upc); logger.fine("Credentials for realm " + getRealm() + " for CrawlURI " + curi.toString() + " added to request: " + result); http.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Arrays.asList(AuthPolicy.DIGEST, AuthPolicy.BASIC)); result = true; } catch (URIException e) { logger.severe("Failed to parse host from " + curi + ": " + e.getMessage()); } return result; }
From source file:org.archiviststoolkit.plugin.utils.WebServiceHelper.java
/** * Method to generate a handle by using the restful interface to the * handle server. Those handles will be assessable using the url like * <p/>/*w w w . j a v a2 s . com*/ * http://hdl.handle.net/prefix/handle * * @param handleServiceUrl The URL of the Restful handle service * @param handleUrl The url this handle will be bound to i.e. http://some_location/item * @param description A brief description of this handle */ public static String createHandle(String handleServiceUrl, String handleUrl, String description, String userid, String password) throws Exception { String handle = ""; // this is the handle that was returned from server // set the correct url if (handleServiceUrl == null) { handleServiceUrl = RESTFUL_HANDLE_TEST_URL; } // Get the HTTP client and set the authentication credentials String host = getHostFromURL(handleServiceUrl); HttpClient httpclient = new HttpClient(); httpclient.getState().setCredentials(new AuthScope(host, 443, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userid, password)); // do automatic authentication if the server request it. httpclient.getParams().setAuthenticationPreemptive(true); // create the xml that is sent to the restful handle service String xml = getHandleXML(handleUrl, description); // Prepare HTTP post method. PostMethod post = new PostMethod(handleServiceUrl); post.setRequestEntity(new StringRequestEntity(xml, "text/xml", null)); // Execute request try { int statusCode = httpclient.executeMethod(post); // Display status code String statusMessage = "Status code: " + statusCode + "\nStatus text: " + post.getStatusText(); System.out.println(statusMessage); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); // if status code doesn't equal to success throw exception if (statusCode == HttpStatus.SC_CREATED) { handle = getHandleFromXML(post.getResponseBodyAsString()); } else { post.releaseConnection(); throw new Exception(statusMessage); } } finally { // Release current connection to the server post.releaseConnection(); } return handle; }
From source file:org.artifactory.cli.rest.RestClient.java
/** * Returnes an HTTP client object with the given configurations * * @param url Target URL/*from w w w .j a va2s. c om*/ * @param timeout Request timeout * @param credentials For authentication * @return HttpClient - Configured client * @throws Exception */ private static HttpClient getHttpClient(String url, int timeout, Credentials credentials) { HttpConnectionManager connectionManager = new SimpleHttpConnectionManager(); HttpConnectionManagerParams connectionManagerParams = connectionManager.getParams(); //Set the socket connection timeout connectionManagerParams.setConnectionTimeout(3000); HttpClient client = new HttpClient(connectionManager); HttpClientParams clientParams = client.getParams(); //Set the socket data timeout int to = 60000; if (timeout > 0) { to = timeout; } clientParams.setSoTimeout(to); if (credentials != null) { String host; try { host = new URL(url).getHost(); } catch (MalformedURLException mue) { throw new RemoteCommandException("\nAn error has occurred while trying to resolve the given url: " + url + "\n" + mue.getMessage()); } clientParams.setAuthenticationPreemptive(true); AuthScope scope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM); client.getState().setCredentials(scope, credentials); } return client; }
From source file:org.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java
/** * Wrapper that uses HttpProvider with specified timeout, default parserpool and timer * @param sMetadataSource/* w ww . j a va2 s . c om*/ * @param oParserPool * @param oTimer * @return * @throws OAException */ public static MetadataProvider createProviderForURL(String sMetadataSource, int iTimeoutMs) { HttpClient oHttpClient; oHttpClient = new HttpClient(); oHttpClient.getParams().setSoTimeout(iTimeoutMs); return createProviderForURL(sMetadataSource, DEFAULT_PARSERPOOL, DEFAULT_TIMER, oHttpClient); }
From source file:org.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java
/** * Create a new HTTP Metadata Provider from the provided URL and HTTP settings<br/> * An exception is thrown when the provider could not be initiated. * /*from w ww . j av a 2s . co m*/ * @param sMetadataURL * @param sMetadataTimeout * @param oParserPool * @param oMPM * @return * @throws OAException */ public static MetadataProvider newHTTPMetadataProvider(String sId, String sMetadataURL, int iTimeout, ParserPool oParserPool, IMetadataProviderManager oMPM) throws OAException { MetadataProvider oProvider = null; // Check URL format URL oURLTarget = null; try { oURLTarget = new URL(sMetadataURL); } catch (MalformedURLException e) { _oLogger.error("Invalid url for metadata: " + sMetadataURL, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } // Check valid and existing destination (with configured timeout settings) try { URLConnection oURLConnection = oURLTarget.openConnection(); if (iTimeout <= 0) { oURLConnection.setConnectTimeout(3000); oURLConnection.setReadTimeout(3000); } else { oURLConnection.setConnectTimeout(iTimeout); oURLConnection.setReadTimeout(iTimeout); } oURLConnection.connect(); } catch (IOException e) { _oLogger.warn("Could not connect to metadata url: " + sMetadataURL + "(using timout " + (iTimeout == 0 ? "3000" : iTimeout) + "ms)", e); } // Establish dedicated refresh timer: String sTimername = "Metadata_HTTP-" + (oMPM == null ? "" : oMPM.getId() + "-") + sId + "-Timer"; Timer oRefreshTimer = new Timer(sTimername, true); // Establish HttpClient HttpClient oHttpClient = new HttpClient(); if (iTimeout > 0) { // Set configured Timeout settings oHttpClient.getParams().setSoTimeout(iTimeout); } oProvider = MetadataProviderUtil.createProviderForURL(sMetadataURL, oParserPool, oRefreshTimer, oHttpClient); if (oProvider != null) { // Start managing it: if (oMPM != null) { oMPM.setProviderFor(sId, oProvider, oRefreshTimer); } } else { // Unsuccessful creation; clean up created Timer oRefreshTimer.cancel(); } return oProvider; }
From source file:org.asynchttpclient.providers.apache.ApacheAsyncHttpProvider.java
public <T> ListenableFuture<T> execute(Request request, AsyncHandler<T> handler) throws IOException { if (isClose.get()) { throw new IOException("Closed"); }//from w w w. j av a 2 s. c om if (ResumableAsyncHandler.class.isAssignableFrom(handler.getClass())) { request = ResumableAsyncHandler.class.cast(handler).adjustRequestRange(request); } if (config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()) { throw new IOException(String.format("Too many connections %s", config.getMaxTotalConnections())); } if (idleConnectionTimeoutThread != null) { idleConnectionTimeoutThread.shutdown(); idleConnectionTimeoutThread = null; } int requestTimeout = AsyncHttpProviderUtils.requestTimeout(config, request); if (config.getIdleConnectionTimeoutInMs() > 0 && requestTimeout != -1 && requestTimeout < config.getIdleConnectionTimeoutInMs()) { idleConnectionTimeoutThread = new IdleConnectionTimeoutThread(); idleConnectionTimeoutThread.setConnectionTimeout(config.getIdleConnectionTimeoutInMs()); idleConnectionTimeoutThread.addConnectionManager(connectionManager); idleConnectionTimeoutThread.start(); } HttpClient httpClient = new HttpClient(params, connectionManager); Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null) { httpClient.getParams().setAuthenticationPreemptive(realm.getUsePreemptiveAuth()); Credentials defaultcreds = new UsernamePasswordCredentials(realm.getPrincipal(), realm.getPassword()); httpClient.getState().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds); } HttpMethodBase method = createMethod(httpClient, request); ApacheResponseFuture<T> f = new ApacheResponseFuture<T>(handler, requestTimeout, request, method); f.touch(); f.setInnerFuture(config.executorService() .submit(new ApacheClientRunnable<T>(request, handler, method, f, httpClient))); maxConnections.incrementAndGet(); return f; }
From source file:org.bonitasoft.connectors.xwiki.common.XWikiRestClient.java
/** * Update an XWiki MetaData using REST/*from w w w . j a v a 2s. c om*/ * @throws IOException * @throws HttpException */ @SuppressWarnings("deprecation") public boolean updateMetadata(String wikiName, String spaceName, String pageName, String className, String propertyName, String propertyValue, XWikiConnector conn) throws HttpException, IOException { try { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("updateMetadata wikiName=" + wikiName + " spaceName=" + spaceName + " pageName=" + pageName + " className=" + className + " propertyName=" + propertyName + " value=" + propertyValue); } String uri = server + "/xwiki/rest/wikis/" + wikiName + "/spaces/" + spaceName + "/pages/" + pageName + "/objects/" + className + "/0/properties/" + propertyName; if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("PUT " + uri); } HttpClient httpClient = new HttpClient(); JAXBContext context = JAXBContext.newInstance("org.xwiki.rest.model.jaxb"); Unmarshaller unmarshaller = context.createUnmarshaller(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); httpClient.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", "application/xml"); putMethod.setRequestHeader("Content-Type", "text/plain"); putMethod.setRequestBody(propertyValue); httpClient.executeMethod(putMethod); Object result = ""; String returnString = putMethod.getResponseBodyAsString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("HTTP Result: " + returnString); } conn.setResponse(returnString); try { Property prop = (Property) unmarshaller.unmarshal(new StreamSource(new StringReader(returnString))); result = prop.getValue(); boolean status = result.equals(propertyValue); conn.setStatus(status); return status; } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error reading xwiki rest call result", e); conn.setStatus(false); return false; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error in xwiki connector", e); conn.setStatus(false); conn.setResponse("updateMetadata failed with exception: " + e.getMessage()); return false; } }
From source file:org.bonitasoft.connectors.xwiki.common.XWikiRestClient.java
/** * GET an XWiki MetaData using REST// ww w. j a v a 2 s . c o m * @throws IOException * @throws HttpException */ public String getMetadata(String wikiName, String spaceName, String pageName, String className, String propertyName, XWikiConnector conn) throws HttpException, IOException { try { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("getMetadata wikiName=" + wikiName + " spaceName=" + spaceName + " pageName=" + pageName + " className=" + className + " propertyName=" + propertyName); } String uri = server + "/xwiki/rest/wikis/" + wikiName + "/spaces/" + spaceName + "/pages/" + pageName + "/objects/" + className + "/0/properties/" + propertyName; if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("GET " + uri); } HttpClient httpClient = new HttpClient(); JAXBContext context = JAXBContext.newInstance("org.xwiki.rest.model.jaxb"); Unmarshaller unmarshaller = context.createUnmarshaller(); httpClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); httpClient.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); GetMethod getMethod = new GetMethod(uri); getMethod.addRequestHeader("Accept", "application/xml"); httpClient.executeMethod(getMethod); Object result = ""; String returnString = getMethod.getResponseBodyAsString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("HTTP Result: " + returnString); } conn.setResponse(returnString); try { Property prop = (Property) unmarshaller.unmarshal(new StreamSource(new StringReader(returnString))); result = prop.getValue(); conn.setStatus(true); if (result == null) return null; else return result.toString(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error reading xwiki rest call result", e); conn.setStatus(false); return null; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Error in xwiki connector", e); conn.setStatus(false); conn.setResponse("getMetadata failed with exception: " + e.getMessage()); return null; } }
From source file:org.bsc.confluence.xmlrpc.ConfluenceExportDecorator.java
/** * /*from w ww .j av a 2 s .c o m*/ * @param space * @param pageTitle * @param format * @param outputFile * @throws Exception */ public final void exportPage(String space, String pageTitle, ExportFormat format, final java.io.File outputFile) { assert space != null; assert pageTitle != null; assert format != null; assert outputFile != null; if (space == null) { throw new IllegalArgumentException("space is null!"); } if (pageTitle == null) { throw new IllegalArgumentException("pageTitle is null!"); } if (format == null) { throw new IllegalArgumentException("format is null!"); } if (outputFile == null) { throw new IllegalArgumentException("outputFile is null!"); } if (outputFile.exists() && !outputFile.isFile()) { throw new IllegalArgumentException("outputFile is not a file!"); } confluence.getPage(space, pageTitle).thenAccept(p -> { Model.Page page = p.orElseThrow(() -> new RuntimeException(format("page [%s] not found!", pageTitle))); final HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); login(client, String.format("%s?pageId=%s", format.url, page.getId()), (location) -> { final java.net.URI uri = java.net.URI.create(url).resolve(location).normalize(); System.out.printf("==> EXPORT URL [%s]\n", uri.toString()); exportpdf(client, uri.toURL(), outputFile); }); }).exceptionally(ex -> { ex.printStackTrace(); return null; }); }
From source file:org.candlepin.client.DefaultCandlepinClientFacade.java
protected CandlepinConsumerClient clientWithCert() { try {/* w ww .j ava 2s . co m*/ HttpClient httpclient = new HttpClient(); CustomSSLProtocolSocketFactory factory = new CustomSSLProtocolSocketFactory(config, true); setHttpsProtocol(httpclient, factory); httpclient.getParams().setConnectionManagerTimeout(1000); CandlepinConsumerClient client = ProxyFactory.create(CandlepinConsumerClient.class, config.getServerURL(), new ApacheHttpClientExecutor(httpclient)); return client; } catch (Exception e) { throw new ClientException(e); } }