Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.thoughtworks.twist.mingle.core.MingleClientTest.java

public void testInvalidXmlThrowsException() throws Exception {
    MingleClient mingleClient = new TestMingleClient("http://localhost:3000/projects/foo", "ketan", "ketan",
            HttpStatus.SC_OK) {
        protected Reader getResponse(HttpMethod method) {
            return new StringReader("<html>Some response for client</html>\n");
        }/*from  w w  w.j  a v a  2  s  .  co  m*/
    };

    try {
        mingleClient.getAllTaskData();
        fail("Expected CouldNotParseTasksException");
    } catch (CouldNotParseTasksException e) {
        // pass
    }
}

From source file:ccc.migration.FileUploader.java

private ResourceSummary uploadFile(final String hostPath, final UUID parentId, final String fileName,
        final String originalTitle, final String originalDescription, final Date originalLastUpdate,
        final PartSource ps, final String contentType, final String charset, final boolean publish)
        throws IOException {

    final PostMethod filePost = new PostMethod(hostPath);

    try {/*  ww  w .j a v  a  2 s.c  o  m*/
        LOG.debug("Migrating file: " + fileName);
        final String name = ResourceName.escape(fileName).toString();

        final String title = (null != originalTitle) ? originalTitle : fileName;

        final String description = (null != originalDescription) ? originalDescription : "";

        final String lastUpdate;
        if (originalLastUpdate == null) {
            lastUpdate = "" + new Date().getTime();
        } else {
            lastUpdate = "" + originalLastUpdate.getTime();
        }

        final FilePart fp = new FilePart("file", ps);
        fp.setContentType(contentType);
        fp.setCharSet(charset);
        final Part[] parts = { new StringPart("fileName", name), new StringPart("title", title),
                new StringPart("description", description), new StringPart("lastUpdate", lastUpdate),
                new StringPart("path", parentId.toString()), new StringPart("publish", String.valueOf(publish)),
                fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        _client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);

        final int status = _client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            final String entity = filePost.getResponseBodyAsString();
            LOG.debug("Upload complete, response=" + entity);

            return new S11nProvider<ResourceSummary>().readFrom(ResourceSummary.class, ResourceSummary.class,
                    null, MediaType.valueOf(filePost.getResponseHeader("Content-Type").getValue()), null,
                    filePost.getResponseBodyAsStream());
        }

        throw RestExceptionMapper.fromResponse(filePost.getResponseBodyAsString());

    } finally {
        filePost.releaseConnection();
    }
}

From source file:gobblin.metrics.kafka.KafkaAvroSchemaRegistry.java

/**
 * Get the latest schema of a topic.//from w ww.  java  2s .  c  o  m
 *
 * @param topic topic name
 * @return the latest schema
 * @throws SchemaRegistryException if failed to retrieve schema.
 */
@Override
public Schema getLatestSchemaByTopic(String topic) throws SchemaRegistryException {
    String schemaUrl = KafkaAvroSchemaRegistry.this.url + GET_RESOURCE_BY_TYPE + topic;

    LOG.debug("Fetching from URL : " + schemaUrl);

    GetMethod get = new GetMethod(schemaUrl);

    int statusCode;
    String schemaString;
    HttpClient httpClient = this.borrowClient();
    try {
        statusCode = httpClient.executeMethod(get);
        schemaString = get.getResponseBodyAsString();
    } catch (HttpException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        get.releaseConnection();
        this.httpClientPool.returnObject(httpClient);
    }

    if (statusCode != HttpStatus.SC_OK) {
        throw new SchemaRegistryException(String
                .format("Latest schema for topic %s cannot be retrieved. Status code = %d", topic, statusCode));
    }

    Schema schema;
    try {
        schema = new Schema.Parser().parse(schemaString);
    } catch (Throwable t) {
        throw new SchemaRegistryException(
                String.format("Latest schema for topic %s cannot be retrieved", topic), t);
    }

    return schema;
}

From source file:com.testmax.uri.ExecuteHttpRequest.java

public String handleHTTPPostPerformance() throws Exception {
    String resp = null;//w  w w. j  ava  2 s .  co m
    boolean isItemIdReplaced = false;
    String replacedParam = "";
    // Create a method instance.   

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    URLConfig urlConf = this.page.getPageURL().getUrlConfig(this.action);
    List<Element> globalItemList = urlConf.getItemListElement();
    if (globalItemList.size() > 0) {
        urlConf.setItemList();
        isItemIdReplaced = true;
    }
    String newurl = urlConf.replaceGlobalItemIdForUrl(this.url);
    PostMethod method = new PostMethod(newurl);
    System.out.println(newurl);
    Set<String> s = urlConf.getUrlParamset();

    for (String param : s) {
        if (!isItemIdReplaced) {
            //nvps.add(new BasicNameValuePair(param,urlConf.getUrlParamValue(param)));              
            method.addParameter(param, urlConf.getUrlParamValue(param));
        } else {
            replacedParam = urlConf.getUrlReplacedItemIdParamValue(param);
            method.addParameter(param, replacedParam);
            //System.out.println(replacedParam);              
            //nvps.add(new BasicNameValuePair(param,replacedParam));
        }

    }
    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

    this.startRecording();
    int startcount = 0;
    long starttime = this.getCurrentTime();
    int statusCode = 0;
    try {

        // Execute the method.
        statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            WmLog.getCoreLogger()
                    .info("Auth Server response received, but there was a ParserConfigurationException: ");
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        resp = new String(responseBody, "UTF-8");

        // log the response
        WmLog.getCoreLogger().info("MDE Request  : " + resp);

    } catch (HttpException e) {
        WmLog.getCoreLogger().info("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } catch (IOException e) {
        WmLog.getCoreLogger().info("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    // Measure the time passed between response
    long elaspedTime = this.getElaspedTime(starttime);
    this.stopMethodRecording(statusCode, elaspedTime, startcount);

    //System.out.println(resp);
    System.out.println("ElaspedTime: " + elaspedTime);
    WmLog.getCoreLogger().info("Response XML: " + resp);
    WmLog.getCoreLogger().info("ElaspedTime: " + elaspedTime);
    this.printMethodRecording(statusCode, newurl);
    this.printMethodLog(statusCode, newurl);

    if (statusCode == 200 && validateAssert(urlConf, resp)) {
        this.addThreadActionMonitor(this.action, true, elaspedTime);

    } else {
        this.addThreadActionMonitor(this.action, false, elaspedTime);
        WmLog.getCoreLogger().info("Input XML: " + replacedParam);
        WmLog.getCoreLogger().info("Response XML: " + resp);
    }

    return (resp);

}

From source file:com.cognifide.calais.OpenCalaisService.java

@SuppressWarnings("deprecation")
private String doCalaisRequest(String textBody) throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Calais Rest Client");

    PostMethod method = createPostMethod();
    method.setRequestEntity(new StringRequestEntity(textBody));

    try {//from www.j  a v a  2 s . c om
        int returnCode = client.executeMethod(method);
        if (returnCode == HttpStatus.SC_OK) {
            return getResponse(method);
        } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            log("The Post method is not implemented by this URI");
        } else {
            log("Got code: " + returnCode);
            log("response: " + method.getResponseBodyAsString());
        }
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:edu.unc.lib.dl.admin.controller.AccessControlController.java

@RequestMapping(value = "acl/{pid}", method = RequestMethod.GET)
public String getAccessControl(@PathVariable("pid") String pid, Model model, HttpServletResponse response) {
    model.addAttribute("pid", pid);

    // Retrieve ancestor information about the targeted object
    AccessGroupSet accessGroups = GroupsThreadStore.getGroups();
    SimpleIdRequest objectRequest = new SimpleIdRequest(pid, targetResultFields, accessGroups);
    BriefObjectMetadataBean targetObject = queryLayer.getObjectById(objectRequest);
    if (targetObject == null)
        throw new InvalidRecordRequestException();
    model.addAttribute("targetMetadata", targetObject);

    // Get access information for the target's parent
    BriefObjectMetadataBean parentObject = null;
    if (targetObject.getAncestorPathFacet() != null) {
        objectRequest = new SimpleIdRequest(targetObject.getAncestorPathFacet().getSearchKey(),
                parentResultFields, accessGroups);
        parentObject = queryLayer.getObjectById(objectRequest);
        if (parentObject == null)
            throw new InvalidRecordRequestException();
        model.addAttribute("parentMetadata", parentObject);
    }/* w w  w  . j  a  va2s. c  o  m*/

    // Retrieve the targeted objects directly attributed ACL document
    String dataUrl = swordUrl + "em/" + pid + "/ACL";
    HttpClient client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
    client.getParams().setAuthenticationPreemptive(true);
    GetMethod method = new GetMethod(dataUrl);
    // Pass the users groups along with the request
    AccessGroupSet groups = GroupsThreadStore.getGroups();
    method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, groups.joinAccessGroups(";"));

    Element accessControlElement;
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            String accessControlXML = method.getResponseBodyAsString();
            log.debug(accessControlXML);
            SAXBuilder saxBuilder = new SAXBuilder();
            accessControlElement = saxBuilder.build(new StringReader(accessControlXML)).getRootElement();
            model.addAttribute("accessControlXML", accessControlXML);
            model.addAttribute("targetACLs", accessControlElement);
        } else {
            log.error("Failed to retrieve access control document for " + pid + ": "
                    + method.getStatusLine().toString());
            response.setStatus(method.getStatusCode());
            return null;
        }
    } catch (Exception e) {
        response.setStatus(500);
        log.error("Failed to retrieve access control document for " + pid, e);
        return null;
    } finally {
        if (method != null)
            method.releaseConnection();
    }

    Map<String, List<RoleGrant>> rolesGranted = new LinkedHashMap<String, List<RoleGrant>>();
    for (Object elementObject : accessControlElement.getChildren()) {
        Element childElement = (Element) elementObject;
        if (childElement.getNamespace().equals(JDOMNamespaceUtil.CDR_ACL_NS)) {
            String group = childElement.getAttributeValue("group", JDOMNamespaceUtil.CDR_ACL_NS);
            String role = childElement.getAttributeValue("role", JDOMNamespaceUtil.CDR_ACL_NS);

            List<RoleGrant> groupList = rolesGranted.get(role);
            if (groupList == null) {
                groupList = new ArrayList<RoleGrant>();
                rolesGranted.put(role, groupList);
            }
            groupList.add(new RoleGrant(group, false));
        }
    }

    if (parentObject != null) {
        for (String parentRoles : parentObject.getRoleGroup()) {
            String[] roleParts = parentRoles.split("\\|");
            if (roleParts.length < 2)
                continue;
            String role = roleParts[0];

            List<RoleGrant> groupList = rolesGranted.get(role);
            if (groupList == null) {
                groupList = new ArrayList<RoleGrant>();
                rolesGranted.put(role, groupList);
            }
            String group = roleParts[1];
            // If the map already contains this group, then it is marked explicitly as not inherited
            groupList.add(new RoleGrant(group, true));
        }
    }

    model.addAttribute("rolesGranted", rolesGranted);

    model.addAttribute("template", "ajax");
    return "edit/accessControl";
}

From source file:davmail.caldav.TestCaldav.java

public void testGetInbox() throws IOException {
    GetMethod method = new GetMethod("/users/" + session.getEmail() + "/inbox/");
    httpClient.executeMethod(method);/*from   w w  w  .j ava 2 s  .  c  o  m*/
    assertEquals(HttpStatus.SC_OK, method.getStatusCode());
}

From source file:models.Calais.java

private JSONObject doRequest(PostMethod method) throws IOException, ParseException {
    int returnCode = client.executeMethod(method);
    JSONObject result = null;/*from  w  w  w  .  j  a v a2s. com*/
    if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
        System.err.println("The Post method is not implemented by this URI");
        // still consume the response body
        method.getResponseBodyAsString();
    } else if (returnCode == HttpStatus.SC_OK) {
        System.out.println("Post succeeded.");
        result = saveResponse(method);
    } else {
        System.err.println("Post failed.");
        System.err.println("Got code: " + returnCode);
        System.err.println("response: " + method.getResponseBodyAsString());
    }
    method.releaseConnection();
    return result;
}

From source file:CertStreamCallback.java

private static void invokeActions(String url, String params, byte[] data, Part[] parts, String accept,
        String contentType, String sessionID, String language, String method, Callback callback) {

    if (params != null && !"".equals(params)) {
        if (url.contains("?")) {
            url = url + "&" + params;
        } else {//  ww w.  j  a  va2  s .  c  o  m
            url = url + "?" + params;
        }
    }

    if (language != null && !"".equals(language)) {
        if (url.contains("?")) {
            url = url + "&language=" + language;
        } else {
            url = url + "?language=" + language;
        }
    }

    HttpMethod httpMethod = null;

    try {
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        httpMethod = getHttpMethod(url, method);
        if ((httpMethod instanceof PostMethod) || (httpMethod instanceof PutMethod)) {
            if (null != data)
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(new ByteArrayRequestEntity(data));
            if (httpMethod instanceof PostMethod && null != parts)
                ((PostMethod) httpMethod)
                        .setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
        }

        if (sessionID != null) {
            httpMethod.addRequestHeader("Cookie", "JSESSIONID=" + sessionID);
        }

        if (!(httpMethod instanceof PostMethod && null != parts)) {
            if (null != accept && !"".equals(accept))
                httpMethod.addRequestHeader("Accept", accept);
            if (null != contentType && !"".equals(contentType))
                httpMethod.addRequestHeader("Content-Type", contentType);
        }

        int statusCode = httpClient.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            throw ActionException.create(ClientMessages.CON_ERROR1, httpMethod.getStatusLine());
        }

        contentType = null != httpMethod.getResponseHeader("Content-Type")
                ? httpMethod.getResponseHeader("Content-Type").getValue()
                : accept;

        InputStream o = httpMethod.getResponseBodyAsStream();
        if (callback != null) {
            callback.execute(o, contentType, sessionID);
        }

    } catch (Exception e) {
        String result = BizClientUtils.doError(e, contentType);
        ByteArrayInputStream in = null;
        try {
            in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            if (callback != null) {
                callback.execute(in, contentType, null);
            }

        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1.getMessage() + "", e1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    } finally {
        // 
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

/**
 * <pre>//from w  w w  .  j  a  va  2 s.  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;
}