List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:com.openx.oauth.client.Helper.java
/** * Validates the access token with the API * @param domain// w w w . j av a2s . co m * @param token * @param path * @return success or fail * @throws IOException */ public boolean validateToken(String domain, String token, String path) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); OpenXRedirectStrategy dsr = new OpenXRedirectStrategy(); httpclient.setRedirectStrategy(dsr); if (cookieStore == null) { createCookieStore(domain, token); } httpclient.setCookieStore(cookieStore); HttpPut httpput = new HttpPut(domain + path + "session/validate"); HttpResponse response = httpclient.execute(httpput); httpclient.getConnectionManager().shutdown(); boolean valid = true; if (response.getStatusLine().getStatusCode() != 200) { valid = false; } return valid; }
From source file:org.deegree.protocol.ows.http.OwsHttpClientImpl.java
@Override public OwsHttpResponse doPost(URL endPoint, String contentType, StreamBufferStore body, Map<String, String> headers) throws IOException { OwsHttpResponse response = null;//from ww w.java2s .co m try { HttpPost httpPost = new HttpPost(endPoint.toURI()); DefaultHttpClient httpClient = getInitializedHttpClient(endPoint); LOG.debug("Performing POST request on " + endPoint); LOG.debug("post size: " + body.size()); InputStreamEntity entity = new InputStreamEntity(body.getInputStream(), (long) body.size()); entity.setContentType(contentType); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); response = new OwsHttpResponseImpl(httpResponse, httpClient.getConnectionManager(), endPoint.toString()); } catch (Throwable e) { String msg = "Error performing POST request on '" + endPoint + "': " + e.getMessage(); throw new IOException(msg); } return response; }
From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java
@Test public void testUnprotectedResource() throws Exception { URL url = new URL(urlStr + "notProtected"); DefaultHttpClient httpclient = null; try {//from w w w . j ava 2 s . com httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(404, response.getStatusLine().getStatusCode()); } finally { // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java
@Test public void testProtectedResource() throws Exception { URL url = new URL(urlStr + "onlyManagers"); DefaultHttpClient httpclient = null; try {//from w w w. ja v a 2s . c o m httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); HttpResponse response = httpclient.execute(httpget); assertEquals(401, response.getStatusLine().getStatusCode()); } finally { // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java
public LDClient(ClientConfiguration config) { log.info("Initialising Linked Data Client Service ..."); this.config = config; endpoints = new ArrayList<>(); for (Endpoint endpoint : defaultEndpoints) { endpoints.add(endpoint);/* w w w . j a va 2s . com*/ } endpoints.addAll(config.getEndpoints()); Collections.sort(endpoints); if (log.isInfoEnabled()) { for (Endpoint endpoint : endpoints) { log.info("- LDClient Endpoint: {}", endpoint.getName()); } } providers = new ArrayList<>(); for (DataProvider provider : defaultProviders) { providers.add(provider); } providers.addAll(config.getProviders()); if (log.isInfoEnabled()) { for (DataProvider provider : providers) { log.info("- LDClient Provider: {}", provider.getName()); } } retrievalSemaphore = new Semaphore(config.getMaxParallelRequests()); if (config.getHttpClient() != null) { log.debug("Using HttpClient provided in the configuration"); this.client = config.getHttpClient(); } else { log.debug("Creating default HttpClient based on the configuration"); HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient"); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", 443, sf)); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(20); cm.setDefaultMaxPerRoute(10); DefaultHttpClient client = new DefaultHttpClient(cm, httpParams); client.setRedirectStrategy(new LMFRedirectStrategy()); client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler()); idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager()); idleConnectionMonitorThread.start(); this.client = client; } }
From source file:org.carrot2.util.httpclient.HttpClientFactoryTest.java
/** * Verify that the connection timeout is working. */// w ww . j a va2s. c om @Test public void testTimeOut() throws Exception { DefaultHttpClient client = HttpClientFactory.getTimeoutingClient(500); HttpGet request = new HttpGet("http://localhost:" + serverSocket.getLocalPort()); long start = System.currentTimeMillis(); try { client.execute(request); Assert.fail(); } catch (ConnectTimeoutException e) { // Expected. This is thrown if TCP connection fails into a // firewall deadhole, for example. } catch (SocketTimeoutException e) { // Expected. This is thrown if no data appears on input within // the given timeout range. } finally { client.getConnectionManager().shutdown(); } long end = System.currentTimeMillis(); assertThat(end - start).as("Timeout").isGreaterThanOrEqualTo(500); }
From source file:com.pm.myshop.controller.FinanceController.java
@RequestMapping(value = "/addFinance", method = RequestMethod.GET) public @ResponseBody String authenticateCard(@RequestParam("cardNo") String cardNo, @RequestParam("price") double price) throws IOException { System.out.println("CALL FINANCE APPLICATIOn"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet("http://localhost:8080/Finance/add?cardNo=" + cardNo + "&price=" + price); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { session.setAttribute("cardvalidation", "fail"); return "fail"; }//from w ww . j a va2 s .co m BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { session.setAttribute("cardvalidation", output); return output; } httpClient.getConnectionManager().shutdown(); session.setAttribute("cardvalidation", "fail"); return "fail"; }
From source file:org.xwiki.extension.repository.xwiki.internal.resources.ExtensionVersionFileRESTResource.java
private ResponseBuilder downloadLocalExtension(String extensionId, String extensionVersion) throws ResolveException, IOException, QueryException, XWikiException { XWikiDocument extensionDocument = getExistingExtensionDocumentById(extensionId); checkRights(extensionDocument);/* ww w . j ava 2s . c om*/ BaseObject extensionObject = getExtensionObject(extensionDocument); BaseObject extensionVersionObject = getExtensionVersionObject(extensionDocument, extensionVersion); ResponseBuilder response = null; ResourceReference resourceReference = this.repositoryManager.getDownloadReference(extensionDocument, extensionVersionObject); if (ResourceType.ATTACHMENT.equals(resourceReference.getType())) { // It's an attachment AttachmentReference attachmentReference = this.attachmentResolver .resolve(resourceReference.getReference(), extensionDocument.getDocumentReference()); XWikiContext xcontext = getXWikiContext(); XWikiDocument document = xcontext.getWiki().getDocument(attachmentReference.getDocumentReference(), xcontext); checkRights(document); XWikiAttachment xwikiAttachment = document.getAttachment(attachmentReference.getName()); response = getAttachmentResponse(xwikiAttachment); } else if (ResourceType.URL.equals(resourceReference.getType())) { // It's an URL URL url = new URL(resourceReference.getReference()); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "XWikiExtensionRepository"); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); HttpGet getMethod = new HttpGet(url.toString()); HttpResponse subResponse; try { subResponse = httpClient.execute(getMethod); } catch (Exception e) { throw new IOException("Failed to request [" + getMethod.getURI() + "]", e); } response = Response.status(subResponse.getStatusLine().getStatusCode()); // TODO: find a proper way to do a perfect proxy of the URL without directly using Restlet classes. // Should probably use javax.ws.rs.ext.MessageBodyWriter HttpEntity entity = subResponse.getEntity(); InputRepresentation content = new InputRepresentation(entity.getContent(), new MediaType(entity.getContentType().getValue()), entity.getContentLength()); String type = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE); Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(extensionId + '-' + extensionVersion + '.' + type); content.setDisposition(disposition); response.entity(content); } else if (ExtensionResourceReference.TYPE.equals(resourceReference.getType())) { ExtensionResourceReference extensionResource; if (resourceReference instanceof ExtensionResourceReference) { extensionResource = (ExtensionResourceReference) resourceReference; } else { extensionResource = new ExtensionResourceReference(resourceReference.getReference()); } response = downloadRemoteExtension(extensionResource); } else { throw new WebApplicationException(Status.NOT_FOUND); } return response; }
From source file:com.groupon.jenkins.util.HttpPoster.java
public String post(String url, Map postData) throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); try {/* w w w. j a va2 s.co m*/ post.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(postData))); HttpResponse response = httpclient.execute(post); HttpHost proxy = getProxy(post); if (proxy != null) { httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException(response.getStatusLine().toString()); } return getResponse(response); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:it.attocchi.utils.HttpClientUtils.java
/** * /*from w w w .ja v a 2s . co m*/ * @param url * un url dove scaricare il file * @param urlFileNameParam * specifica il parametro nell'url che definisce il nome del * file, se non specificato il nome corrisponde al nome nell'url * @param dest * dove salvare il file, se non specificato crea un file * temporaneo * @return * @throws ClientProtocolException * @throws IOException */ public static File getFile(String url, String urlFileNameParam, File dest) throws ClientProtocolException, IOException { DefaultHttpClient httpclient = null; HttpGet httpget = null; HttpResponse response = null; HttpEntity entity = null; try { httpclient = new DefaultHttpClient(); url = url.trim(); /* Per prima cosa creiamo il File */ String name = getFileNameFromUrl(url, urlFileNameParam); String baseName = FilenameUtils.getBaseName(name); String extension = FilenameUtils.getExtension(name); if (dest == null) dest = File.createTempFile(baseName + "_", "." + extension); /* Procediamo con il Download */ httpget = new HttpGet(url); response = httpclient.execute(httpget); entity = response.getEntity(); if (entity != null) { OutputStream fos = null; try { // var fos = new // java.io.FileOutputStream('c:\\temp\\myfile.ext'); fos = new java.io.FileOutputStream(dest); entity.writeTo(fos); } finally { if (fos != null) fos.close(); } logger.debug(fos); } } catch (Exception ex) { logger.error(ex); } finally { // org.apache.http.client.utils.HttpClientUtils.closeQuietly(httpClient); // if (entity != null) // EntityUtils.consume(entity); // try { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } catch (Exception ex) { logger.error(ex); } } return dest; }