Java Code Examples for org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream()

The following examples show how to use org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MailUtils.java    From document-management-system with GNU General Public License v2.0 6 votes vote down vote up
/**
 * User tinyurl service as url shorter Depends on commons-httpclient:commons-httpclient:jar:3.0 because of
 * org.apache.jackrabbit:jackrabbit-webdav:jar:1.6.4
 */
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
	HttpClient httpclient = new HttpClient();

	// Prepare a request object
	HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
	method.setQueryString(new NameValuePair[]{new NameValuePair("url", fullUrl)});
	httpclient.executeMethod(method);
	InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
	StringWriter sw = new StringWriter();
	int c;
	while ((c = isr.read()) != -1)
		sw.write(c);
	isr.close();
	method.releaseConnection();

	return sw.toString();
}
 
Example 2
Source File: HttpUtils.java    From http4e with Apache License 2.0 6 votes vote down vote up
public static void dumpResponse( HttpMethod httpmethod, PrintStream out){

      try {
         out.println("------------");
         out.println(httpmethod.getStatusLine().toString());

         Header[] h = httpmethod.getResponseHeaders();
         for (int i = 0; i < h.length; i++) {
            out.println(h[i].getName() + ": " + h[i].getValue());
         }

         InputStreamReader inR = new InputStreamReader(httpmethod.getResponseBodyAsStream());
         BufferedReader buf = new BufferedReader(inR);
         String line;
         while ((line = buf.readLine()) != null) {
            out.println(line);
         }
         out.println("------------");

      } catch (Exception e) {
         throw new RuntimeException(e);
      }
   }
 
Example 3
Source File: User.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public void launchUser() throws IOException {
    String encodedUsername = URLEncoder.encode(this.getUserName(), "UTF-8");
    this.encryptedPassword = TestClientWithAPI.createMD5Password(this.getPassword());
    String encodedPassword = URLEncoder.encode(this.encryptedPassword, "UTF-8");
    String url =
        this.server + "?command=createUser&username=" + encodedUsername + "&password=" + encodedPassword +
            "&firstname=Test&lastname=Test&[email protected]&domainId=1";
    String userIdStr = null;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);

    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> userIdValues = TestClientWithAPI.getSingleValueFromXML(is, new String[] {"id"});
        userIdStr = userIdValues.get("id");
        if ((userIdStr != null) && (Long.parseLong(userIdStr) != -1)) {
            this.setUserId(userIdStr);
        }
    }
}
 
Example 4
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public InputStream openInputStream() throws IOException {
  HttpMethod res = getResult(true);
  InputStream is = res.getResponseBodyAsStream();

  if (is == null) {
    return null;
  }

  InputWrapper iw = new InputWrapper(is);

  synchronized(iss) {
    iss.add(iw);
  }

  return iw;
}
 
Example 5
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private static String executeRegistration(String server, String username, String password) throws HttpException, IOException {
    String url = server + "?command=registerUserKeys&id=" + s_userId.get().toString();
    s_logger.info("registering: " + username);
    String returnValue = null;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] {"apikey", "secretkey"});
        s_apiKey.set(requestKeyValues.get("apikey"));
        returnValue = requestKeyValues.get("secretkey");
    } else {
        s_logger.error("registration failed with error code: " + responseCode);
    }
    return returnValue;
}
 
Example 6
Source File: TestClientWithAPI.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private static String executeRegistration(String server, String username, String password) throws HttpException, IOException {
    String url = server + "?command=registerUserKeys&id=" + s_userId.get().toString();
    s_logger.info("registering: " + username);
    String returnValue = null;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] {"apikey", "secretkey"});
        s_apiKey.set(requestKeyValues.get("apikey"));
        returnValue = requestKeyValues.get("secretkey");
    } else {
        s_logger.error("registration failed with error code: " + responseCode);
    }
    return returnValue;
}
 
Example 7
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public byte[] decryptResponseBody(HttpMethod method) throws IOException
{
    // TODO fileoutputstream if content is especially large?
    InputStream body = method.getResponseBodyAsStream();
    if(body != null)
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FileCopyUtils.copy(body, out);

        AlgorithmParameters params = decodeAlgorithmParameters(method);
        if(params != null)
        {
            byte[] decrypted = encryptor.decrypt(KeyProvider.ALIAS_SOLR, params, out.toByteArray());
            return decrypted;
        }
        else
        {
            throw new AlfrescoRuntimeException("Unable to decrypt response body, missing encryption algorithm parameters");
        }
    }
    else
    {
        return null;
    }
}
 
Example 8
Source File: ApiCommand.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public Element queryAsyncJobResult(String jobId) {
    Element returnBody = null;
    int code = 400;
    String resultUrl = this.host + ":8096/?command=queryAsyncJobResult&jobid=" + jobId;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(resultUrl);
    while (true) {
        try {
            code = client.executeMethod(method);
            if (code == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();
                returnBody = doc.getDocumentElement();
                Element jobStatusTag = (Element)returnBody.getElementsByTagName("jobstatus").item(0);
                String jobStatus = jobStatusTag.getTextContent();
                if (jobStatus.equals("0")) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        s_logger.debug("[ignored] interupted while during async job result query.");
                    }
                } else {
                    break;
                }
                method.releaseConnection();
            } else {
                s_logger.error("Error during queryJobAsync. Error code is " + code);
                this.responseCode = code;
                return null;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    }
    return returnBody;
}
 
Example 9
Source File: PerformanceWithAPI.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
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;

    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;
}
 
Example 10
Source File: TestClientWithAPI.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private static boolean getNetworkStat(String server) {
    try {
        String url = server + "?command=listAccountStatistics&account=" + s_account.get();
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        s_logger.info("listAccountStatistics response code: " + responseCode);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            Map<String, String> requestKeyValues = getSingleValueFromXML(is, new String[] {"receivedbytes", "sentbytes"});
            int bytesReceived = Integer.parseInt(requestKeyValues.get("receivedbytes"));
            int bytesSent = Integer.parseInt(requestKeyValues.get("sentbytes"));
            if ((bytesReceived > 100000000) && (bytesSent > 0)) {
                s_logger.info("Network stat is correct for account" + s_account.get() + "; bytest received is " + bytesReceived + " and bytes sent is " + bytesSent);
                return true;
            } else {
                s_logger.error("Incorrect value for bytes received/sent for the account " + s_account.get() + ". We got " + bytesReceived + " bytes received; " +
                    " and " + bytesSent + " bytes sent");
                return false;
            }

        } else {
            s_logger.error("listAccountStatistics failed with error code: " + responseCode + ". Following URL was sent: " + url);
            return false;
        }
    } catch (Exception ex) {
        s_logger.error("Exception while sending command listAccountStatistics");
        return false;
    }
}
 
Example 11
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private static int executeEventsAndBilling(String server, String developerServer) throws HttpException, IOException {
    // test steps:
    // - get all the events in the system for all users in the system
    // - generate all the usage records in the system
    // - get all the usage records in the system

    // -----------------------------
    // GET EVENTS
    // -----------------------------
    String url = server + "?command=listEvents&page=1&account=" + s_account.get();

    s_logger.info("Getting events for the account " + s_account.get());
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("get events response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, List<String>> eventDescriptions = getMultipleValuesFromXML(is, new String[] {"description"});
        List<String> descriptionText = eventDescriptions.get("description");
        if (descriptionText == null) {
            s_logger.info("no events retrieved...");
        } else {
            for (String text : descriptionText) {
                s_logger.info("event: " + text);
            }
        }
    } else {
        s_logger.error("list events failed with error code: " + responseCode + ". Following URL was sent: " + url);

        return responseCode;
    }
    return responseCode;
}
 
Example 12
Source File: HttpUtils.java    From http4e with Apache License 2.0 5 votes vote down vote up
public static void dumpResponse( HttpMethod httpmethod, StringBuilder httpResponsePacket, StringBuilder respBody){
   try {
      httpResponsePacket.append('\n');
      httpResponsePacket.append(httpmethod.getStatusLine().toString());
      httpResponsePacket.append('\n');

      Header[] h = httpmethod.getResponseHeaders();
      for (int i = 0; i < h.length; i++) {
         httpResponsePacket.append(h[i].getName() + ": " + h[i].getValue());
         httpResponsePacket.append('\n');
      }

      InputStreamReader inR = new InputStreamReader(httpmethod.getResponseBodyAsStream());
      BufferedReader buf = new BufferedReader(inR);
      String line;
      while ((line = buf.readLine()) != null) {
         httpResponsePacket.append(line);
         httpResponsePacket.append('\n');
         respBody.append(line);
         respBody.append('\n');
      }
      httpResponsePacket.append('\n');

   } catch (Exception e) {
      throw new RuntimeException(e);
   }
}
 
Example 13
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Element queryAsyncJobResult(String host, InputStream inputStream) {
    Element returnBody = null;

    Map<String, String> values = getSingleValueFromXML(inputStream, new String[] {"jobid"});
    String jobId = values.get("jobid");

    if (jobId == null) {
        s_logger.error("Unable to get a jobId");
        return null;
    }

    //s_logger.info("Job id is " + jobId);
    String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(resultUrl);
    while (true) {
        try {
            client.executeMethod(method);
            //s_logger.info("Method is executed successfully. Following url was sent " + resultUrl);
            InputStream is = method.getResponseBodyAsStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            returnBody = doc.getDocumentElement();
            doc.getDocumentElement().normalize();
            Element jobStatusTag = (Element)returnBody.getElementsByTagName("jobstatus").item(0);
            String jobStatus = jobStatusTag.getTextContent();
            if (jobStatus.equals("0")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    s_logger.debug("[ignored] interupted while during async job result query.");
                }
            } else {
                break;
            }

        } catch (Exception ex) {
            s_logger.error(ex);
        }
    }
    return returnBody;
}
 
Example 14
Source File: TestClientWithAPI.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static Element queryAsyncJobResult(String host, InputStream inputStream) {
    Element returnBody = null;

    Map<String, String> values = getSingleValueFromXML(inputStream, new String[] {"jobid"});
    String jobId = values.get("jobid");

    if (jobId == null) {
        s_logger.error("Unable to get a jobId");
        return null;
    }

    // s_logger.info("Job id is " + jobId);
    String resultUrl = host + "?command=queryAsyncJobResult&jobid=" + jobId;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(resultUrl);
    while (true) {
        try {
            client.executeMethod(method);
            // s_logger.info("Method is executed successfully. Following url was sent " + resultUrl);
            InputStream is = method.getResponseBodyAsStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            returnBody = doc.getDocumentElement();
            doc.getDocumentElement().normalize();
            Element jobStatusTag = (Element)returnBody.getElementsByTagName("jobstatus").item(0);
            String jobStatus = jobStatusTag.getTextContent();
            if (jobStatus.equals("0")) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    s_logger.debug("[ignored] interupted while during async job result query.");
                }
            } else {
                break;
            }

        } catch (Exception ex) {
            s_logger.error(ex);
        }
    }
    return returnBody;
}
 
Example 15
Source File: ApiCommand.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static boolean verifyEvents(String fileName, String level, String host, String account) {
    boolean result = false;
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    String key = "";

    File file = new File(fileName);
    if (file.exists()) {
        Properties pro = new Properties();
        try {
            // get expected events
            FileInputStream in = new FileInputStream(file);
            pro.load(in);
            Enumeration<?> en = pro.propertyNames();
            while (en.hasMoreElements()) {
                key = (String)en.nextElement();
                expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
            }

            // get actual events
            String url = host + "/?command=listEvents&account=" + account + "&level=" + level + "&domainid=1&pagesize=100";
            s_logger.info("Getting events with the following url " + url);
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            int responseCode = client.executeMethod(method);
            if (responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is, new String[] {"event"});

                for (int i = 0; i < eventValues.size(); i++) {
                    HashMap<String, String> element = eventValues.get(i);
                    if (element.get("level").equals(level)) {
                        if (actualEvents.containsKey(element.get("type")) == true) {
                            actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                        } else {
                            actualEvents.put(element.get("type"), 1);
                        }
                    }
                }
            }
            method.releaseConnection();

            // compare actual events with expected events

            // compare expected result and actual result
            Iterator<?> iterator = expectedEvents.keySet().iterator();
            Integer expected;
            Integer actual;
            int fail = 0;
            while (iterator.hasNext()) {
                expected = null;
                actual = null;
                String type = iterator.next().toString();
                expected = expectedEvents.get(type);
                actual = actualEvents.get(type);
                if (actual == null) {
                    s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " +
                        expected);
                    fail++;
                } else if (expected.compareTo(actual) != 0) {
                    fail++;
                    s_logger.info("Amount of events of  " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected +
                        ", actual number is " + actual);
                }
            }
            if (fail == 0) {
                result = true;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    } else {
        s_logger.info("File " + fileName + " not found");
    }
    return result;
}
 
Example 16
Source File: ApiCommand.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host, String parameters) {
    boolean result = false;
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    try {
        // get actual events
        String url = host + "/?command=listEvents&" + parameters;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is, new String[] {"event"});

            for (int i = 0; i < eventValues.size(); i++) {
                HashMap<String, String> element = eventValues.get(i);
                if (element.get("level").equals(level)) {
                    if (actualEvents.containsKey(element.get("type")) == true) {
                        actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                    } else {
                        actualEvents.put(element.get("type"), 1);
                    }
                }
            }
        }
        method.releaseConnection();
    } catch (Exception ex) {
        s_logger.error(ex);
    }

    // compare actual events with expected events
    Iterator<?> iterator = expectedEvents.keySet().iterator();
    Integer expected;
    Integer actual;
    int fail = 0;
    while (iterator.hasNext()) {
        expected = null;
        actual = null;
        String type = iterator.next().toString();
        expected = expectedEvents.get(type);
        actual = actualEvents.get(type);
        if (actual == null) {
            s_logger.error("Event of type " + type + " and level " + level + " is missing in the listEvents response. Expected number of these events is " + expected);
            fail++;
        } else if (expected.compareTo(actual) != 0) {
            fail++;
            s_logger.info("Amount of events of  " + type + " type and level " + level + " is incorrect. Expected number of these events is " + expected +
                ", actual number is " + actual);
        }
    }

    if (fail == 0) {
        result = true;
    }

    return result;
}
 
Example 17
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * 转发返回数据,包括转发请求的cookie、Header、以及返回数据流(response)设置到转发前请求的响应对象(response)中。
 * </p>
 * @param appServer 当前应用相关信息
 * @param response  转发前的响应对象(即进本filter时的response)
 * @param client    请求客户端对象
 * @param httpMethod  Http请求
 * @throws IOException
 */
private void transmitResponse(AppServer appServer, HttpServletResponse response, HttpClient client,
           HttpMethod httpMethod) throws IOException {
       
	// 转发返回的Cookies信息
    org.apache.commons.httpclient.Cookie[] cookies = client.getState().getCookies();
       for (int i = 0; i < cookies.length; i++) {
           String cookieName = cookies[i].getName();
           ApplicationContext appContext = Context.getApplicationContext();
		if (cookieName.equals(appContext.getCurrentAppCode())) continue;
           
           if (cookieName.equals(appServer.getSessionIdName())) {
               cookieName = appServer.getCode();
           }
           
           String cpath = appContext.getCurrentAppServer().getPath();
           javax.servlet.http.Cookie cookie = HttpClientUtil.createCookie(cookieName, cookies[i].getValue(), cpath);
           response.addCookie(cookie);
       }
       
       // 转发返回的Header信息
       Header contentType = httpMethod.getRequestHeader(HttpClientUtil.CONTENT_TYPE);
       if(contentType != null && contentType.getValue().indexOf("multipart/form-data") < 0) {
           response.setContentType(contentType.getValue());
       }
       
       // 转发返回数据流信息: log.debug(httpMethod.getResponseBodyAsString());
       ServletOutputStream out = response.getOutputStream();
       InputStream in = httpMethod.getResponseBodyAsStream();
       byte[] data = new byte[1024];
       int len = in.read(data);
       while (len > 0) {
           out.write(data, 0, len);
           len = in.read(data);
       }
       out.flush();
       out.close();
       out = null;
       
       in.close();
       in = null;
}