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.cloud.test.regression.ApiCommand.java

public Element queryAsyncJobResult(String jobId) {
    Element returnBody = null;/*from w w  w .  j ava2 s .c o  m*/
    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) {
                    }
                } 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;
}

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

public void sendCommand(HttpClient client, Connection conn) {
    if (TestCaseEngine._printUrl == true) {
        s_logger.info("url is " + this.command);
    }/*ww  w. j  a v a 2 s.c o  m*/

    if (this.getCommandType() == CommandType.SCRIPT) {
        try {
            s_logger.info("Executing command " + this.command);
            Runtime rtime = Runtime.getRuntime();
            Process child = rtime.exec(this.command);
            Thread.sleep(10000);
            int retCode = child.waitFor();
            if (retCode != 0) {
                this.responseCode = retCode;
            } else {
                this.responseCode = 200;
            }

        } catch (Exception ex) {
            s_logger.error("Unable to execute a command " + this.command, ex);
        }
    } else if (this.getCommandType() == CommandType.MYSQL) {
        try {
            Statement stmt = conn.createStatement();
            this.result = stmt.executeQuery(this.command);
            this.responseCode = 200;
        } catch (Exception ex) {
            this.responseCode = 400;
            s_logger.error("Unable to execute mysql query " + this.command, ex);
        }
    } else {
        HttpMethod method = new GetMethod(this.command);
        try {
            this.responseCode = client.executeMethod(method);

            if (this.responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(is);
                doc.getDocumentElement().normalize();

                if (!(this.isAsync)) {
                    this.responseBody = doc.getDocumentElement();
                } else {
                    // get async job result
                    Element jobTag = (Element) doc.getDocumentElement().getElementsByTagName("jobid").item(0);
                    String jobId = jobTag.getTextContent();
                    Element responseBodyAsyncEl = queryAsyncJobResult(jobId);
                    if (responseBodyAsyncEl == null) {
                        s_logger.error("Can't get a async result");
                    } else {
                        this.responseBody = responseBodyAsyncEl;
                        // get status of the job
                        Element jobStatusTag = (Element) responseBodyAsyncEl.getElementsByTagName("jobstatus")
                                .item(0);
                        String jobStatus = jobStatusTag.getTextContent();
                        if (!jobStatus.equals("1")) { // Need to modify with different error codes for jobAsync
                            // results
                            // set fake response code by now
                            this.responseCode = 400;
                        }
                    }
                }
            }

            if (TestCaseEngine._printUrl == true) {
                s_logger.info("Response code is " + this.responseCode);
            }
        } catch (Exception ex) {
            s_logger.error("Command " + command + " failed with exception " + ex.getMessage());
        } finally {
            method.releaseConnection();
        }
    }
}

From source file:com.gs.jrpip.client.ThankYouWriter.java

void sendThankYouRequest(CoalesceThankYouNotesKey key) {
    boolean success = false;
    List requestList = this.removeRequestList(key);
    if (done || requestList == null) {
        return;//w  w w  .j a v  a  2 s .c  o  m
    }
    HttpMethod streamedPostMethod = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending thank you for {}", requestList.size());
        }
        AuthenticatedUrl url = key.getAuthenticatedUrl();
        HttpClient httpClient = FastServletProxyFactory.getHttpClient(url);
        httpClient.getState().addCookies(key.getCookies());
        OutputStreamWriter writer = new ThankYouStreamWriter(requestList);
        streamedPostMethod = FastServletProxyFactory.serverSupportsChunking(url)
                ? new StreamedPostMethod(url.getPath() + "?thanks", writer)
                : new BufferedPostMethod(url.getPath() + "?thanks", writer);
        httpClient.executeMethod(streamedPostMethod);

        int code = streamedPostMethod.getStatusCode();

        streamedPostMethod.getResponseBodyAsStream().close();
        streamedPostMethod.releaseConnection();
        streamedPostMethod = null;
        success = code == 200;
    } catch (Exception e) {
        LOGGER.warn("Exception in JRPIP thank you note for URL: {} Retrying.", key.toString(), e);
    } finally {
        if (streamedPostMethod != null) {
            streamedPostMethod.releaseConnection();
        }
    }
    if (!success) {
        this.readList(key, requestList);
    }
}

From source file:com.zimbra.cs.fb.ExchangeFreeBusyProvider.java

public List<FreeBusy> getFreeBusyForHost(String host, ArrayList<Request> req) throws IOException {
    ArrayList<FreeBusy> ret = new ArrayList<FreeBusy>();
    int fb_interval = LC.exchange_free_busy_interval_min.intValueWithinRange(5, 1444);
    Request r = req.get(0);/*ww  w  .  j  a  v a 2 s . c  o  m*/
    ServerInfo serverInfo = (ServerInfo) r.data;
    if (serverInfo == null) {
        ZimbraLog.fb.warn("no exchange server info for user " + r.email);
        return ret;
    }
    if (!serverInfo.enabled) {
        return ret;
    }
    String url = constructGetUrl(serverInfo, req);
    ZimbraLog.fb.debug("fetching fb from url=" + url);
    HttpMethod method = new GetMethod(url);

    Element response = null;
    try {
        int status = sendRequest(method, serverInfo);
        if (status != 200)
            return getEmptyList(req);
        if (ZimbraLog.fb.isDebugEnabled()) {
            Header cl = method.getResponseHeader("Content-Length");
            int contentLength = 10240;
            if (cl != null)
                contentLength = Integer.valueOf(cl.getValue());
            String buf = new String(com.zimbra.common.util.ByteUtil.readInput(method.getResponseBodyAsStream(),
                    contentLength, contentLength), "UTF-8");
            ZimbraLog.fb.debug(buf);
            response = Element.parseXML(buf);
        } else
            response = Element.parseXML(method.getResponseBodyAsStream());
    } catch (XmlParseException e) {
        ZimbraLog.fb.warn("error parsing fb response from exchange", e);
        return getEmptyList(req);
    } catch (IOException e) {
        ZimbraLog.fb.warn("error parsing fb response from exchange", e);
        return getEmptyList(req);
    } finally {
        method.releaseConnection();
    }
    for (Request re : req) {
        String fb = getFbString(response, re.email);
        ret.add(new ExchangeUserFreeBusy(fb, re.email, fb_interval, re.start, re.end));
    }
    return ret;
}

From source file:com.panet.imeta.cluster.SlaveServer.java

public String execService(String service) throws Exception {
    // Prepare HTTP get
    // /*from   w  w w .  ja v  a  2 s  .c  om*/
    HttpClient client = new HttpClient();
    addCredentials(client);
    HttpMethod method = new GetMethod(constructUrl(service));

    // Execute request
    // 
    try {
        int result = client.executeMethod(method);

        // The status code
        log.logDebug(toString(),
                Messages.getString("SlaveServer.DEBUG_ResponseStatus", Integer.toString(result))); //$NON-NLS-1$

        // the response
        InputStream inputStream = new BufferedInputStream(method.getResponseBodyAsStream());

        StringBuffer bodyBuffer = new StringBuffer();
        int c;
        while ((c = inputStream.read()) != -1) {
            bodyBuffer.append((char) c);
        }
        inputStream.close();

        String body = bodyBuffer.toString();

        log.logDetailed(toString(), Messages.getString("SlaveServer.DETAILED_FinishedReading", //$NON-NLS-1$
                Integer.toString(bodyBuffer.length())));
        log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ResponseBody", body)); //$NON-NLS-1$

        return body;
    } finally {
        // Release current connection to the connection pool once you are done
        method.releaseConnection();
        log.logDetailed(toString(),
                Messages.getString("SlaveServer.DETAILED_ExecutedService", service, hostname)); //$NON-NLS-1$
    }

}

From source file:eu.delving.services.controller.SolrProxyController.java

@RequestMapping("/api/solr/select")
public void searchController(HttpServletRequest request, HttpServletResponse response) throws Exception {
    final String solrQueryString = request.getQueryString();
    HttpMethod method = new GetMethod(
            String.format("%s/select?%s", ThemeFilter.getTheme().getSolrSelectUrl(), solrQueryString));
    httpClient.executeMethod(method);/*from w  w  w. jav  a  2 s . c  om*/
    Boolean getAsStream = false;
    for (Header header : method.getResponseHeaders()) {
        if (header.getName().equalsIgnoreCase("content-type")) {
            final String contentType = method.getResponseHeader("Content-Type").getValue();
            response.setContentType(contentType);
            response.setHeader(header.getName(), header.getValue());
            if (contentType.equalsIgnoreCase("application/octet-stream")) {
                getAsStream = true;
            }
        } else if (header.getName().equalsIgnoreCase("server")) {
            //ignore
        } else {
            response.setHeader(header.getName(), header.getValue());
        }
    }
    response.setCharacterEncoding("UTF-8");
    if (getAsStream) {
        OutputStream out = response.getOutputStream();
        try {
            IOUtils.copy(method.getResponseBodyAsStream(), out);
        } finally {
            out.close();
        }
    } else {
        response.getWriter().write(method.getResponseBodyAsString()); //todo add response from SolrProxy here
        response.getWriter().close();
    }
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public int postDocument(InputStream stream) throws IOException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;
    String urlStr = solrHost + "/update?commit=true";
    Log.debug("Ingesting a new document to: " + urlStr);
    method = new PostMethod(urlStr);
    RequestEntity entity = new InputStreamRequestEntity(stream);
    ((PostMethod) method).setRequestEntity(entity);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setRequestHeader("Content-Type", "text/xml");
    method.setRequestHeader("charset", "utf-8");

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsStream());

    Log.debug(solrResponse.getXMLDocumentString());
    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        Log.error(solrResponse.getXMLDocumentString());
    } else/*  w  w w . j  a  v  a2 s  .  c o m*/
        Log.debug(solrResponse.getXMLDocumentString());
    return statusCode;
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*from  w w  w. ja  v a  2  s.  com*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr
                        .lastIndexOf((mCredentials instanceof KeloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:com.owncloud.android.lib.common.OwnCloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*  ww  w.  j a  va2s. c o  m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java

/**
 * Get Volum details from solr meta data instance. Here it adds '\' character before the ':'.
 * @param volId/*from  www .  ja  v  a2 s. c  o  m*/
 * @return VolumeDetailsBean
 * @throws IOException
 */
public VolumeDetailsBean getVolumeDetails(String volId) throws IOException {
    String volumeId;
    if (volId.contains(":")) {
        volumeId = volId.substring(0, volId.indexOf(":")) + "\\" + volId.substring(volId.indexOf(":"));
    } else {
        volumeId = volId;
    }
    String volumeDetailsQueryUrl = PlayConfWrapper.solrMetaQueryUrl() + "id:"
            + URLEncoder.encode(volumeId, "UTF-8")
            + "&fl=title,author,htrc_genderMale,htrc_genderFemale,htrc_genderUnknown,htrc_pageCount,htrc_wordCount";
    VolumeDetailsBean volDetails = new VolumeDetailsBean();

    if (log.isDebugEnabled()) {
        log.debug(volumeDetailsQueryUrl);
    }

    HttpClient httpClient = new HttpClient();
    HttpMethod method = new GetMethod(volumeDetailsQueryUrl);
    method.setFollowRedirects(true);

    try {
        httpClient.executeMethod(method);
        volDetails.setVolumeId(volId);

        if (method.getStatusCode() == 200
                && !method.getResponseBodyAsString().contains("<warn>RESPONSE CODE: 400</warn>")) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

            DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

            Document dom = documentBuilder.parse(method.getResponseBodyAsStream());

            NodeList result = dom.getElementsByTagName("result");
            NodeList arrays = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("arr");
            NodeList integers = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("int");
            NodeList longIntegers = ((org.w3c.dom.Element) result.item(0)).getElementsByTagName("long");

            for (int i = 0; i < arrays.getLength(); i++) {
                org.w3c.dom.Element arr = (org.w3c.dom.Element) arrays.item(i);

                if (arr.hasAttribute("name") && arr.getAttribute("name").equals("title")) {
                    NodeList strElements = arr.getElementsByTagName("str");
                    volDetails.setTitle((strElements.item(0)).getTextContent());
                } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderMale")) {
                    NodeList strElements = arr.getElementsByTagName("str");
                    String maleAuthor = "";

                    for (int j = 0; j < strElements.getLength(); j++) {
                        org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j);
                        if (j != strElements.getLength() - 1) {
                            maleAuthor += str.getTextContent();
                        } else {
                            maleAuthor += str.getTextContent();
                        }
                    }

                    volDetails.setMaleAuthor(maleAuthor);

                } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderFemale")) {
                    NodeList strElements = arr.getElementsByTagName("str");
                    String femaleAuthor = "";

                    for (int j = 0; j < strElements.getLength(); j++) {
                        org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j);
                        if (j != strElements.getLength() - 1) {
                            femaleAuthor += str.getTextContent();
                        } else {
                            femaleAuthor += str.getTextContent();
                        }
                    }

                    volDetails.setFemaleAuthor(femaleAuthor);

                } else if (arr.hasAttribute("name") && arr.getAttribute("name").equals("htrc_genderUnknown")) {
                    NodeList strElements = arr.getElementsByTagName("str");
                    String genderUnknownAuthor = "";

                    for (int j = 0; j < strElements.getLength(); j++) {
                        org.w3c.dom.Element str = (org.w3c.dom.Element) strElements.item(j);
                        if (j != strElements.getLength() - 1) {
                            genderUnknownAuthor += str.getTextContent();
                        } else {
                            genderUnknownAuthor += str.getTextContent();
                        }
                    }

                    volDetails.setGenderUnkownAuthor(genderUnknownAuthor);

                }
            }

            for (int i = 0; i < integers.getLength(); i++) {
                org.w3c.dom.Element integer = (org.w3c.dom.Element) integers.item(i);
                if (integer.hasAttribute("name") && integer.getAttribute("name").equals("htrc_pageCount")) {
                    String pageCount = integer.getTextContent();
                    volDetails.setPageCount(pageCount);
                }
            }
            for (int i = 0; i < longIntegers.getLength(); i++) {
                org.w3c.dom.Element longInteger = (org.w3c.dom.Element) longIntegers.item(0);
                if (longInteger.hasAttribute("name")
                        && longInteger.getAttribute("name").equals("htrc_wordCount")) {
                    String wordCount = longInteger.getTextContent();
                    volDetails.setWordCount(wordCount);
                }
            }

        } else {
            volDetails.setTitle("Cannot retrieve volume details.");
            log.warn("Cannot retrieve details for volume id: " + volId + " Response body: \n"
                    + method.getResponseBodyAsString());
        }

    } catch (SAXParseException e) {
        log.error("Error while parsing volume details for volume: " + volId + " query url: "
                + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e);
        volDetails.setTitle("Cannot parse volume details.");
    } catch (ParserConfigurationException e) {
        log.error("Unrecoverable error while parsing volume details.", e);
        log.error("Error while parsing volume details for volume: " + volId + " query url: "
                + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e);
        throw new RuntimeException("Unrecoverable error while parsing volume details.", e);
    } catch (SAXException e) {
        log.error("Error while parsing volume details for volume: " + volId + " query url: "
                + volumeDetailsQueryUrl + " status code: " + method.getStatusCode(), e);
        volDetails.setTitle("Cannot parse volume details.");
    }

    return volDetails;
}