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

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

<tt>201 Created</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:davmail.caldav.TestCaldav.java

public void testCreateCalendar() throws IOException {
    String folderName = "test & accentu";
    String encodedFolderpath = URIUtil
            .encodePath("/users/" + session.getEmail() + "/calendar/" + folderName + '/');
    // first delete calendar
    session.deleteFolder("calendar/" + folderName);
    String body = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "   <C:mkcalendar xmlns:D=\"DAV:\"\n"
            + "                 xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n" + "     <D:set>\n"
            + "       <D:prop>\n" + "         <D:displayname>" + StringUtil.xmlEncode(folderName)
            + "</D:displayname>\n"
            + "         <C:calendar-description xml:lang=\"en\">Calendar description</C:calendar-description>\n"
            + "         <C:supported-calendar-component-set>\n" + "           <C:comp name=\"VEVENT\"/>\n"
            + "         </C:supported-calendar-component-set>\n" + "       </D:prop>\n" + "     </D:set>\n"
            + "   </C:mkcalendar>";

    SearchReportMethod method = new SearchReportMethod(encodedFolderpath, body) {
        @Override/*  w w  w .j  av  a 2s . c o m*/
        public String getName() {
            return "MKCALENDAR";
        }
    };
    httpClient.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, method.getStatusCode());

    GetMethod getMethod = new GetMethod(encodedFolderpath);
    httpClient.executeMethod(getMethod);
    assertEquals(HttpStatus.SC_OK, getMethod.getStatusCode());
}

From source file:com.hp.alm.ali.idea.services.EntityService.java

private Entity createOldDefectLink(Entity entity, boolean silent) {
    String xml = XMLOutputterFactory.getXMLOutputter()
            .outputString(new Document(DefectLinkList.linkToXml(entity)));
    MyResultInfo result = new MyResultInfo();
    if (restService.post(xml, result, "defects/{0}/defect-links",
            entity.getPropertyValue("first-endpoint-id")) != HttpStatus.SC_CREATED) {
        if (!silent) {
            errorService.showException(new RestException(result));
        }// w ww .  j  ava  2 s.c o m
        return null;
    } else {
        Entity resultEntity = DefectLinkList.create(result.getBodyAsStream()).get(0);
        fireEntityLoaded(resultEntity, EntityListener.Event.CREATE);
        return resultEntity;
    }
}

From source file:com.hp.alm.ali.idea.services.EntityService.java

public Entity createEntity(Entity entity, boolean silent) {
    if ("defect-link".equals(entity.getType()) && restService.getServerStrategy().hasSecondLevelDefectLink()) {
        return createOldDefectLink(entity, silent);
    }/* w ww .  ja  va 2  s  . co  m*/
    String xml = XMLOutputterFactory.getXMLOutputter().outputString(new Document(entity.toElement(null)));
    MyResultInfo result = new MyResultInfo();
    if (restService.post(xml, result, "{0}s", entity.getType()) != HttpStatus.SC_CREATED) {
        if (!silent) {
            errorService.showException(new RestException(result));
        }
        return null;
    } else {
        return parseEntityAndFireEvent(result.getBodyAsStream(), EntityListener.Event.CREATE);
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Updates a TestOutcome on the Cuanto server with the details provided.
 *
 * @param testOutcome The new details that will replace the corresponding values of the existing TestOutcome.
 *//*from  w w  w  .  j a v  a  2  s. co  m*/
public void updateTestOutcome(TestOutcome testOutcome) {
    if (testOutcome.getId() == null) {
        throw new IllegalArgumentException(
                "The specified TestOutcome has no ID value. Any TestOutcome you wish to"
                        + " update should be fetched from the server first.");
    }
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/updateTestOutcome");
    try {
        post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus != HttpStatus.SC_CREATED) {
            throw new RuntimeException("Adding the TestRun failed with HTTP status code " + httpStatus + ": \n"
                    + getResponseBodyAsString(post));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloud.network.brocade.BrocadeVcsApi.java

protected <T> boolean executeCreateObject(T newObject, String uri) throws BrocadeVcsApiException {
    if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null
            || _adminpass.isEmpty()) {// w  w  w .  ja  v a  2 s .c  om
        throw new BrocadeVcsApiException("Hostname/credentials are null or empty");
    }

    boolean result = true;
    HttpPost pm = (HttpPost) createMethod("post", uri);
    pm.setHeader("Accept", "application/vnd.configuration.resource+xml");
    pm.setEntity(new StringEntity(convertToString(newObject), ContentType.APPLICATION_XML));

    HttpResponse response = executeMethod(pm);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {

        String errorMessage;
        try {
            errorMessage = responseToErrorMessage(response);
        } catch (IOException e) {
            s_logger.error("Failed to create object : " + e.getMessage());
            throw new BrocadeVcsApiException("Failed to create object : " + e.getMessage());
        }

        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new BrocadeVcsApiException("Failed to create object : " + errorMessage);
    }

    pm.releaseConnection();

    return result;
}

From source file:com.cloudbees.jenkins.plugins.gogs.server.client.GogsServerAPIClient.java

private String postRequest(PostMethod httppost) throws UnsupportedEncodingException {
    HttpClient client = getHttpClient();
    client.getState().setCredentials(AuthScope.ANY, credentials);
    client.getParams().setAuthenticationPreemptive(true);
    String response = null;//  w  w  w  .j  a va 2s. c  o  m
    InputStream responseBodyAsStream = null;
    try {
        client.executeMethod(httppost);
        if (httppost.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // 204, no content
            return "";
        }
        responseBodyAsStream = httppost.getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            response = IOUtils.toString(responseBodyAsStream, "UTF-8");
        }
        if (httppost.getStatusCode() != HttpStatus.SC_OK && httppost.getStatusCode() != HttpStatus.SC_CREATED) {
            throw new GogsRequestException(httppost.getStatusCode(), "HTTP request error. Status: "
                    + httppost.getStatusCode() + ": " + httppost.getStatusText() + ".\n" + response);
        }
    } catch (HttpException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } catch (IOException e) {
        throw new GogsRequestException(0, "Communication error: " + e, e);
    } finally {
        httppost.releaseConnection();
        if (responseBodyAsStream != null) {
            IOUtils.closeQuietly(responseBodyAsStream);
        }
    }
    if (response == null) {
        throw new GogsRequestException(0, "HTTP request error");
    }
    return response;

}

From source file:davmail.caldav.TestCaldav.java

public void testRenameCalendar() throws IOException {
    String folderName = "testcalendarfolder";
    String encodedFolderpath = URIUtil
            .encodePath("/users/" + session.getEmail() + "/calendar/" + folderName + '/');
    // first delete calendar
    session.deleteFolder("calendar/" + folderName);
    String body = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "   <C:mkcalendar xmlns:D=\"DAV:\"\n"
            + "                 xmlns:C=\"urn:ietf:params:xml:ns:caldav\">\n" + "     <D:set>\n"
            + "       <D:prop>\n" + "         <D:displayname>" + StringUtil.xmlEncode(folderName)
            + "</D:displayname>\n"
            + "         <C:calendar-description xml:lang=\"en\">Calendar description</C:calendar-description>\n"
            + "         <C:supported-calendar-component-set>\n" + "           <C:comp name=\"VEVENT\"/>\n"
            + "         </C:supported-calendar-component-set>\n" + "       </D:prop>\n" + "     </D:set>\n"
            + "   </C:mkcalendar>";

    SearchReportMethod method = new SearchReportMethod(encodedFolderpath, body) {
        @Override/*from   w ww .j av a  2s . c  o  m*/
        public String getName() {
            return "MKCALENDAR";
        }
    };
    httpClient.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, method.getStatusCode());
    MoveMethod moveMethod = new MoveMethod(encodedFolderpath,
            "http://localhost:" + Settings.getProperty("davmail.caldavPort") + "/users/" + session.getEmail()
                    + "/movedcalendarfolder",
            true);
    httpClient.executeMethod(moveMethod);
}

From source file:net.sf.sail.webapp.junit.AbstractSpringHttpUnitTests.java

private Long extractNewlyCreatedId(WebResponse webResponse) {
    assertEquals(HttpStatus.SC_CREATED, webResponse.getResponseCode());
    String locationHeader = webResponse.getHeaderField("Location");
    return new Long(locationHeader.substring(locationHeader.lastIndexOf("/") + 1));
}

From source file:com.hp.alm.ali.idea.services.EntityService.java

private Entity doLock(EntityRef ref, boolean silent) {
    MyResultInfo result = new MyResultInfo();
    int httpStatus = restService.post("", result, "{0}s/{1}/lock", ref.type, ref.id);
    if (httpStatus != HttpStatus.SC_OK && httpStatus != HttpStatus.SC_CREATED) {
        if (!silent) {
            errorService.showException(new RestException(result));
        }//from w w  w .j  av  a  2 s .c  om
        return null;
    }
    return parse(result.getBodyAsStream(), true).get(0);
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

private <T> T executeCreateObject(T newObject, Type returnObjectType, String uri,
        Map<String, String> parameters) throws NiciraNvpApiException {
    String url;/*from   w  ww  .  ja  va  2 s  . com*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    Gson gson = new Gson();

    PostMethod pm = new PostMethod(url);
    pm.setRequestHeader("Content-Type", "application/json");
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null));
    } catch (UnsupportedEncodingException e) {
        throw new NiciraNvpApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
        result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (IOException e) {
        throw new NiciraNvpApiException("Failed to decode json response body", e);
    } finally {
        pm.releaseConnection();
    }

    return result;
}