List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.cryptomator.frontend.webdav.WebDavServerTest.java
@Test public void testMultipleGetWithRangeAsync() throws IOException, URISyntaxException, InterruptedException { final String testResourceUrl = servletRoot + "/foo.txt"; // prepare 8MiB test data: final byte[] plaintextData = new byte[2097152 * Integer.BYTES]; final ByteBuffer plaintextDataByteBuffer = ByteBuffer.wrap(plaintextData); for (int i = 0; i < 2097152; i++) { plaintextDataByteBuffer.putInt(i); }//w w w. j a v a 2 s .com try (WritableFile w = fs.file("foo.txt").openWritable()) { plaintextDataByteBuffer.flip(); w.write(plaintextDataByteBuffer); } final MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager(); cm.getParams().setDefaultMaxConnectionsPerHost(50); final HttpClient client = new HttpClient(cm); // multiple async range requests: final List<ForkJoinTask<?>> tasks = new ArrayList<>(); final Random generator = new Random(System.currentTimeMillis()); final AtomicBoolean success = new AtomicBoolean(true); // 10 full interrupted requests: for (int i = 0; i < 10; i++) { final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl); final int statusCode = client.executeMethod(getMethod); if (statusCode != 200) { LOG.error("Invalid status code for interrupted full request"); success.set(false); } getMethod.getResponseBodyAsStream().read(); getMethod.getResponseBodyAsStream().close(); getMethod.releaseConnection(); } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 50 crappy interrupted range requests: for (int i = 0; i < 50; i++) { final int lower = generator.nextInt(plaintextData.length); final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl); getMethod.addRequestHeader("Range", "bytes=" + lower + "-"); final int statusCode = client.executeMethod(getMethod); if (statusCode != 206) { LOG.error("Invalid status code for interrupted range request"); success.set(false); } getMethod.getResponseBodyAsStream().read(); getMethod.getResponseBodyAsStream().close(); getMethod.releaseConnection(); } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 50 normal open range requests: for (int i = 0; i < 50; i++) { final int lower = generator.nextInt(plaintextData.length - 512); final int upper = plaintextData.length - 1; final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl); getMethod.addRequestHeader("Range", "bytes=" + lower + "-"); final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1); final int statusCode = client.executeMethod(getMethod); final byte[] responseBody = new byte[upper - lower + 10]; final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody); getMethod.releaseConnection(); if (statusCode != 206) { LOG.error("Invalid status code for open range request"); success.set(false); } else if (upper - lower + 1 != bytesRead) { LOG.error("Invalid response length for open range request"); success.set(false); } else if (!Arrays.equals(expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) { LOG.error("Invalid response body for open range request"); success.set(false); } } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 200 normal closed range requests: for (int i = 0; i < 200; i++) { final int pos1 = generator.nextInt(plaintextData.length - 512); final int pos2 = pos1 + 512; final ForkJoinTask<?> task = ForkJoinTask.adapt(() -> { try { final int lower = Math.min(pos1, pos2); final int upper = Math.max(pos1, pos2); final HttpMethod getMethod = new GetMethod(testResourceUrl); getMethod.addRequestHeader("Range", "bytes=" + lower + "-" + upper); final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1); final int statusCode = client.executeMethod(getMethod); final byte[] responseBody = new byte[upper - lower + 1]; final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody); getMethod.releaseConnection(); if (statusCode != 206) { LOG.error("Invalid status code for closed range request"); success.set(false); } else if (upper - lower + 1 != bytesRead) { LOG.error("Invalid response length for closed range request"); success.set(false); } else if (!Arrays.equals(expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) { LOG.error("Invalid response body for closed range request"); success.set(false); } } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } Collections.shuffle(tasks, generator); final ForkJoinPool pool = new ForkJoinPool(4); for (ForkJoinTask<?> task : tasks) { pool.execute(task); } for (ForkJoinTask<?> task : tasks) { task.join(); } pool.shutdown(); cm.shutdown(); Assert.assertTrue(success.get()); }
From source file:org.devproof.portal.module.bookmark.service.SynchronizeServiceImpl.java
@Override public DeliciousBean getDataFromDelicious(String username, String password, String tags) { logger.debug("Retrieve data from delicious"); HttpClient httpClient = new HttpClient(); HttpClientParams httpClientParams = new HttpClientParams(); DefaultHttpMethodRetryHandler defaultHttpMethodRetryHandler = new DefaultHttpMethodRetryHandler(0, false); httpClientParams.setParameter("User-Agent", BookmarkConstants.USER_AGENT); httpClientParams.setParameter(HttpClientParams.RETRY_HANDLER, defaultHttpMethodRetryHandler); httpClient.setParams(httpClientParams); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); String urlTag = ""; if (StringUtils.isNotEmpty(tags)) { urlTag = "tag=" + tags; }//from w w w.j a v a2 s . com HttpMethod method = new GetMethod(BookmarkConstants.DELICIOUS_API + urlTag); method.setDoAuthentication(true); DeliciousBean bean = new DeliciousBean(); try { int httpCode = httpClient.executeMethod(method); bean.setHttpCode(httpCode); if (!bean.hasError()) { XStream xstream = new XStream(new DomDriver()); xstream.alias("posts", DeliciousBean.class); xstream.alias("post", DeliciousPostBean.class); xstream.addImplicitCollection(DeliciousBean.class, "posts"); xstream.useAttributeFor(String.class); xstream.useAttributeFor(Integer.class); bean = (DeliciousBean) xstream.fromXML(method.getResponseBodyAsStream()); bean.setHttpCode(httpCode); } else { bean.setErrorMessage("Unknown Error: Http Status: " + httpCode); } } catch (HttpException e) { bean.setErrorMessage(e.getMessage()); } catch (IOException e) { bean.setErrorMessage(e.getMessage()); } method.releaseConnection(); return bean; }
From source file:org.devproof.portal.module.deadlinkcheck.panel.DeadlinkCheckPanel.java
private AjaxButton createAjaxButton() { return new AjaxButton("startButton") { private static final long serialVersionUID = 1L; @Override//from w w w . j a v a2 s. c o m protected void onSubmit(AjaxRequestTarget target, Form<?> form) { String baseUrl = RequestUtils.toAbsolutePath(""); progressBar.start(target); newDeadlinkCheckThread(baseUrl).start(); setEnabled(false); } private Thread newDeadlinkCheckThread(final String baseUrl) { return new Thread() { @Override public void run() { threadActive = true; Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443)); List<T> listToCheck = listToCheckModel.getObject(); maxItem = listToCheck.size(); for (T link : listToCheck) { if (!threadActive) { return; } String url = link.getUrl(); boolean isBroken; if (isLocalFile(url)) { try { URI uri = new URI(url); File downloadFile = new File(uri); isBroken = !downloadFile.canRead(); } catch (URISyntaxException e) { // nothing to log isBroken = true; } } else { url = buildAbsoluteUrl(baseUrl, url); isBroken = isBrokenURIFormat(url); if (!isBroken) { isBroken = isHttpCallBroken(url); } } // if (isBroken) { DeadlinkCheckPanel.this.onBroken(link); DeadlinkCheckPanel.this.brokenFound++; } else { DeadlinkCheckPanel.this.onValid(link); } DeadlinkCheckPanel.this.actualItem++; DeadlinkCheckPanel.this.progressInPercent = (int) (((double) DeadlinkCheckPanel.this.actualItem / (double) DeadlinkCheckPanel.this.maxItem) * 100d); } // The bar is stopped automatically, if progress is done } private boolean isHttpCallBroken(String url) { HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(120000); HttpMethod method = new GetMethod(url); boolean isBroken; try { int httpCode = client.executeMethod(method); isBroken = (httpCode / 100) != 2; } catch (HttpException e) { isBroken = true; } catch (IOException e) { isBroken = true; } method.releaseConnection(); return isBroken; } private boolean isBrokenURIFormat(String url) { try { new URI(url); } catch (URISyntaxException e1) { return true; } return false; } private String buildAbsoluteUrl(String baseUrl, String url) { if (isNotExternalUrl(url)) { if (isRelativeUrl(url)) { url = url.substring(1); } url = baseUrl + url; } return url; } private boolean isRelativeUrl(String url) { return url.startsWith("/"); } private boolean isNotExternalUrl(String url) { return !url.startsWith("http://") && !url.startsWith("https://") && !url.startsWith("ftp://"); } private boolean isLocalFile(String url) { return url.startsWith("file:/"); } }; } }; }
From source file:org.dspace.app.util.AbstractDSpaceWebapp.java
/** Return the list of running applications. */ static public List<AbstractDSpaceWebapp> getApps() { ArrayList<AbstractDSpaceWebapp> apps = new ArrayList<AbstractDSpaceWebapp>(); TableRowIterator tri;// w ww . j ava 2s . c o m Context context = null; HttpMethod request = null; try { context = new Context(); tri = DatabaseManager.queryTable(context, "Webapp", "SELECT * FROM Webapp"); for (TableRow row : tri.toList()) { DSpaceWebapp app = new DSpaceWebapp(); app.kind = row.getStringColumn("AppName"); app.url = row.getStringColumn("URL"); app.started = row.getDateColumn("Started"); app.uiQ = row.getBooleanColumn("isUI"); HttpClient client = new HttpClient(); request = new HeadMethod(app.url); int status = client.executeMethod(request); request.getResponseBody(); if (status != HttpStatus.SC_OK) { DatabaseManager.delete(context, row); context.commit(); continue; } apps.add(app); } } catch (SQLException e) { log.error("Unable to list running applications", e); } catch (HttpException e) { log.error("Failure checking for a running webapp", e); } catch (IOException e) { log.error("Failure checking for a running webapp", e); } finally { if (null != request) { request.releaseConnection(); } if (null != context) { context.abort(); } } return apps; }
From source file:org.dspace.rest.providers.DiscoverProvider.java
public List<?> getEntities(EntityReference ref, Search search) { log.info("DiscoverProvider - get_entities"); List<Object> entities = new ArrayList<Object>(); try {/*from w w w. j a va 2 s .c o m*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( ConfigurationManager.getProperty("discovery", "search.server") + "/select"); log.info("DiscoverProvider method - " + ConfigurationManager.getProperty("discovery", "search.server")); log.info("DiscoverProvider search.getRestrictions().length - " + search.getRestrictions().length); log.info("DiscoverProvider format - " + format); List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>(); if (search.getRestrictions().length > 0) { for (int i = 0; i < search.getRestrictions().length; i++) { log.info("DiscoverProvider search.getRestrictions()[i].getProperty() - " + search.getRestrictions()[i].getProperty()); log.info("DiscoverProvider search.getRestrictions()[i].getStringValue() - " + search.getRestrictions()[i].getStringValue()); if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) { nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(), search.getRestrictions()[i].getStringValue())); } } if ("json".equals(format)) { nameValuePairsList.add(new NameValuePair("wt", "json")); } } if (search.getOrders().length > 0) { for (int i = 0; i < search.getOrders().length; i++) { log.info("DiscoverProvider search.getOrders()[i].getProperty() - " + search.getOrders()[i].getProperty()); nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty())); } } NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()]; nameValuePairsList.toArray(nameValuePairs); method.setQueryString(nameValuePairs); client.executeMethod(method); String s = method.getResponseBodyAsString(); // log.info("DiscoverProvider result string - " + s); entities.add(new EntityData(s)); method.releaseConnection(); } catch (IOException e) { throw new EntityException("Internal server error", "IO error, cannot call solr server", 500); } return entities; }
From source file:org.dspace.rest.providers.StatisticsProvider.java
public List<?> getEntities(EntityReference ref, Search search) { log.info("StatisticsProvider - get_entities"); List<Object> entities = new ArrayList<Object>(); try {/*from w ww . j a v a 2 s . c om*/ HttpClient client = new HttpClient(); HttpMethod method = new GetMethod( ConfigurationManager.getProperty("solr-statistics", "server") + "/select"); log.info( "StatisticsProvider method - " + ConfigurationManager.getProperty("solr-statistics", "server")); log.info("StatisticsProvider search.getRestrictions().length - " + search.getRestrictions().length); log.info("StatisticsProvider format - " + format); List<NameValuePair> nameValuePairsList = new ArrayList<NameValuePair>(); if (search.getRestrictions().length > 0) { for (int i = 0; i < search.getRestrictions().length; i++) { log.info("StatisticsProvider search.getRestrictions()[i].getProperty() - " + search.getRestrictions()[i].getProperty()); log.info("StatisticsProvider search.getRestrictions()[i].getStringValue() - " + search.getRestrictions()[i].getStringValue()); if (!"org.apache.catalina.ASYNC_SUPPORTED".equals(search.getRestrictions()[i].getProperty())) { nameValuePairsList.add(new NameValuePair(search.getRestrictions()[i].getProperty(), search.getRestrictions()[i].getStringValue())); } } if ("json".equals(format)) { nameValuePairsList.add(new NameValuePair("wt", "json")); } } if (search.getOrders().length > 0) { for (int i = 0; i < search.getOrders().length; i++) { log.info("StatisticsProvider search.getOrders()[i].getProperty() - " + search.getOrders()[i].getProperty()); nameValuePairsList.add(new NameValuePair("sort", search.getOrders()[i].getProperty())); } } NameValuePair[] nameValuePairs = new NameValuePair[nameValuePairsList.size()]; nameValuePairsList.toArray(nameValuePairs); method.setQueryString(nameValuePairs); client.executeMethod(method); String s = method.getResponseBodyAsString(); // log.info("StatisticsProvider result string - " + s); entities.add(new EntityData(s)); method.releaseConnection(); } catch (IOException e) { throw new EntityException("Internal server error", "IO error, cannot call solr server", 500); } return entities; }
From source file:org.eclipse.mylyn.internal.web.tasks.WebRepositoryConnector.java
private static String requestResource(String url, HttpClient client, HostConfiguration hostConfiguration, HttpMethod method) throws IOException, HttpException { String refreshUrl = null;// ww w .ja va 2 s .c o m try { client.executeMethod(hostConfiguration, method); // int statusCode = client.executeMethod(method); // if (statusCode == 300 || statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) { // Header location = method.getResponseHeader("Location"); // if (location != null) { // refreshUrl = location.getValue(); // if (!refreshUrl.startsWith("/")) { // refreshUrl = "/" + refreshUrl; // } // } // } refreshUrl = getRefreshUrl(url, method); if (refreshUrl == null) { return method.getResponseBodyAsString(); } } finally { method.releaseConnection(); } method = new GetMethod(refreshUrl); try { client.executeMethod(hostConfiguration, method); return method.getResponseBodyAsString(); } finally { method.releaseConnection(); } }
From source file:org.eclipse.om2m.comm.http.RestHttpClient.java
/** * Converts a protocol-independent {@link RequestIndication} object into a standard HTTP request and sends a standard HTTP request. * Converts the received standard HTTP request into {@link ResponseConfirm} object and returns it back. * @param requestIndication - protocol independent request. * @return protocol independent response. *///from w w w . j av a 2 s . c om public ResponseConfirm sendRequest(RequestIndication requestIndication) { logServiceTracker = new ServiceTracker(FrameworkUtil.getBundle(RestHttpClient.class).getBundleContext(), org.osgi.service.log.LogService.class.getName(), null); logServiceTracker.open(); logservice = (LogService) logServiceTracker.getService(); LOGGER.debug("Http Client > " + requestIndication); logservice.log(LogService.LOG_ERROR, "Http Client > " + requestIndication); HttpClient httpclient = new HttpClient(); ResponseConfirm responseConfirm = new ResponseConfirm(); HttpMethod httpMethod = null; String url = requestIndication.getUrl(); if (!url.startsWith(protocol + "://")) { url = protocol + "://" + url; } try { switch (requestIndication.getMethod()) { case "RETRIEVE": httpMethod = new GetMethod(url); break; case "CREATE": httpMethod = new PostMethod(url); ((PostMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "UPDATE": httpMethod = new PutMethod(url); ((PutMethod) httpMethod).setRequestEntity( new StringRequestEntity(requestIndication.getRepresentation(), "application/xml", "UTF8")); break; case "DELETE": httpMethod = new DeleteMethod(url); break; case "EXECUTE": httpMethod = new PostMethod(url); break; default: return new ResponseConfirm(); } httpMethod.addRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(requestIndication.getRequestingEntity().getBytes()))); httpMethod.setQueryString(getQueryFromParams(requestIndication.getParameters())); int statusCode = httpclient.executeMethod(httpMethod); responseConfirm.setStatusCode(getRestStatusCode(statusCode)); if (statusCode != 204) { if (httpMethod.getResponseBody() != null) { responseConfirm.setRepresentation(new String(httpMethod.getResponseBody())); } } if (statusCode == 201) { if (httpMethod.getResponseHeader("Location").getValue() != null) { responseConfirm.setResourceURI(httpMethod.getResponseHeader("Location").getValue()); } } //LOGGER.debug("Http Client > "+responseConfirm); LOGGER.debug("Http Client > " + responseConfirm); logservice.log(LogService.LOG_ERROR, "Http Client > " + responseConfirm); } catch (IOException e) { LOGGER.error(url + " Not Found" + responseConfirm, e); logservice.log(LogService.LOG_ERROR, url + " Not Found" + responseConfirm); } finally { httpMethod.releaseConnection(); } return responseConfirm; }
From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.CreateFolderCommand.java
protected ServerStatus executeMethod(HttpMethod method) throws HttpException, IOException, JSONException { try {// ww w . j av a 2s. c om int code = CFActivator.getDefault().getHttpClient().executeMethod(method); if (code == 204) { /* no content response */ return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK); } JSONObject result = new JSONObject(); result.put("response", method.getResponseBodyAsString()); if (code != 200 && code != 201) { // TODO parse error from XML and put in description return HttpUtil.createErrorStatus(Status.ERROR, Integer.toString(code), method.getStatusText()); } return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } finally { /* ensure connections are released back to the connection manager */ method.releaseConnection(); } }
From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java
public static ServerStatus executeMethod(HttpMethod method) throws HttpException, IOException, JSONException { try {//from w ww .j ava 2s . c o m int code = CFActivator.getDefault().getHttpClient().executeMethod(method); if (code == 204) { /* no content response */ return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK); } String response = method.getResponseBodyAsString(); JSONObject result; try { result = new MagicJSONObject(response); } catch (JSONException e) { result = new JSONObject(); result.put("response", response); } if (code != 200 && code != 201) { String desctiption = result.optString("description"); if (desctiption == null || desctiption.length() == 0) { desctiption = result.optString("response", "Could not connect to host. Error: " + code); if (desctiption.length() > 1000) { desctiption = "Could not connect to host. Error: " + code; } } return new ServerStatus(Status.ERROR, code, desctiption, result, null); } if (result.has("error_code")) { return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, result.optString("description"), result, null); } return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } finally { /* ensure connections are released back to the connection manager */ method.releaseConnection(); } }