List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:com.cloud.network.brocade.BrocadeVcsApiTest.java
@Test public void testGetSwitchStatus() throws BrocadeVcsApiException, IOException { // Prepare//w ww . j a v a 2 s .c o m method = mock(HttpPost.class); response = mock(HttpResponse.class); final StatusLine statusLine = mock(StatusLine.class); when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK); when(response.getStatusLine()).thenReturn(statusLine); when(response.getEntity()).thenReturn(new StringEntity(OUTPUT_XML_RESPONSE)); // Execute Output result = api.getSwitchStatus(); // Assert verify(method, times(1)).releaseConnection(); assertEquals("Wrong URI for get SwitchStatus REST service", Constants.STATUS_URI, uri); assertEquals("Wrong HTTP method for get SwitchStatus REST service", "post", type); assertEquals("Wrong state for get SwitchStatus REST service", "Online", result.getVcsNodes().getVcsNodeInfo().get(0).getNodeState()); }
From source file:com.autentia.mvn.plugin.changes.HttpRequest.java
/** * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns * the response as String.//ww w. j a va 2s. c om * * @param cl the HttpClient * @param link the URL * @throws HttpStatusException * @throws IOException */ public byte[] sendGetRequest(final HttpClient cl, final String link) throws HttpStatusException, IOException { try { final GetMethod gm = new GetMethod(link); this.getLog().info("Downloading from Bugzilla at: " + link); gm.setFollowRedirects(true); cl.executeMethod(gm); final StatusLine sl = gm.getStatusLine(); if (sl == null) { this.getLog().error("Unknown error validating link: " + link); throw new HttpStatusException("UNKNOWN STATUS"); } // if we get a redirect, do so if (gm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { final Header locationHeader = gm.getResponseHeader("Location"); if (locationHeader == null) { this.getLog().warn("Site sent redirect, but did not set Location header"); } else { final String newLink = locationHeader.getValue(); this.getLog().debug("Following redirect to " + newLink); this.sendGetRequest(cl, newLink); } } if (gm.getStatusCode() == HttpStatus.SC_OK) { final InputStream is = gm.getResponseBodyAsStream(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buff = new byte[256]; int readed = is.read(buff); while (readed != -1) { baos.write(buff, 0, readed); readed = is.read(buff); } this.getLog().debug("Downloading from Bugzilla was successful"); return baos.toByteArray(); } else { this.getLog().warn("Downloading from Bugzilla failed. Received: [" + gm.getStatusCode() + "]"); throw new HttpStatusException("WRONG STATUS"); } } catch (final HttpException e) { if (this.getLog().isDebugEnabled()) { this.getLog().error("Error downloading issues from Bugzilla:", e); } else { this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage()); } throw e; } catch (final IOException e) { if (this.getLog().isDebugEnabled()) { this.getLog().error("Error downloading issues from Bugzilla:", e); } else { this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage()); } throw e; } }
From source file:edu.unc.lib.dl.fedora.FedoraAccessControlService.java
/** * @Inheritdoc//from w w w . ja va 2 s . c o m * * Retrieves the access control from a Fedora JSON endpoint, represented by role to group relations. */ @SuppressWarnings("unchecked") @Override public ObjectAccessControlsBean getObjectAccessControls(PID pid) { GetMethod method = new GetMethod(this.aclEndpointUrl + pid.getPid() + "/getAccess"); try { int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { Map<?, ?> result = (Map<?, ?>) mapper.readValue(method.getResponseBodyAsStream(), Object.class); Map<String, List<String>> roles = (Map<String, List<String>>) result.get("roles"); Map<String, List<String>> globalRoles = (Map<String, List<String>>) result.get("globals"); List<String> embargoes = (List<String>) result.get("embargoes"); List<String> publicationStatus = (List<String>) result.get("publicationStatus"); List<String> objectState = (List<String>) result.get("objectState"); return new ObjectAccessControlsBean(pid, roles, globalRoles, embargoes, publicationStatus, objectState); } } catch (HttpException e) { log.error("Failed to retrieve object access control for " + pid, e); } catch (IOException e) { log.error("Failed to retrieve object access control for " + pid, e); } finally { method.releaseConnection(); } return null; }
From source file:com.cerema.cloud2.lib.resources.files.ReadRemoteFolderOperation.java
/** * Performs the read operation./*from w w w . j a v a2 s. c o m*/ * * @param client Client object to communicate with the remote ownCloud server. */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; PropFindMethod query = null; try { // remote request query = new PropFindMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath), WebdavUtils.getAllPropSet(), // PropFind Properties DavConstants.DEPTH_1); int status = client.executeMethod(query); // check and process response boolean isSuccess = (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK); if (isSuccess) { // get data from remote folder MultiStatus dataInServer = query.getResponseBodyAsMultiStatus(); readData(dataInServer, client); // Result of the operation result = new RemoteOperationResult(true, status, query.getResponseHeaders()); // Add data to the result if (result.isSuccess()) { result.setData(mFolderAndFiles); } } else { // synchronization failed client.exhaustResponse(query.getResponseBodyAsStream()); result = new RemoteOperationResult(false, status, query.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); } finally { if (query != null) query.releaseConnection(); // let the connection available for other methods if (result.isSuccess()) { Log_OC.i(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); } else { if (result.isException()) { Log_OC.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage(), result.getException()); } else { Log_OC.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); } } } return result; }
From source file:com.exquance.jenkins.plugins.conduit.ConduitAPIClient.java
/** * Call the conduit API of Phabricator//from w ww . j av a 2 s . c om * @param action Name of the API call * @param params The data to send to Harbormaster * @return The result as a JSONObject * @throws IOException If there was a problem reading the response * @throws ConduitAPIException If there was an error calling conduit */ public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpUriRequest request = createRequest(action, params); HttpResponse response; try { response = client.execute(request); } catch (ClientProtocolException e) { throw new ConduitAPIException(e.getMessage()); } InputStream responseBody = response.getEntity().getContent(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new ConduitAPIException(responseBody.toString(), response.getStatusLine().getStatusCode()); } JsonSlurper jsonParser = new JsonSlurper(); return (JSONObject) jsonParser.parse(responseBody); }
From source file:guru.nidi.atlassian.remote.script.RemoteConfluence.java
Object executeImpl(String command, Object... parameters) throws RpcException { PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/confluenceservice-v2/" + command); post.setRequestHeader("Content-Type", "application/json"); HttpUtils.setAuthHeader(post, username, password); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {// w w w . j a v a2s.c om mapper.writeValue(baos, parameters); post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("not ok"); } try { ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), ErrorResponse.class); throw new RpcException(errorResponse); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<HashMap<String, Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<ArrayList<Object>>() { }); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:it.geosolutions.geoserver.rest.HTTPUtils.java
/** * Performs an HTTP GET on the given URL. <BR> * Basic auth is used if both username and pw are not null. * /*from ww w . j av a 2 s . co m*/ * @param url The URL where to connect to. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 * (OK). * @throws MalformedURLException */ public static String get(String url, String username, String pw) { GetMethod httpMethod = null; HttpClient client = new HttpClient(); HttpConnectionManager connectionManager = client.getHttpConnectionManager(); try { setAuth(client, url, username, pw); httpMethod = new GetMethod(url); connectionManager.getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); String response = IOUtils.toString(is); IOUtils.closeQuietly(is); if (response.trim().length() == 0) { // sometime gs rest fails LOGGER.warn("ResponseBody is empty"); return null; } else { return response; } } else { LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url); } } catch (ConnectException e) { LOGGER.info("Couldn't connect to [" + url + "]"); } catch (IOException e) { LOGGER.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); connectionManager.closeIdleConnections(0); } return null; }
From source file:com.unicauca.braim.http.HttpBraimClient.java
public Song[] GET_Songs(int page, String access_token, JButton bt_next_list, JButton bt_previous_list) throws IOException { if (page == 1) { bt_previous_list.setEnabled(false); } else {// w ww.ja v a 2 s .c om bt_previous_list.setEnabled(true); } String token = "braim_token=" + access_token; String data = "page=" + page + "&per_page=10"; GetMethod method = new GetMethod(api_url + "/api/v1/songs?" + token + "&" + data); Song[] songList = null; Gson gson = new Gson(); try { method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); Integer total_pages = Integer.parseInt(method.getResponseHeader("total_pages").getValue()); System.out.println("TOTAL SONG PAGES= " + method.getResponseHeader("total_pages")); String response = new String(responseBody, "UTF-8"); songList = gson.fromJson(response, Song[].class); if (page == total_pages) { bt_next_list.setEnabled(false); } else { bt_next_list.setEnabled(true); } } catch (UnsupportedEncodingException ex) { Logger.getLogger(HttpBraimClient.class.getName()).log(Level.SEVERE, null, ex); } return songList; }
From source file:com.gagein.crawler.FileDownLoader.java
public String downloadLink(String url, HtmlFileBean hfb) { /* 1.? HttpClinet ? */ HttpClient httpClient = new HttpClient(); // Http 5s// w w w . j a v a 2 s.c o m httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2.? GetMethod ? */ GetMethod getMethod = new GetMethod(url); // get 5s getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); // ?? getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); /* 3. HTTP GET */ try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } /* 4.? HTTP ? */ byte[] responseBody = getMethod.getResponseBody();// ? // ? url ???? url = FileUtils.getFileNameByUrl(url); saveToLocal(responseBody, hfb.getDirPath() + File.separator + url); } catch (HttpException e) { // ????? logger.debug("Please check your provided http " + "address!"); e.printStackTrace(); } catch (IOException e) { // ? logger.debug("?"); e.printStackTrace(); } finally { // logger.debug("=======================" + url + "=============?"); getMethod.releaseConnection(); } return hfb.getDirPath() + url; }
From source file:com.bdaum.juploadr.uploadapi.locrrest.LocrMethod.java
public boolean execute() throws ProtocolException, CommunicationException { HttpMethodBase method = getMethod(); boolean rv = false; try {// w ww . ja v a 2 s .c o m int response = client.executeMethod(method); if (HttpStatus.SC_OK == response) { rv = parseResponse(method.getResponseBodyAsString()); if (!rv) { throw defaultExceptionFor(handler.getErrorCode()); } } else { throw new CommunicationException(Messages.getString("juploadr.ui.error.bad.http.response", //$NON-NLS-1$ Activator.getStatusText(response))); } } catch (InvalidAuthTokenException iat) { ((RestLocrApi) session.getApi()).reauthAccount(session); } catch (HttpException e) { throw new CommunicationException(e.getMessage(), e); } catch (IOException e) { throw new CommunicationException(e.getMessage(), e); } finally { method.releaseConnection(); } return rv; }