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:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testSimpleMkcol() throws Exception {
    Account dav1 = users[1].create();//from  w ww  .j  a v a 2  s.co  m
    StringBuilder url = getLocalServerRoot();
    url.append(DavServlet.DAV_PATH).append("/").append(dav1.getName()).append("/simpleMkcol/");
    MkColMethod method = new MkColMethod(url.toString());
    addBasicAuthHeaderForUser(method, dav1);
    HttpClient client = new HttpClient();
    HttpMethodExecutor.execute(client, method, HttpStatus.SC_CREATED);
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testCreateContactWithIfNoneMatchTesting() throws ServiceException, IOException {
    Account dav1 = users[1].create();/*  ww  w  .j av  a2 s  .  c  om*/
    String davBaseName = "SCRUFF1.vcf"; // Based on UID
    String contactsFolderUrl = getFolderUrl(dav1, "Contacts");
    String url = String.format("%s%s", contactsFolderUrl, davBaseName);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/vcard");

    putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
    // Bug 84246 this used to fail with 409 Conflict because we used to require an If-None-Match header
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);

    // Check that trying to put the same thing again when we don't expect it to exist (i.e. Using If-None-Match
    // header) will fail.
    putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/vcard");
    putMethod.addRequestHeader(DavProtocol.HEADER_IF_NONE_MATCH, "*");
    putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_PRECONDITION_FAILED);
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void sendNotification(Notification notification, int instanceId, int learningObjectId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Notification",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportAsXml = serializeNotificationToXML(notification);
    InputStream is = new ByteArrayInputStream(reportAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {/*  ww w . j a  v  a 2s . co  m*/
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testAppleStyleGroup() throws ServiceException, IOException {
    Account dav1 = users[1].create();//from w w  w  .j  ava 2s .c  o  m
    String contactsFolderUrl = getFolderUrl(dav1, "Contacts");
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(contactsFolderUrl);
    addBasicAuthHeaderForUser(postMethod, dav1);
    postMethod.addRequestHeader("Content-Type", "text/vcard");
    postMethod
            .setRequestEntity(new ByteArrayRequestEntity(rachelVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED);

    postMethod = new PostMethod(contactsFolderUrl);
    addBasicAuthHeaderForUser(postMethod, dav1);
    postMethod.addRequestHeader("Content-Type", "text/vcard");
    postMethod.setRequestEntity(
            new ByteArrayRequestEntity(blueGroupCreate.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor exe = HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED);
    String groupLocation = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            groupLocation = hdr.getValue();
        }
    }
    assertNotNull("Location Header returned when creating Group", groupLocation);

    postMethod = new PostMethod(contactsFolderUrl);
    addBasicAuthHeaderForUser(postMethod, dav1);
    postMethod.addRequestHeader("Content-Type", "text/vcard");
    postMethod.setRequestEntity(new ByteArrayRequestEntity(parisVcard.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED);

    String url = String.format("%s%s", contactsFolderUrl, "F53A6F96-566F-46CC-8D48-A5263FAB5E38.vcf");
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/vcard");
    putMethod.setRequestEntity(
            new ByteArrayRequestEntity(blueGroupModify.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_NO_CONTENT);

    GetMethod getMethod = new GetMethod(url);
    addBasicAuthHeaderForUser(getMethod, dav1);
    getMethod.addRequestHeader("Content-Type", "text/vcard");
    exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK);
    String respBody = new String(exe.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    String[] expecteds = { "X-ADDRESSBOOKSERVER-KIND:group",
            "X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:BE43F16D-336E-4C3E-BAE6-22B8F245A986",
            "X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:07139DE2-EA7B-46CB-A970-C4DF7F72D9AE" };
    for (String expected : expecteds) {
        assertTrue(String.format("GET should contain '%s'\nBODY=%s", expected, respBody),
                respBody.contains(expected));
    }

    // members are actually stored in a different way.  Make sure it isn't a fluke
    // that the GET response contained the correct members by checking that the members
    // appear where expected in a search hit.
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.setSortBy("dateDesc");
    searchRequest.setLimit(8);
    searchRequest.setSearchTypes("contact");
    searchRequest.setQuery("in:Contacts");
    ZMailbox mbox = users[1].getZMailbox();
    SearchResponse searchResp = mbox.invokeJaxb(searchRequest);
    assertNotNull("JAXB SearchResponse object", searchResp);
    List<SearchHit> hits = searchResp.getSearchHits();
    assertNotNull("JAXB SearchResponse hits", hits);
    assertEquals("JAXB SearchResponse hits", 3, hits.size());
    boolean seenGroup = false;
    for (SearchHit hit : hits) {
        ContactInfo contactInfo = (ContactInfo) hit;
        if ("BlueGroup".equals(contactInfo.getFileAs())) {
            seenGroup = true;
            assertEquals("Number of members of group in search hit", 2,
                    contactInfo.getContactGroupMembers().size());
        }
        ZimbraLog.test.info("Hit %s class=%s", hit, hit.getClass().getName());
    }
    assertTrue("Seen group", seenGroup);
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void sendNotificationToUsers(Notification notification, int learningObjectId, int instanceId,
        int[] receiverUserIds, int senderUserId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/NotificationToUsers",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportAsXml = serializeNotificationToWrappedXML(notification);
    String userIdsAsXml = serializeUserIdsToWrappedXML(receiverUserIds);
    String senderUserIdAsXml = "<senderUserId>" + Integer.toString(senderUserId) + "</senderUserId>";
    String openingTag = "<SendNotificationToUsers xmlns=\"http://tempuri.org/\">";
    String closingTag = "</SendNotificationToUsers>";

    StringBuilder xmlBuilder = new StringBuilder();
    xmlBuilder.append(openingTag);//from w w  w .j a v a2 s  . c  om
    xmlBuilder.append(reportAsXml);
    xmlBuilder.append(userIdsAsXml);
    xmlBuilder.append(senderUserIdAsXml);
    xmlBuilder.append(closingTag);

    method.setRequestEntity(new StringRequestEntity(xmlBuilder.toString(), "text/xml", "UTF-8"));

    try {
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void setUpdated(int instanceId, int learningObjectId) throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Updated",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);

    try {//  w w w.j  a  va2  s  . c  o m
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testXBusyMacAttach() throws ServiceException, IOException {
    Account dav1 = users[1].create();/*from  w ww  .  java  2s  . c  om*/
    String contactsFolderUrl = getFolderUrl(dav1, "Contacts");
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(contactsFolderUrl);
    addBasicAuthHeaderForUser(postMethod, dav1);
    postMethod.addRequestHeader("Content-Type", "text/vcard");
    postMethod.setRequestEntity(
            new ByteArrayRequestEntity(smallBusyMacAttach.getBytes(), MimeConstants.CT_TEXT_VCARD));
    HttpMethodExecutor exe = HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED);
    String location = null;
    for (Header hdr : exe.respHeaders) {
        if ("Location".equals(hdr.getName())) {
            location = hdr.getValue();
        }
    }
    assertNotNull("Location Header returned when creating", location);
    String url = String.format("%s%s", contactsFolderUrl, location.substring(location.lastIndexOf('/') + 1));
    GetMethod getMethod = new GetMethod(url);
    addBasicAuthHeaderForUser(getMethod, dav1);
    getMethod.addRequestHeader("Content-Type", "text/vcard");
    exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK);
    String respBody = new String(exe.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    String[] expecteds = { "\r\nX-BUSYMAC-ATTACH;X-FILENAME=favicon.ico;ENCODING=B:AAABAAEAEBAAAAEAIABoBA\r\n",
            "\r\n AAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAABMLAAATCwAAAAAAAAAAAAAAAAAAw4cAY8\r\n",
            "\r\nX-BUSYMAC-MODIFIED-BY:Gren Elliot\r\n",
            "\r\nX-CUSTOM:one two three four five six seven eight nine ten eleven twelve t\r\n hirteen fourteen fifteen",
            "\r\nX-CUSTOM:Here are my simple\\Nmultiline\\Nnotes\r\n",
            "\r\nX-CUSTOM;TYPE=pref:semi-colon\\;seperated\\;\"stuff\"\\;here\r\n",
            "\r\nX-CUSTOM:comma\\,\"stuff\"\\,'there'\\,too\r\n", "\r\nX-HOBBY:my backslash\\\\ hobbies\r\n",
            "\r\nX-CREATED:2015-04-05T09:50:44Z\r\n" };
    for (String expected : expecteds) {
        assertTrue(String.format("GET should contain '%s'\nBODY=%s", expected, respBody),
                respBody.contains(expected));
    }

    SearchRequest searchRequest = new SearchRequest();
    searchRequest.setSortBy("dateDesc");
    searchRequest.setLimit(8);
    searchRequest.setSearchTypes("contact");
    searchRequest.setQuery("in:Contacts");
    ZMailbox mbox = users[1].getZMailbox();
    SearchResponse searchResp = mbox.invokeJaxb(searchRequest);
    assertNotNull("JAXB SearchResponse object", searchResp);
    List<SearchHit> hits = searchResp.getSearchHits();
    assertNotNull("JAXB SearchResponse hits", hits);
    assertEquals("JAXB SearchResponse hits", 1, hits.size());
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc//from   w ww .  ja v a 2  s . c om
 */
@Override
public void moveFolder(String folderPath, String targetPath) throws IOException {
    MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(folderPath)),
            URIUtil.encodePath(getFolderPath(targetPath)), false);
    try {
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new HttpPreconditionFailedException(BundleMessage.format("EXCEPTION_UNABLE_TO_MOVE_FOLDER"));
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        } else if (folderPath.equalsIgnoreCase("/users/" + getEmail() + "/calendar")) {
            // calendar renamed, need to reload well known folders 
            getWellKnownFolders();
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReports(List<LearningObjectInstanceUserReport> userReports,
        int instanceId, int learningObjectId) throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports",
            learningObjectId, instanceId);
    PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST);
    String reportsAsXml = serializeLearningObjectInstanceUserReportsToXML(userReports);
    InputStream is = new ByteArrayInputStream(reportsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {//from  w  w  w  .  j a  va2  s. c  om
        int statusCode = _httpClient.executeMethod(method);
        // POST methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

protected void moveItem(MoveMethod method) throws IOException {
    try {//from w w w .  j av a  2 s  . c  o m
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_ITEM");
        } else if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}