List of usage examples for org.apache.commons.httpclient.methods OptionsMethod releaseConnection
@Override public void releaseConnection()
From source file:OptionsMethodExample.java
public static void main(String args[]) { HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "Test Client"); OptionsMethod method = new OptionsMethod("http://www.google.com"); try {/*from ww w.j ava2s .co m*/ int returnCode = client.executeMethod(method); Enumeration list = method.getAllowedMethods(); while (list.hasMoreElements()) { System.err.println(list.nextElement()); } } catch (Exception e) { System.err.println(e); } finally { method.releaseConnection(); } }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
/** * Makes a OPTIONS request to the URL. Reads data back and returns the data * read. Note that this method only works with text data as it does the * byte-to-char conversion. This method will return null for responses * with binary MIME types. The addTextType(String) method is used to * register additional MIME types as text types. Use getContentSize() to * obtain the bytes of binary data read. * * @param url The URL to read from/*from w w w .j a va2s . c om*/ * @param headers The request headers, or null * @return The StringBuilder buffer containing the resulting document * @throws java.io.IOException */ public StringBuilder optionsURL(String url, Map<String, String> headers) throws IOException { OptionsMethod method = new OptionsMethod(url); method.setFollowRedirects(followRedirects); setHeaders(method, headers); try { responseCode = hc.executeMethod(method); buildResponseHeaders(method); return fetchResponse(method); } finally { method.releaseConnection(); } }
From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java
/** * Only return file names (no directory) * //w w w . j av a2s . co m * @param repoPath * path in registry * @return * @throws RegistryExtException * @throws ClientProtocolException * @throws IOException * @throws IllegalStateException * @throws JAXBException * @throws OAuthProblemException * @throws OAuthSystemException */ public ListResourceResponse getAllChildren(String repoPath) throws RegistryExtException, ClientProtocolException, IOException, IllegalStateException, JAXBException, OAuthSystemException, OAuthProblemException { Map<String, Object> session = ActionContext.getContext().getSession(); String accessToken = (String) session.get(Constants.SESSION_TOKEN); int statusCode = 200; String requestURL = composeURL(FILEOPPREFIX, repoPath); if (logger.isDebugEnabled()) { logger.debug("List request URL=" + requestURL); } HttpClient httpclient = new HttpClient(); OptionsMethod options = new OptionsMethod(requestURL); options.addRequestHeader("Accept", "application/xml"); options.addRequestHeader("Authorization", "Bearer " + accessToken); try { httpclient.executeMethod(options); statusCode = options.getStatusLine().getStatusCode(); /* handle token expiration */ if (statusCode == 401) { logger.info(String.format("Access token %s expired, going to refresh it", accessToken)); refreshToken(session); // use refreshed access token accessToken = (String) session.get(Constants.SESSION_TOKEN); options.addRequestHeader("Authorization", "Bearer " + accessToken); // re-send the request httpclient.executeMethod(options); statusCode = options.getStatusLine().getStatusCode(); } if (statusCode == 404) { logger.equals("List request URL=" + requestURL + " doesn't exist"); return new ListResourceResponse(null, statusCode); } if (statusCode != 200) { throw new RegistryExtException("Failed in listing children : HTTP error code : " + options.getStatusLine().getStatusCode()); } Entry xmlFile = FileSchemaUtil.readConfigXML(options.getResponseBodyAsStream()); if (logger.isDebugEnabled()) { logger.debug(String.format("Returned content:%n%s", FileSchemaUtil.toXMLString(xmlFile))); } Entries entries = xmlFile.getEntries(); return new ListResourceResponse(entries, statusCode); } finally { if (options != null) options.releaseConnection(); } }
From source file:org.apache.wink.itest.headers.HeadersTest.java
public void testAllowHeaders() throws Exception { try {//from ww w . ja va 2s . c om OptionsMethod httpMethod = new OptionsMethod(); httpMethod.setURI(new URI(getBaseURI() + "/headersallow1/allow1", false)); httpClient = new HttpClient(); try { int result = httpClient.executeMethod(httpMethod); assertEquals(204, result); assertNotNull(httpMethod.getResponseHeader("Allow")); List<String> allowedMethods = Arrays .asList(httpMethod.getResponseHeader("Allow").getValue().split(", ")); System.out.println(allowedMethods); assertEquals(3, allowedMethods.size()); assertTrue(allowedMethods.contains("HEAD")); assertTrue(allowedMethods.contains("OPTIONS")); assertTrue(allowedMethods.contains("GET")); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } try { OptionsMethod httpMethod = new OptionsMethod(); httpMethod.setURI(new URI(getBaseURI() + "/headersallow2", false)); httpClient = new HttpClient(); try { int result = httpClient.executeMethod(httpMethod); assertEquals(204, result); assertNotNull(httpMethod.getResponseHeader("Allow")); List<String> allowedMethods = Arrays .asList(httpMethod.getResponseHeader("Allow").getValue().split(", ")); System.out.println(allowedMethods); assertEquals(6, allowedMethods.size()); assertTrue(allowedMethods.contains("HEAD")); assertTrue(allowedMethods.contains("OPTIONS")); assertTrue(allowedMethods.contains("GET")); assertTrue(allowedMethods.contains("PUT")); assertTrue(allowedMethods.contains("POST")); assertTrue(allowedMethods.contains("DELETE")); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } try { OptionsMethod httpMethod = new OptionsMethod(); httpMethod.setURI(new URI(getBaseURI() + "/headersallow3/sublocator", false)); httpClient = new HttpClient(); try { int result = httpClient.executeMethod(httpMethod); assertEquals(204, result); assertNotNull(httpMethod.getResponseHeader("Allow")); List<String> allowedMethods = Arrays .asList(httpMethod.getResponseHeader("Allow").getValue().split(", ")); System.out.println(allowedMethods); assertEquals(3, allowedMethods.size()); assertTrue(allowedMethods.contains("HEAD")); assertTrue(allowedMethods.contains("OPTIONS")); assertTrue(allowedMethods.contains("GET")); assertEquals(null, httpMethod.getResponseBodyAsString()); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.apache.wink.itest.methodannotations.HttpMethodTest.java
/** * Tests that an OPTIONS request can be sent to resource containing only a * GET method.// w ww . j a va 2 s . c o m */ public void testOPTIONSRequest() { try { OptionsMethod httpMethod = new OptionsMethod(); httpMethod.setURI(new URI(BASE_URI, false)); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); assertEquals(204, result); Enumeration<?> allowedMethods = httpMethod.getAllowedMethods(); assertNotNull(allowedMethods); assertTrue(allowedMethods.hasMoreElements()); List<String> methods = new ArrayList<String>(); while (allowedMethods.hasMoreElements()) { methods.add((String) allowedMethods.nextElement()); } assertTrue(methods.contains("HEAD")); assertTrue(methods.contains("GET")); assertTrue(methods.contains("OPTIONS")); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.apache.wink.itest.methodannotations.HttpMethodTest.java
/** * Tests that a OPTIONS request can be sent to resource annotated with a * custom OPTIONS annotation.//from ww w. ja v a 2 s.c o m */ public void testCustomOPTIONSRequest() { try { OptionsMethod httpMethod = new OptionsMethod(); httpMethod.setURI(new URI(ALT_URI, false)); httpclient = new HttpClient(); try { int result = httpclient.executeMethod(httpMethod); System.out.println("Response status code: " + result); System.out.println("Response body: "); String responseBody = httpMethod.getResponseBodyAsString(); System.out.println(responseBody); assertEquals(200, result); assertEquals("", responseBody); Header header = httpMethod.getResponseHeader("Allow"); assertNotNull(header); String value = header.getValue(); assertTrue(value.contains("HEAD")); assertTrue(value.contains("OPTIONS")); assertTrue(value.contains("GET")); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); } finally { httpMethod.releaseConnection(); } } catch (URIException e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.collectionspace.services.client.test.ServiceLayerTest.java
@Test public void servicesExist() { if (logger.isDebugEnabled()) { logger.debug(BaseServiceTest.testBanner("servicesExist", CLASS_NAME)); }//from w w w . j a v a 2 s. c o m //use ID service that should always be present in a working service layer String url = serviceClient.getBaseURL() + "idgenerators"; OptionsMethod method = new OptionsMethod(url); try { serviceClient = new TestServiceClient(); int statusCode = httpClient.executeMethod(method); if (logger.isDebugEnabled()) { logger.debug("servicesExist url=" + url + " status=" + statusCode); } Assert.assertEquals(statusCode, HttpStatus.SC_OK, "expected " + HttpStatus.SC_OK); } catch (HttpException e) { logger.error("Fatal protocol violation: ", e); } catch (IOException e) { logger.error("Fatal transport error", e); } catch (Exception e) { logger.error("unknown exception ", e); } finally { // Release the connection. method.releaseConnection(); } }
From source file:org.exist.xquery.modules.httpclient.OPTIONSFunction.java
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { Sequence response = null;/*w w w . j ava 2 s.c o m*/ // must be a URL if (args[0].isEmpty()) { return (Sequence.EMPTY_SEQUENCE); } //get the url String url = args[0].itemAt(0).getStringValue(); //get the persist state boolean persistState = args[1].effectiveBooleanValue(); //setup OPTIONS request OptionsMethod options = new OptionsMethod(url); //setup OPTIONS Request Headers if (!args[2].isEmpty()) { setHeaders(options, ((NodeValue) args[2].itemAt(0)).getNode()); } try { //execute the request response = doRequest(context, options, persistState, null, null); } catch (IOException ioe) { throw (new XPathException(this, ioe.getMessage(), ioe)); } finally { options.releaseConnection(); } return (response); }
From source file:org.exjello.mail.Exchange2003Connection.java
private void signOn() throws Exception { HttpClient client = getClient();//from w w w . j av a 2s .c om URL serverUrl = new URL(server); String host = serverUrl.getHost(); int port = serverUrl.getPort(); if (port == -1) port = serverUrl.getDefaultPort(); AuthScope authScope = new AuthScope(host, port); if (username.indexOf("\\") < 0) { client.getState().setCredentials(authScope, new UsernamePasswordCredentials(username, password)); } else { // Try to connect with NTLM authentication String domainUser = username.substring(username.indexOf("\\") + 1, username.length()); String domain = username.substring(0, username.indexOf("\\")); client.getState().setCredentials(authScope, new NTCredentials(domainUser, password, host, domain)); } boolean authenticated = false; OptionsMethod authTest = new OptionsMethod(server + "/exchange"); try { authenticated = (client.executeMethod(authTest) < 400); } finally { try { InputStream stream = authTest.getResponseBodyAsStream(); byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } finally { authTest.releaseConnection(); } } if (!authenticated) { PostMethod op = new PostMethod(server + SIGN_ON_URI); op.setRequestHeader("Content-Type", FORM_URLENCODED_CONTENT_TYPE); op.addParameter("destination", server + "/exchange"); op.addParameter("flags", "0"); op.addParameter("username", username); op.addParameter("password", password); try { int status = client.executeMethod(op); if (status >= 400) { throw new IllegalStateException("Sign-on failed: " + status); } } finally { try { InputStream stream = op.getResponseBodyAsStream(); byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } finally { op.releaseConnection(); } } } findInbox(); }
From source file:org.exoplatform.calendar.service.impl.RemoteCalendarServiceImpl.java
@Override public boolean isValidRemoteUrl(String url, String type, String remoteUser, String remotePassword) throws IOException, UnsupportedOperationException { try {// w ww . j a v a 2 s . c om HttpClient client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); String host = new URL(url).getHost(); if (StringUtils.isEmpty(host)) host = url; hostConfig.setHost(host); client.setHostConfiguration(hostConfig); Credentials credentials = null; client.setHostConfiguration(hostConfig); if (!StringUtils.isEmpty(remoteUser)) { credentials = new UsernamePasswordCredentials(remoteUser, remotePassword); client.getState().setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials); } if (CalendarService.ICALENDAR.equals(type)) { GetMethod get = new GetMethod(url); client.executeMethod(get); int statusCode = get.getStatusCode(); get.releaseConnection(); return (statusCode == HttpURLConnection.HTTP_OK); } else { if (CalendarService.CALDAV.equals(type)) { OptionsMethod options = new OptionsMethod(url); client.executeMethod(options); Header header = options.getResponseHeader("DAV"); options.releaseConnection(); if (header == null) { if (logger.isDebugEnabled()) { logger.debug("Cannot connect to remoter server or not support WebDav access"); } return false; } Boolean support = header.toString().contains("calendar-access"); options.releaseConnection(); if (!support) { if (logger.isDebugEnabled()) { logger.debug("Remote server does not support CalDav access"); } throw new UnsupportedOperationException("Remote server does not support CalDav access"); } return support; } return false; } } catch (MalformedURLException e) { if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e); throw new IOException("URL is invalid. Maybe no legal protocol or URl could not be parsed"); } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e); throw new IOException("Error occurs when connecting to remote server"); } }