List of usage examples for org.apache.commons.httpclient HttpMethod releaseConnection
public abstract void releaseConnection();
From source file:org.olat.restapi.GroupMgmtTest.java
@Test public void testAddTutor() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/owners/" + owner3.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> owners = secm.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); boolean found = false; for (final Identity owner : owners) { if (owner.getKey().equals(owner3.getKey())) { found = true;//from w w w . j av a 2 s.c o m } } assertTrue(found); }
From source file:org.olat.restapi.GroupMgmtTest.java
@Test public void testRemoveTutor() throws HttpException, IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final String request = "/groups/" + g1.getKey() + "/owners/" + owner2.getKey(); final HttpMethod method = createDelete(request, MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); method.releaseConnection(); assertTrue(code == 200);/*from w w w.j a va 2 s . com*/ final BaseSecurity secm = BaseSecurityManager.getInstance(); final List<Identity> owners = secm.getIdentitiesOfSecurityGroup(g1.getOwnerGroup()); boolean found = false; for (final Identity owner : owners) { if (owner.getKey().equals(owner2.getKey())) { found = true; } } assertFalse(found); }
From source file:org.olat.restapi.UserMgmtTest.java
@Test public void testGetUsers() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final HttpMethod method = createGet("/users", MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200);/*from www . j a v a 2 s.c o m*/ final String body = method.getResponseBodyAsString(); method.releaseConnection(); final List<UserVO> vos = parseUserArray(body); final List<Identity> identities = BaseSecurityManager.getInstance().getIdentitiesByPowerSearch(null, null, true, null, null, null, null, null, null, null, Identity.STATUS_VISIBLE_LIMIT); assertNotNull(vos); assertFalse(vos.isEmpty()); assertEquals(vos.size(), identities.size()); }
From source file:org.olat.restapi.UserMgmtTest.java
@Test public void testGetUser() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final HttpMethod method = createGet("/users/" + id1.getKey(), MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200);/*from www. j ava 2 s .co m*/ final String body = method.getResponseBodyAsString(); method.releaseConnection(); final UserVO vo = parse(body, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id1.getKey()); assertEquals(vo.getLogin(), id1.getName()); // are the properties there? assertFalse(vo.getProperties().isEmpty()); }
From source file:org.olat.restapi.UserMgmtTest.java
@Test public void testGetUserNotAdmin() throws IOException { final HttpClient c = loginWithCookie("rest-one", "A6B7C8"); final HttpMethod method = createGet("/users/" + id2.getKey(), MediaType.APPLICATION_JSON, true); final int code = c.executeMethod(method); assertEquals(code, 200);// w w w . ja v a 2 s .c o m final String body = method.getResponseBodyAsString(); method.releaseConnection(); final UserVO vo = parse(body, UserVO.class); assertNotNull(vo); assertEquals(vo.getKey(), id2.getKey()); assertEquals(vo.getLogin(), id2.getName()); // no properties for security reason assertTrue(vo.getProperties().isEmpty()); }
From source file:org.openanzo.client.BinaryStoreClient.java
protected int executeAuthenticatedHttpClientMethod(HttpMethod method) throws HttpException, IOException, AnzoException { method.addRequestHeader("X-Requested-With", "XMLHttpRequest"); String serviceUser = anzoClient.getServiceUser(); if (serviceUser != null && serviceUser.equals(anzoClient.clientDatasource.getServiceUser())) method.addRequestHeader(AUTHRUNAS_HEADER, anzoClient.clientDatasource.getServiceUser()); int rc = httpclient.executeMethod(method); if (rc == HttpStatus.SC_FORBIDDEN) { method.releaseConnection(); authenticate();/*w w w. j a va 2 s. c o m*/ rc = httpclient.executeMethod(method); } return rc; }
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests./*from w w w . j a v a 2 s . c o m*/ * * @return <code>true</code> if login was successful; <code>false</code> otherwise. */ public boolean doLogin() { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } try { final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (Exception e) { logger.error("Parsing response failed"); } } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.openhab.binding.frontiersiliconradio.internal.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * //from w ww . j a v a 2 s .c o m * Typically used for changing parameters. * * @param REST * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) { // 3 retries upon failure for (int i = 0; i < 3; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '" + url + "'"); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); isLoggedIn = false; method.releaseConnection(); continue; } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("got result: " + responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; method.releaseConnection(); continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) return result; isLoggedIn = false; method.releaseConnection(); continue; // try again } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); isLoggedIn = false; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.openhab.binding.garadget.internal.Connection.java
/** * Send a command to the Particle REST API (convenience function). * * @param device//from ww w. ja v a 2 s.c om * the device context, or <code>null</code> if not needed for this command. * @param funcName * the function name to call, or variable/field to retrieve if <code>command</code> is * <code>null</code>. * @param user * the user name to use in Basic Authentication if the funcName would require Basic Authentication. * @param pass * the password to use in Basic Authentication if the funcName would require Basic Authentication. * @param command * the command to send to the API. * @param proc * a callback object that receives the status code and response body, or <code>null</code> if not * needed. */ public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) { String url = null; String httpMethod = null; String content = null; String contentType = null; Properties headers = new Properties(); logger.trace("sendCommand: funcName={}", funcName); switch (funcName) { case "createToken": httpMethod = HTTP_POST; url = TOKEN_URL; content = command; contentType = APPLICATION_FORM_URLENCODED; break; case "deleteToken": httpMethod = HTTP_DELETE; url = String.format(ACCESS_TOKENS_URL, tokens.accessToken); break; case "getDevices": httpMethod = HTTP_GET; url = String.format(GET_DEVICES_URL, tokens.accessToken); break; default: url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken); if (command == null) { // retrieve a variable httpMethod = HTTP_GET; } else { // call a function httpMethod = HTTP_POST; content = command; contentType = APPLICATION_JSON; } break; } HttpClient client = new HttpClient(); // Only perform basic authentication when we aren't using OAuth if (!url.contains("access_token=")) { Credentials credentials = new UsernamePasswordCredentials(user, pass); client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } HttpMethod method = createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (String httpHeaderKey : headers.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey))); logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey)); } try { // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null)); logger.trace("content='{}', contentType='{}'", content, contentType); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '{}'", method.getURI()); } catch (URIException e) { logger.debug(e.getMessage()); } } int statusCode = client.executeMethod(method); if (statusCode >= HttpStatus.SC_BAD_REQUEST) { logger.debug("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug("Body of response: {}", responseBody); } if (proc != null) { proc.handleResponse(statusCode, responseBody); } } catch (HttpException he) { logger.warn("{}", he); } catch (IOException ioe) { logger.debug("{}", ioe); } finally { method.releaseConnection(); } }