Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream.

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static String getErrorMessage(@NotNull HttpMethod method) {
    try {// w  w w . j a  va2s . com
        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:com.ms.commons.utilities.HttpClientUtils.java

/**
 * <pre>/*from   w  w  w .j av  a2s  . c o  m*/
 * 
 * 
 * try {
 *      inputStream = getResponseBodyAsStream(method, tryTimes, soTimeoutMill);
 * } finally {
 *      IOUtils.closeQuietly(inputStream);
 *      method.releaseConnection();
 * }
 * 
 * @param method
 * @param tryTimes
 * @param soTimeoutMill
 * @return
 */
public static InputStream getResponseBodyAsStream(HttpMethod method, Integer tryTimes, Integer soTimeoutMill) {
    init();
    if (tryTimes == null) {
        tryTimes = 1;
    }
    if (soTimeoutMill == null) {
        soTimeoutMill = 20000;
    }
    method.getParams().setSoTimeout(soTimeoutMill);
    for (int i = 0; i < tryTimes; i++) {
        try {
            int responseCode = client.executeMethod(method);
            if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                return method.getResponseBodyAsStream();
            }
            logger.error(String.format(
                    "getResponseBodyAsString failed, responseCode: %s, should be 200, 301, 302", responseCode));
        } catch (Exception e) {
            logger.error("getResponseBodyAsString failed", e);
        } finally {
            // method releaseConnection  ResponseStream ResponseStream
            // ?finally { method.releaseConnection }
            // method.releaseConnection();
        }
    }
    return null;
}

From source file:com.intellij.tasks.impl.httpclient.ResponseUtil.java

public static String getResponseContentAsString(@Nonnull HttpMethod response) throws IOException {
    // Sometimes servers don't specify encoding and HttpMethod#getResponseBodyAsString
    // by default decodes from Latin-1, so we got to read byte stream and decode it from UTF-8
    // manually//from   ww w  .  j ava 2  s  .c om
    //if (!response.hasBeenUsed()) {
    //  return "";
    //}
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null && header.getValue().contains("charset")) {
        // ISO-8859-1 if charset wasn't specified in response
        return StringUtil.notNullize(response.getResponseBodyAsString());
    } else {
        InputStream stream = response.getResponseBodyAsStream();
        return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET);
    }
}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static ResponsePage request(@NotNull GithubAuthData auth, @NotNull String path,
        @Nullable String requestBody, @NotNull Collection<Header> headers, @NotNull HttpVerb verb)
        throws IOException {
    HttpMethod method = null;
    try {/*from w  w  w .j a v a  2s.  c  om*/
        String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + path;
        method = doREST(auth, uri, requestBody, headers, verb);

        checkStatusCode(method);

        InputStream resp = method.getResponseBodyAsStream();
        if (resp == null) {
            return new ResponsePage();
        }

        JsonElement ret = parseResponse(resp);
        if (ret.isJsonNull()) {
            return new ResponsePage();
        }

        Header header = method.getResponseHeader("Link");
        if (header != null) {
            String value = header.getValue();
            int end = value.indexOf(">; rel=\"next\"");
            int begin = value.lastIndexOf('<', end);
            if (begin >= 0 && end >= 0) {
                String newPath = GithubUrlUtil.removeProtocolPrefix(value.substring(begin + 1, end));
                int index = newPath.indexOf('/');

                return new ResponsePage(ret, newPath.substring(index));
            }
        }

        return new ResponsePage(ret);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host,
        String parameters) {/*from  w ww  . j a  v a 2  s.c o  m*/
    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;
}

From source file:com.cloud.test.regression.ApiCommand.java

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 {/*  www . j  ava 2s.  c o m*/
            // 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;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.file.RemoteFileReader.java

/**
 * Main constructor/*w  w  w .j  a  va 2 s .  c  o  m*/
 * @param source Source to connect
 * @throws IOException thrown by the reader constructor
 */
public RemoteFileReader(Source source) throws IOException {
    // gets repository properties
    String sourceName = source.getName();
    String url = source.getUrl();
    String sourceUrl = url + sourceName;
    String user = source.getUser();
    String password = source.getPassword();

    HttpMethod getMethod = httpGet(sourceUrl, user, password);
    InputStream is = getMethod.getResponseBodyAsStream();

    // gets the reader
    inputStreamReader = new InputStreamReader(is);

    numBytes = ((GetMethod) getMethod).getResponseContentLength();
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private InputStream getInputStream(HttpMethod method) {
    try {/*w w  w  . j  a  v  a  2 s.co m*/
        return method.getResponseBodyAsStream() != null ? new HttpMethodStream(method) : null;
    } catch (IOException e) {
        method.releaseConnection();
        throw new HTTPException("Unable to get InputStream from HttpClient", e);
    }
}

From source file:de.bermuda.arquillian.example.ContentTypeProxyServlet.java

private void copyResponseContent(HttpServletResponse resp, HttpMethod post) throws IOException {
    OutputStream out = resp.getOutputStream();
    InputStream input = post.getResponseBodyAsStream();
    StringBuilder responseBody = new StringBuilder();
    byte[] buffer = new byte[1024];
    while (input.read(buffer) >= 0) {

        responseBody.append(new String(buffer));
        out.write(buffer);/*from   ww  w  . j  a  v  a  2 s.c  om*/
    }
    requestLogger.info("ResponseBody: " + responseBody.toString());
}

From source file:com.intellij.coldFusion.mxunit.CfmlUnitRemoteTestsRunner.java

public static void executeScript(final CfmlUnitRunnerParameters params,
        final ProcessHandler processHandler/*final String webPath,
                                           final String componentFilePath,
                                           final String methodName,
                                           final ProcessHandler processHandler*/, final Project project)
        throws ExecutionException {
    final Ref<ExecutionException> ref = new Ref<>();

    ApplicationManager.getApplication().assertIsDispatchThread();

    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {//from   w ww.  ja v a2s.co  m
            final VirtualFile componentFile = LocalFileSystem.getInstance()
                    .refreshAndFindFileByPath(params.getPath());
            if (componentFile == null) {
                throw new ExecutionException("File " + params.getPath() + " not found");
            }

            // creating script files
            final VirtualFile directory = componentFile.getParent();
            final String launcherFileName = "mxunit-launcher.cfc";//generateUniqueName("mxunit-launcher", project);
            LOG.debug("Copying script file" + launcherFileName + " to component folder: " + directory);
            createFile(project, directory, launcherFileName, getLauncherText("/scripts/mxunit-launcher.cfc"));

            final String resultsFileName = "mxunit-result-capture.cfc";//generateUniqueName("mxunit-result-capture", project);
            LOG.debug("Copying results capture file " + resultsFileName + " to component folder: " + directory);
            createFile(project, directory, resultsFileName,
                    getLauncherText("/scripts/mxunit-result-capture.cfc"));

            // retrieving data through URL
            String webPath = params.getWebPath();
            if (webPath.endsWith("/") || webPath.endsWith("\\")) {
                webPath = webPath.substring(0, webPath.length() - 1);
            }
            String agentPath = webPath.substring(0, webPath.lastIndexOf('/')) + "/" + launcherFileName;
            LOG.debug("Retrieving data from coldfusion server by " + agentPath + " URL");
            BufferedReader reader = null;
            String agentUrl;
            if (params.getScope() == CfmlUnitRunnerParameters.Scope.Directory) {
                agentUrl = agentPath + "?method=executeDirectory&directoryName=" + componentFile.getName();
            } else {
                agentUrl = agentPath + "?method=executeTestCase&componentName="
                        + componentFile.getNameWithoutExtension();
                if (params.getScope() == CfmlUnitRunnerParameters.Scope.Method) {
                    agentUrl += "&methodName=" + params.getMethod();
                }
            }
            HttpMethod method = null;
            try {
                LOG.debug("Retrieving test results from: " + agentUrl);
                /*
                final FileObject httpFile = getManager().resolveFile(agentUrl);
                        
                reader = new BufferedReader(new InputStreamReader(httpFile.getContent().getInputStream()));
                */
                HttpClient client = new HttpClient();
                method = new GetMethod(agentUrl);
                int statusCode = client.executeMethod(method);
                if (statusCode != HttpStatus.SC_OK) {
                    LOG.debug("Http request failed: " + method.getStatusLine());
                    processHandler.notifyTextAvailable("Http request failed: " + method.getStatusLine(),
                            ProcessOutputTypes.SYSTEM);
                }
                final InputStream responseStream = method.getResponseBodyAsStream();
                reader = new BufferedReader(new InputStreamReader(responseStream));
                String line;
                while (!processHandler.isProcessTerminating() && !processHandler.isProcessTerminated()
                        && (line = reader.readLine()) != null) {
                    if (!StringUtil.isEmptyOrSpaces(line)) {
                        LOG.debug("MXUnit: " + line);
                        processHandler.notifyTextAvailable(line + "\n", ProcessOutputTypes.SYSTEM);
                    }
                }
            } catch (IOException e) {
                LOG.warn(e);
                processHandler.notifyTextAvailable(
                        "Failed to retrieve test results from the server at " + agentUrl + "\n",
                        ProcessOutputTypes.SYSTEM);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
            LOG.debug("Cleaning temporary files");
            deleteFile(project, directory.findChild(launcherFileName));
            deleteFile(project, directory.findChild(resultsFileName));
            if (!processHandler.isProcessTerminated() && !processHandler.isProcessTerminating()) {
                processHandler.destroyProcess();
            }
        } catch (ExecutionException e) {
            ref.set(e);
        }
    });
    if (!ref.isNull()) {
        throw ref.get();
    }
}