List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.nuxeo.ecm.tokenauth.TestTokenAuthenticationServlet.java
@Test public void testServlet() throws Exception { HttpClient httpClient = new HttpClient(); HttpMethod getMethod = null; try {//w ww . j a va2 s . c om // ------------ Test bad authentication ---------------- getMethod = new GetMethod( "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&deviceId=dead-beaf-cafe-babe&permission=rw"); int status = executeGetMethod(httpClient, getMethod, "Administrator", "badPassword"); // Receives 404 because of redirection to error page assertEquals(404, status); // ------------ Test omitting required parameters ---------------- // Token acquisition getMethod = new GetMethod("http://localhost:18080/authentication/token?applicationName=myFavoriteApp"); status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator"); assertEquals(400, status); // Token revocation getMethod = new GetMethod( "http://localhost:18080/authentication/token?applicationName=myFavoriteApp&revoke=true"); status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator"); assertEquals(400, status); // ------------ Test acquiring token ---------------- String queryParams = URIUtil .encodeQuery("applicationName=Nuxeo Drive&deviceId=dead-beaf-cafe-babe&permission=rw"); URI uri = new URI("http", null, "localhost", 18080, "/authentication/token", queryParams, null); getMethod = new GetMethod(uri.toString()); // Acquire new token status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator"); assertEquals(201, status); String token = getMethod.getResponseBodyAsString(); assertNotNull(token); assertNotNull(getTokenAuthenticationService().getUserName(token)); assertEquals(1, getTokenAuthenticationService().getTokenBindings("Administrator").size()); // Acquire existing token status = httpClient.executeMethod(getMethod); assertEquals(201, status); String existingToken = getMethod.getResponseBodyAsString(); assertEquals(token, existingToken); // ------------ Test revoking token ---------------- // Non existing token, should do nothing getMethod = new GetMethod( "http://localhost:18080/authentication/token?applicationName=nonExistingApp&deviceId=dead-beaf-cafe-babe&revoke=true"); status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator"); assertEquals(400, status); String response = getMethod.getResponseBodyAsString(); assertEquals(String.format( "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.", "Administrator", "nonExistingApp", "dead-beaf-cafe-babe"), response); // Existing token queryParams = URIUtil .encodeQuery("applicationName=Nuxeo Drive&deviceId=dead-beaf-cafe-babe&revoke=true"); uri = new URI("http", null, "localhost", 18080, "/authentication/token", queryParams, null); getMethod = new GetMethod(uri.toString()); status = executeGetMethod(httpClient, getMethod, "Administrator", "Administrator"); assertEquals(202, status); response = getMethod.getResponseBodyAsString(); assertEquals(String.format("Token revoked for userName %s, applicationName %s and deviceId %s.", "Administrator", "Nuxeo Drive", "dead-beaf-cafe-babe"), response); nextTransaction(); // see committed changes assertNull(getTokenAuthenticationService().getUserName(token)); assertTrue(getTokenAuthenticationService().getTokenBindings("Administrator").isEmpty()); } finally { getMethod.releaseConnection(); } }
From source file:org.nuxeo.jira.NuxeoServerInfoCollector.java
public static File collectNuxeoServerInfoAsZip(String serverURL, String userName, String password) throws HttpException, IOException { HttpClient httpClient = new HttpClient(); HttpMethod getMethod = null; try {//from w w w.j a va 2 s .c om getMethod = new GetMethod(serverURL + "/site/collectServerInfo/info.zip"); executeGetMethod(httpClient, getMethod, userName, password); InputStream in = getMethod.getResponseBodyAsStream(); File tmpFile = File.createTempFile("NXserverInfo-", ".zip"); tmpFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tmpFile); byte[] bytes = new byte[1024]; try { int read; while ((read = in.read(bytes)) > 0) { out.write(bytes, 0, read); } } finally { in.close(); out.close(); } return tmpFile; } finally { getMethod.releaseConnection(); } }
From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java
/** {@inheritDoc} */ public HttpResponse fetch(HttpRequest request) { HttpClient httpClient = new HttpClient(); HttpMethod httpMethod; String methodType = request.getMethod(); String requestUri = request.getUri().toString(); ProxyHelper.fillProxy(httpClient, requestUri); // true for non-HEAD requests boolean requestCompressedContent = true; if ("POST".equals(methodType) || "PUT".equals(methodType)) { EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri) : new PutMethod(requestUri); if (request.getPostBodyLength() > 0) { enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody())); enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength())); }// w ww . j a va 2s. c o m httpMethod = enclosingMethod; } else if ("DELETE".equals(methodType)) { httpMethod = new DeleteMethod(requestUri); } else if ("HEAD".equals(methodType)) { httpMethod = new HeadMethod(requestUri); } else { httpMethod = new GetMethod(requestUri); } httpMethod.setFollowRedirects(false); httpMethod.getParams().setSoTimeout(connectionTimeoutMs); if (requestCompressedContent) httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate"); for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ',')); } try { int statusCode = httpClient.executeMethod(httpMethod); // Handle redirects manually if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) { Header header = httpMethod.getResponseHeader("location"); if (header != null) { String redirectUri = header.getValue(); if ((redirectUri == null) || (redirectUri.equals(""))) { redirectUri = "/"; } httpMethod.releaseConnection(); httpMethod = new GetMethod(redirectUri); statusCode = httpClient.executeMethod(httpMethod); } } return makeResponse(httpMethod, statusCode); } catch (IOException e) { if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) { return HttpResponse.timeout(); } return HttpResponse.error(); } finally { httpMethod.releaseConnection(); } }
From source file:org.obm.caldav.client.AbstractPushTest.java
private synchronized Document doRequest(HttpMethod hm) { Document xml = null;// www. j a va 2s . c o m try { int ret = hc.executeMethod(hm); Header[] hs = hm.getResponseHeaders(); for (Header h : hs) { System.err.println("head[" + h.getName() + "] => " + h.getValue()); } if (ret == HttpStatus.SC_UNAUTHORIZED) { UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password); authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm); return null; } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) { InputStream is = hm.getResponseBodyAsStream(); if (is != null) { if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) { xml = DOMUtils.parse(is); DOMUtils.logDom(xml); } else { System.out.println(FileUtils.streamString(is, false)); } } } else { System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString()); } } catch (Exception e) { e.printStackTrace(); } finally { hm.releaseConnection(); } return xml; }
From source file:org.olat.modules.tu.IframeTunnelController.java
/** * Constructor for a tunnel component wrapper controller * /*from w ww .j av a 2 s .c o m*/ * @param ureq the userrequest * @param wControl the windowcontrol * @param config the module configuration */ public IframeTunnelController(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config) { super(ureq, wControl); // use iframe translator for generic iframe title text setTranslator(Util.createPackageTranslator(IFrameDisplayController.class, ureq.getLocale())); this.config = config; // configuration.... final int configVersion = config.getConfigurationVersion(); // since config version 1 final String proto = (String) config.get(TUConfigForm.CONFIGKEY_PROTO); final String host = (String) config.get(TUConfigForm.CONFIGKEY_HOST); final Integer port = (Integer) config.get(TUConfigForm.CONFIGKEY_PORT); final String user = (String) config.get(TUConfigForm.CONFIGKEY_USER); final String startUri = (String) config.get(TUConfigForm.CONFIGKEY_URI); final String pass = (String) config.get(TUConfigForm.CONFIGKEY_PASS); String firstQueryString = null; if (configVersion == 2) { // query string is available since config version 2 firstQueryString = (String) config.get(TUConfigForm.CONFIGKEY_QUERY); } final boolean usetunnel = config.getBooleanSafe(TUConfigForm.CONFIG_TUNNEL); myContent = createVelocityContainer("iframe_index"); if (!usetunnel) { // display content directly final String rawurl = TUConfigForm.getFullURL(proto, host, port, startUri, firstQueryString).toString(); myContent.contextPut("url", rawurl); } else { // tunnel final Identity ident = ureq.getIdentity(); if (user != null && user.length() > 0) { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, user, pass); } else { httpClientInstance = HttpClientFactory.getHttpClientInstance(host, port.intValue(), proto, null, null); } final Locale loc = ureq.getLocale(); final Mapper mapper = new Mapper() { @Override public MediaResource handle(final String relPath, final HttpServletRequest hreq) { MediaResource mr = null; final String method = hreq.getMethod(); String uri = relPath; HttpMethod meth = null; if (uri == null) { uri = (startUri == null) ? "" : startUri; } if (uri.length() > 0 && uri.charAt(0) != '/') { uri = "/" + uri; } // String contentType = hreq.getContentType(); // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(uri); final String queryString = hreq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; // if response is a redirect, follow it if (meth == null) { return null; } meth.setFollowRedirects(true); } else if (method.equals("POST")) { // if (contentType == null || contentType.equals("application/x-www-form-urlencoded")) { // regular post, no file upload // } final Map params = hreq.getParameterMap(); final PostMethod pmeth = new PostMethod(uri); final Set postKeys = params.keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) params.get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", userName); meth.addRequestHeader("X-OLAT-LASTNAME", lastName); meth.addRequestHeader("X-OLAT-FIRSTNAME", firstName); meth.addRequestHeader("X-OLAT-EMAIL", email); boolean ok = false; try { httpClientInstance.executeMethod(meth); ok = true; } catch (final Exception e) { // handle error later } if (!ok) { // error meth.releaseConnection(); return new NotFoundMediaResource(relPath); } // get or post successfully final Header responseHeader = meth.getResponseHeader("Content-Type"); if (responseHeader == null) { // error return new NotFoundMediaResource(relPath); } mr = new HttpRequestMediaResource(meth); return mr; } }; final String amapPath = registerMapper(mapper); String alluri = amapPath + startUri; if (firstQueryString != null) { alluri += "?" + firstQueryString; } myContent.contextPut("url", alluri); } final String frameId = "ifdc" + hashCode(); // for e.g. js use myContent.contextPut("frameId", frameId); putInitialPanel(myContent); }
From source file:org.olat.modules.tu.TunnelComponent.java
private void fetchFirstResource(final Identity ident) { final TURequest tureq = new TURequest(); // config, ureq); tureq.setContentType(null); // not used tureq.setMethod("GET"); tureq.setParameterMap(Collections.EMPTY_MAP); tureq.setQueryString(query);/*from w w w .j a va 2 s.c om*/ if (startUri != null) { if (startUri.startsWith("/")) { tureq.setUri(startUri); } else { tureq.setUri("/" + startUri); } } // if (allowedToSendPersonalHeaders) { final String userName = ident.getName(); final User u = ident.getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); tureq.setEmail(email); tureq.setFirstName(firstName); tureq.setLastName(lastName); tureq.setUserName(userName); // } final HttpMethod meth = fetch(tureq, httpClientInstance); if (meth == null) { setFetchError(); } else { final Header responseHeader = meth.getResponseHeader("Content-Type"); String mimeType; if (responseHeader == null) { setFetchError(); mimeType = null; } else { mimeType = responseHeader.getValue(); } if (mimeType != null && mimeType.startsWith("text/html")) { // we have html content, let doDispatch handle it for // inline rendering, update hreq for next content request String body; try { body = meth.getResponseBodyAsString(); } catch (final IOException e) { Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class); htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": Unknown transfer problem '"; return; } final SimpleHtmlParser parser = new SimpleHtmlParser(body); if (!parser.isValidHtml()) { // this is not valid HTML, deliver // asynchronuous } meth.releaseConnection(); htmlHead = parser.getHtmlHead(); jsOnLoad = parser.getJsOnLoad(); htmlContent = parser.getHtmlContent(); } else { htmlContent = "Error: cannot display inline :" + tureq.getUri() + ": mime type was '" + mimeType + "' but expected 'text/html'. Response header was '" + responseHeader + "'."; } } }
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @see org.olat.core.gui.media.AsyncMediaResponsible#getAsyncMediaResource(org.olat.core.gui.UserRequest) *///from ww w . j a va2 s. com @Override public MediaResource getAsyncMediaResource(final UserRequest ureq) { final String moduleURI = ureq.getModuleURI(); // FIXME:fj: can we distinguish between a ../ call an a click to another component? // now works for start uri's like /demo/tunneldemo.php but when in tunneldemo.php // a link is used like ../ this link does not work (moduleURI is null). if i use // ../index.php instead everything works as expected if (moduleURI == null) { // after a click on some other component e.g. if (!firstCall) { return null; } firstCall = false; // reset first call } final TURequest tureq = new TURequest(config, ureq); // if (allowedToSendPersonalHeaders) { final String userName = ureq.getIdentity().getName(); final User u = ureq.getIdentity().getUser(); final String lastName = u.getProperty(UserConstants.LASTNAME, loc); final String firstName = u.getProperty(UserConstants.FIRSTNAME, loc); final String email = u.getProperty(UserConstants.EMAIL, loc); tureq.setEmail(email); tureq.setFirstName(firstName); tureq.setLastName(lastName); tureq.setUserName(userName); // } final HttpMethod meth = fetch(tureq, httpClientInstance); if (meth == null) { setFetchError(); return null; } final Header responseHeader = meth.getResponseHeader("Content-Type"); if (responseHeader == null) { setFetchError(); return null; } final String mimeType = responseHeader.getValue(); if (mimeType != null && mimeType.startsWith("text/html")) { // we have html content, let doDispatch handle it for // inline rendering, update hreq for next content request String body; try { body = meth.getResponseBodyAsString(); } catch (final IOException e) { Tracing.logWarn("Problems when tunneling URL::" + tureq.getUri(), e, TunnelComponent.class); return null; } final SimpleHtmlParser parser = new SimpleHtmlParser(body); if (!parser.isValidHtml()) { // this is not valid HTML, deliver // asynchronuous return new HttpRequestMediaResource(meth); } meth.releaseConnection(); htmlHead = parser.getHtmlHead(); jsOnLoad = parser.getJsOnLoad(); htmlContent = parser.getHtmlContent(); setDirty(true); } else { return new HttpRequestMediaResource(meth); // this is a async browser } // refetch return null; }
From source file:org.olat.modules.tu.TunnelComponent.java
/** * @param tuReq//from ww w.j a va 2s . c o m * @param client * @return HttpMethod */ public HttpMethod fetch(final TURequest tuReq, final HttpClient client) { final String modulePath = tuReq.getUri(); HttpMethod meth = null; final String method = tuReq.getMethod(); if (method.equals("GET")) { final GetMethod cmeth = new GetMethod(modulePath); final String queryString = tuReq.getQueryString(); if (queryString != null) { cmeth.setQueryString(queryString); } meth = cmeth; if (meth == null) { return null; } // if response is a redirect, follow it meth.setFollowRedirects(true); } else if (method.equals("POST")) { final String type = tuReq.getContentType(); if (type == null || type.equals("application/x-www-form-urlencoded")) { // regular post, no file upload } final PostMethod pmeth = new PostMethod(modulePath); final Set postKeys = tuReq.getParameterMap().keySet(); for (final Iterator iter = postKeys.iterator(); iter.hasNext();) { final String key = (String) iter.next(); final String vals[] = (String[]) tuReq.getParameterMap().get(key); for (int i = 0; i < vals.length; i++) { pmeth.addParameter(key, vals[i]); } meth = pmeth; } if (meth == null) { return null; // Redirects are not supported when using POST method! // See RFC 2616, section 10.3.3, page 62 } } // Add olat specific headers to the request, can be used by external // applications to identify user and to get other params // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName()); meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName()); meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName()); meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail()); try { client.executeMethod(meth); return meth; } catch (final Exception e) { meth.releaseConnection(); } return null; }
From source file:org.olat.restapi.GroupMgmtTest.java
@Test public void testAddParticipant() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/participants/" + part3.getKey(); final HttpMethod method = createPut(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200 || code == 201); final BaseSecurity secm = BaseSecurityManager.getInstance(); final List<Identity> participants = secm.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup()); boolean found = false; for (final Identity participant : participants) { if (participant.getKey().equals(part3.getKey())) { found = true;// w ww . j a v a2 s . c o m } } assertTrue(found); }
From source file:org.olat.restapi.GroupMgmtTest.java
@Test public void testRemoveParticipant() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/participants/" + part2.getKey(); final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200);/* w ww .jav a 2 s . com*/ final BaseSecurity secm = BaseSecurityManager.getInstance(); final List<Identity> participants = secm.getIdentitiesOfSecurityGroup(g1.getPartipiciantGroup()); boolean found = false; for (final Identity participant : participants) { if (participant.getKey().equals(part2.getKey())) { found = true; } } assertFalse(found); }