List of usage examples for org.apache.commons.httpclient HttpMethod getStatusText
public abstract String getStatusText();
From source file:com.cloud.test.utils.TestClient.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8080"; String testUrl = "/client/test"; int numThreads = 1; try {// w w w . j a v a2 s .c om // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } } final String server = host + ":" + port + testUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); String url = server + "?email=" + username + "&password=" + username + "&command=deploy"; s_logger.info("Launching test for user: " + username + " with url: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); boolean success = false; String reason = null; if (responseCode == 200) { if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. s_logger.info("Begin Linux SSH test"); reason = sshTest(method.getResponseHeader("linuxIP").getValue()); if (reason == null) { s_logger.info("Linux SSH test successful"); s_logger.info("Begin Windows SSH test"); reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); } } if (reason == null) { if (internet) { s_logger.info("Windows SSH test successful"); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (users == null) { s_logger.info("Sending cleanup command"); url = server + "?email=" + username + "&password=" + username + "&command=cleanup"; } else { s_logger.info("Sending stop DomR / destroy VM command"); url = server + "?email=" + username + "&password=" + username + "&command=stopDomR"; } method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { success = true; } else { reason = method.getStatusText(); } } else { // Just stop but don't destroy the VMs/Routers s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; responseCode = client.executeMethod(new GetMethod(url)); } } else { // Just stop but don't destroy the VMs/Routers reason = method.getStatusText(); s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } } catch (Exception e) { s_logger.warn("Error in thread", e); try { HttpClient client = new HttpClient(); String url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:com.urswolfer.intellij.plugin.gerrit.rest.GerritApiUtil.java
@Nullable private static JsonElement request(@NotNull String host, @Nullable String login, @Nullable String password, @NotNull String path, @Nullable String requestBody, boolean post) { HttpMethod method = null; try {//from www . ja va2 s. c o m method = doREST(host, login, password, path, requestBody, post); String resp = method.getResponseBodyAsString(); if (method.getStatusCode() != 200) { String message = String.format("Request not successful. Message: %s. Status-Code: %s.", method.getStatusText(), method.getStatusCode()); LOG.warn(message); throw new HttpStatusException(method.getStatusCode(), method.getStatusText(), message); } if (resp == null) { String message = String.format("Unexpectedly empty response: %s.", resp); LOG.warn(message); throw new RuntimeException(message); } return parseResponse(resp); } catch (IOException e) { LOG.warn(String.format("Request failed: %s", e.getMessage()), e); throw Throwables.propagate(e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java
/** * ?log.//from w w w. ja va 2 s . c o m * * @param httpMethod * the http method * @param httpClientConfig * the http client config * @return the http method response attribute map for log */ private static Map<String, Object> getHttpMethodResponseAttributeMapForLog(HttpMethod httpMethod, HttpClientConfig httpClientConfig) { Map<String, Object> map = new LinkedHashMap<String, Object>(); Object statusCode = null; try { statusCode = httpMethod.getStatusCode(); } catch (Exception e) { statusCode = e.getClass().getName() + " " + e.getMessage(); } String statusText = null; try { statusText = httpMethod.getStatusText(); } catch (Exception e) { statusText = e.getClass().getName() + " " + e.getMessage(); } map.put("httpMethod.getRequestHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getRequestHeaders())); map.put("httpMethod.getStatusCode()", statusCode); map.put("httpMethod.getStatusText()", statusText); map.put("httpMethod.getStatusLine()", "" + httpMethod.getStatusLine()); map.put("httpMethod.getResponseHeaders()-->map", NameValuePairUtil.toMap(httpMethod.getResponseHeaders())); map.put("httpMethod.getResponseFooters()", httpMethod.getResponseFooters()); map.put("httpClientConfig", httpClientConfig); return map; }
From source file:com.cloud.test.longrun.PerformanceWithAPI.java
private static int CreateForwardingRule(User myUser, String privateIp, String publicIp, String publicPort, String privatePort) throws IOException { String encodedPrivateIp = URLEncoder.encode("" + privateIp, "UTF-8"); String encodedPublicIp = URLEncoder.encode("" + publicIp, "UTF-8"); String encodedPrivatePort = URLEncoder.encode("" + privatePort, "UTF-8"); String encodedPublicPort = URLEncoder.encode("" + publicPort, "UTF-8"); String encodedApiKey = URLEncoder.encode(myUser.getApiKey(), "UTF-8"); int responseCode = 500; String requestToSign = "apiKey=" + encodedApiKey + "&command=createOrUpdateIpForwardingRule&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort; requestToSign = requestToSign.toLowerCase(); s_logger.info("Request to sign is " + requestToSign); String signature = TestClientWithAPI.signRequest(requestToSign, myUser.getSecretKey()); String encodedSignature = URLEncoder.encode(signature, "UTF-8"); String url = myUser.getDeveloperServer() + "?command=createOrUpdateIpForwardingRule" + "&publicIp=" + encodedPublicIp + "&publicPort=" + encodedPublicPort + "&privateIp=" + encodedPrivateIp + "&privatePort=" + encodedPrivatePort + "&protocol=tcp&apiKey=" + encodedApiKey + "&signature=" + encodedSignature;/*from ww w. j a v a 2 s. com*/ s_logger.info("Trying to create IP forwarding rule: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); responseCode = client.executeMethod(method); s_logger.info("create ip forwarding rule response code: " + responseCode); if (responseCode == 200) { s_logger.info("The rule is created successfully"); } else if (responseCode == 500) { InputStream is = method.getResponseBodyAsStream(); Map<String, String> errorInfo = TestClientWithAPI.getSingleValueFromXML(is, new String[] { "errorCode", "description" }); s_logger.error("create ip forwarding rule (linux) test failed with errorCode: " + errorInfo.get("errorCode") + " and description: " + errorInfo.get("description")); } else { s_logger.error("internal error processing request: " + method.getStatusText()); } return responseCode; }
From source file:com.kodokux.github.api.GithubApiUtil.java
@NotNull private static String getErrorMessage(@NotNull HttpMethod method) { try {/*from w w w.j a v a2s.c o m*/ InputStream resp = method.getResponseBodyAsStream(); if (resp != null) { GithubErrorMessageRaw error = fromJson(parseResponse(resp), GithubErrorMessageRaw.class); return method.getStatusText() + " - " + error.getMessage(); } } catch (IOException e) { LOG.info(e); } return method.getStatusText(); }
From source file:davmail.http.DavGatewayHttpClientFacade.java
/** * Build Http Exception from methode status * * @param method Http Method/* w w w. ja v a 2 s . com*/ * @return Http Exception */ public static HttpException buildHttpException(HttpMethod method) { int status = method.getStatusCode(); StringBuilder message = new StringBuilder(); message.append(status).append(' ').append(method.getStatusText()); try { message.append(" at ").append(method.getURI().getURI()); if (method instanceof CopyMethod || method instanceof MoveMethod) { message.append(" to ").append(method.getRequestHeader("Destination")); } } catch (URIException e) { message.append(method.getPath()); } // 440 means forbidden on Exchange if (status == 440) { return new LoginTimeoutException(message.toString()); } else if (status == HttpStatus.SC_FORBIDDEN) { return new HttpForbiddenException(message.toString()); } else if (status == HttpStatus.SC_NOT_FOUND) { return new HttpNotFoundException(message.toString()); } else if (status == HttpStatus.SC_PRECONDITION_FAILED) { return new HttpPreconditionFailedException(message.toString()); } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) { return new HttpServerErrorException(message.toString()); } else { return new HttpException(message.toString()); } }
From source file:com.thoughtworks.go.agent.launcher.ServerCall.java
public static ServerResponseWrapper invoke(HttpMethod method) throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS); try {//www .j a v a 2s . com final int status = httpClient.executeMethod(method); if (status == HttpStatus.SC_NOT_FOUND) { StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); out.println("Return Code: " + status); out.println("Few Possible Causes: "); out.println("1. Your Go Server is down or not accessible."); out.println( "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent."); out.close(); throw new Exception(sw.toString()); } if (status != HttpStatus.SC_OK) { throw new Exception("Got status " + status + " " + method.getStatusText() + " from server"); } for (Header header : method.getResponseHeaders()) { headers.put(header.getName(), header.getValue()); } return new ServerResponseWrapper(headers, method.getResponseBodyAsStream()); } catch (Exception e) { String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString(); LOG.error(message); throw new Exception(message, e); } finally { method.releaseConnection(); } }
From source file:de.micromata.jira.rest.core.util.RestException.java
public RestException(HttpMethod method) { this.statusCode = method.getStatusCode(); this.reasonPhrase = method.getStatusText(); try {/*ww w . j av a 2s .co m*/ InputStream inputStream = method.getResponseBodyAsStream(); if (inputStream != null) { InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8"); JsonReader jsonReader = new JsonReader(reader); jsonReader.setLenient(true); Gson gson = new Gson(); restErrorMessage = gson.fromJson(jsonReader, ErrorBean.class); } } catch (IOException e) { // nothing to say } finally { method.releaseConnection(); } }
From source file:net.sf.sail.webapp.domain.webservice.http.impl.HttpGetCurnitMapRequest.java
/** * @see net.sf.sail.webapp.domain.webservice.http.AbstractHttpRequest#isValidResponseStatus(org.apache.commons.httpclient.HttpMethod, * int)/*from w w w. j a va 2s .c o m*/ */ public boolean isValidResponseStatus(HttpMethod method, int actualStatusCode) throws IOException, HttpStatusCodeException { if (actualStatusCode == this.expectedResponseStatusCode) return true; String statusText = method.getStatusText(); logMethodInfo(method, actualStatusCode); throw new CurnitMapNotFoundException(statusText); }
From source file:net.sf.sail.webapp.domain.webservice.http.AbstractHttpRequest.java
/** * Logs the HttpMethod response information * // w w w. j a v a 2s .c o m * @param method the HttpMethod response. * @param actualStatusCode The status code retrieved from the response. * @throws IOException If the response body cannot be retrieved. */ protected void logMethodInfo(HttpMethod method, int actualStatusCode) throws IOException { if (logger.isWarnEnabled()) { logger.warn(actualStatusCode + ": " + method.getStatusText()); logger.warn("body: " + method.getResponseBodyAsString()); } }