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

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

Introduction

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

Prototype

int SC_MULTI_STATUS

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

Click Source Link

Document

<tt>207 Multi-Status</tt> (WebDAV - RFC 2518) or <tt>207 Partial Update OK</tt> (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?)

Usage

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

@Test
public void testAndroidMeetingSeries() throws Exception {
    Account dav1 = users[1].create();/*  w  w  w .  j ava2s  .  co  m*/
    Account dav2 = users[2].create();
    users[2].getZMailbox(); // Force creation of mailbox - shouldn't be needed
    String calFolderUrl = getFolderUrl(dav1, "Calendar").replaceAll("@", "%40");
    String url = String.format("%s%s.ics", calFolderUrl, androidSeriesMeetingUid);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");

    String body = androidSeriesMeetingTemplate.replace("%%ORG%%", dav1.getName())
            .replace("%%ATT%%", dav2.getName()).replace("%%UID%%", androidSeriesMeetingUid);
    putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED);

    String inboxhref = TestCalDav.waitForNewSchedulingRequestByUID(dav2, androidSeriesMeetingUid);
    assertTrue("Found meeting request for newly created item", inboxhref.contains(androidSeriesMeetingUid));

    GetMethod getMethod = new GetMethod(url);
    addBasicAuthHeaderForUser(getMethod, dav1);
    HttpMethodExecutor exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK);
    String etag = null;
    for (Header hdr : exe.respHeaders) {
        if (DavProtocol.HEADER_ETAG.equals(hdr.getName())) {
            etag = hdr.getValue();
        }
    }
    assertNotNull("ETag from get", etag);

    // Check that we fail if the etag is wrong
    putMethod = new PutMethod(url);
    addBasicAuthHeaderForUser(putMethod, dav1);
    putMethod.addRequestHeader("Content-Type", "text/calendar");
    putMethod.addRequestHeader(DavProtocol.HEADER_IF_MATCH, "willNotMatch");
    putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR));
    HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_PRECONDITION_FAILED);

    PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar"));
    addBasicAuthHeaderForUser(propFindMethod, dav1);
    TestCalDav.HttpMethodExecutor executor;
    String respBody;
    Element respElem;
    propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    propFindMethod.addRequestHeader("Depth", "1");
    propFindMethod.setRequestEntity(
            new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS);
    respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    respElem = Element.XMLElement.parseXML(respBody);
    assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName());
    assertTrue("propfind response should have child elements", respElem.hasChildren());
    Iterator<Element> iter = respElem.elementIterator();
    boolean hasCalendarHref = false;
    boolean hasCalItemHref = false;
    while (iter.hasNext()) {
        Element child = iter.next();
        if (DavElements.P_RESPONSE.equals(child.getName())) {
            Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF);
            while (hrefIter.hasNext()) {
                Element href = hrefIter.next();
                calFolderUrl.endsWith(href.getText());
                hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText());
                hasCalItemHref = hasCalItemHref || url.endsWith(href.getText());
            }
        }
    }
    assertTrue("propfind response contained entry for calendar", hasCalendarHref);
    assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref);

    DeleteMethod deleteMethod = new DeleteMethod(url);
    addBasicAuthHeaderForUser(deleteMethod, dav1);
    HttpMethodExecutor.execute(client, deleteMethod, HttpStatus.SC_NO_CONTENT);
}

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

@Test
public void testMkcol4addressBook() throws Exception {
    String xml = "<D:mkcol xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:carddav\">" + "     <D:set>"
            + "       <D:prop>" + "         <D:resourcetype>" + "           <D:collection/>"
            + "           <C:addressbook/>" + "         </D:resourcetype>"
            + "         <D:displayname>OtherContacts</D:displayname>"
            + "         <C:addressbook-description xml:lang=\"en\">Extra Contacts</C:addressbook-description>"
            + "       </D:prop>" + "     </D:set>" + "</D:mkcol>";
    Account dav1 = users[1].create();// w  w w  . j  ava2 s .com
    StringBuilder url = getLocalServerRoot();
    url.append(DavServlet.DAV_PATH).append("/").append(dav1.getName()).append("/OtherContacts/");
    MkColMethod method = new MkColMethod(url.toString());
    addBasicAuthHeaderForUser(method, dav1);
    HttpClient client = new HttpClient();
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(xml.getBytes(), MimeConstants.CT_TEXT_XML));
    HttpMethodExecutor.execute(client, method, HttpStatus.SC_MULTI_STATUS);

    ZMailbox.Options options = new ZMailbox.Options();
    options.setAccount(dav1.getName());
    options.setAccountBy(AccountBy.name);
    options.setPassword(TestUtil.DEFAULT_PASSWORD);
    options.setUri(TestUtil.getSoapUrl());
    options.setNoSession(true);
    ZMailbox mbox = ZMailbox.getMailbox(options);
    ZFolder folder = mbox.getFolderByPath("/OtherContacts");
    assertEquals("OtherContacts", folder.getName());
    assertEquals("OtherContacts default view", View.contact, folder.getDefaultView());
}

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

public HttpMethodExecutor doPropPatch(Account account, String url, String body) throws IOException {
    HttpClient client = new HttpClient();
    PropPatchMethod propPatchMethod = new PropPatchMethod(url);
    addBasicAuthHeaderForUser(propPatchMethod, account);
    propPatchMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    propPatchMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_XML));
    return HttpMethodExecutor.execute(client, propPatchMethod, HttpStatus.SC_MULTI_STATUS);
}

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

/**
 * @inheritDoc/*  w  w w  .ja  v  a2s.c  o m*/
 */
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties)
        throws IOException {
    Set<PropertyValue> propertyValues = new HashSet<PropertyValue>();
    if (properties != null) {
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
        }
    }
    propertyValues.add(Field.createPropertyValue("folderclass", folderClass));

    // standard MkColMethod does not take properties, override PropPatchMethod instead
    ExchangePropPatchMethod method = new ExchangePropPatchMethod(URIUtil.encodePath(getFolderPath(folderPath)),
            propertyValues) {
        @Override
        public String getName() {
            return "MKCOL";
        }
    };
    int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
    if (status == HttpStatus.SC_MULTI_STATUS) {
        status = method.getResponseStatusCode();
    }
    return status;
}

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

/**
 * @inheritDoc//from   w  ww .j a v  a2s  . c o m
 */
@Override
public int updateFolder(String folderPath, Map<String, String> properties) throws IOException {
    Set<PropertyValue> propertyValues = new HashSet<PropertyValue>();
    if (properties != null) {
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
        }
    }

    // standard MkColMethod does not take properties, override PropPatchMethod instead
    ExchangePropPatchMethod method = new ExchangePropPatchMethod(URIUtil.encodePath(getFolderPath(folderPath)),
            propertyValues);
    int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
    if (status == HttpStatus.SC_MULTI_STATUS) {
        status = method.getResponseStatusCode();
    }
    return status;
}

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

public static Document groupMemberSetExpandProperty(Account acct, Account member, boolean proxyWrite)
        throws IOException, ServiceException {
    String url = proxyWrite ? TestCalDav.getCalendarProxyWriteUrl(acct)
            : TestCalDav.getCalendarProxyReadUrl(acct);
    url = url.replaceAll("@", "%40");
    String href = proxyWrite ? UrlNamespace.getCalendarProxyWriteUrl(acct, acct)
            : UrlNamespace.getCalendarProxyReadUrl(acct, acct);
    href = href.replaceAll("@", "%40");
    ReportMethod method = new ReportMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(TestCalDav.expandPropertyGroupMemberSet.getBytes(),
            MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV());
    XPathExpression xPathExpr;/* w w w  .jav  a 2  s. c o m*/
    try {
        String xpathS = "/D:multistatus/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        String text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for response", href, text);

        xpathS = "/D:multistatus/D:response/D:propstat/D:prop/D:group-member-set/D:response/D:href/text()";
        xPathExpr = xpath.compile(xpathS);
        text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
        assertEquals("HREF for sharee", UrlNamespace.getPrincipalUrl(member).replaceAll("@", "%40"), text);
    } catch (XPathExpressionException e1) {
        ZimbraLog.test.debug("xpath problem", e1);
    }
    return doc;
}

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

public static Document delegateForExpandProperty(Account acct) throws IOException, ServiceException {
    ReportMethod method = new ReportMethod(getPrincipalUrl(acct));
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(/*  w w  w. j  a  v  a 2 s . c o m*/
            new ByteArrayRequestEntity(expandPropertyDelegateFor.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    return doc;
}

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

public static Document setGroupMemberSet(String url, Account acct, Account memberAcct)
        throws IOException, XmlParseException {
    PropPatchMethod method = new PropPatchMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    String body = TestCalDav.propPatchGroupMemberSetTemplate.replace("%%MEMBER%%",
            UrlNamespace.getPrincipalUrl(memberAcct, memberAcct));
    method.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    return doc;// www . j  a v  a2 s  .  c o  m
}

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

/**
 * create a fake event to get VTIMEZONE body
 *//*from   w w w  .ja v a  2 s.  com*/
@Override
protected void loadVtimezone() {
    try {
        // create temporary folder
        String folderPath = getFolderPath("davmailtemp");
        createCalendarFolder(folderPath, null);

        String fakeEventUrl = null;
        if ("Exchange2003".equals(serverVersion)) {
            PostMethod postMethod = new PostMethod(URIUtil.encodePath(folderPath));
            postMethod.addParameter("Cmd", "saveappt");
            postMethod.addParameter("FORMTYPE", "appointment");
            try {
                // create fake event
                int statusCode = httpClient.executeMethod(postMethod);
                if (statusCode == HttpStatus.SC_OK) {
                    fakeEventUrl = StringUtil.getToken(postMethod.getResponseBodyAsString(),
                            "<span id=\"itemHREF\">", "</span>");
                    if (fakeEventUrl != null) {
                        fakeEventUrl = URIUtil.decode(fakeEventUrl);
                    }
                }
            } finally {
                postMethod.releaseConnection();
            }
        }
        // failover for Exchange 2007, use PROPPATCH with forced timezone
        if (fakeEventUrl == null) {
            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("contentclass", "urn:content-classes:appointment"));
            propertyList.add(Field.createDavProperty("outlookmessageclass", "IPM.Appointment"));
            propertyList.add(Field.createDavProperty("instancetype", "0"));

            // get forced timezone id from settings
            String timezoneId = Settings.getProperty("davmail.timezoneId");
            if (timezoneId == null) {
                // get timezoneid from OWA settings
                timezoneId = getTimezoneIdFromExchange();
            }
            // without a timezoneId, use Exchange timezone
            if (timezoneId != null) {
                propertyList.add(Field.createDavProperty("timezoneid", timezoneId));
            }
            String patchMethodUrl = folderPath + '/' + UUID.randomUUID().toString() + ".EML";
            PropPatchMethod patchMethod = new PropPatchMethod(URIUtil.encodePath(patchMethodUrl), propertyList);
            try {
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode == HttpStatus.SC_MULTI_STATUS) {
                    fakeEventUrl = patchMethodUrl;
                }
            } finally {
                patchMethod.releaseConnection();
            }
        }
        if (fakeEventUrl != null) {
            // get fake event body
            GetMethod getMethod = new GetMethod(URIUtil.encodePath(fakeEventUrl));
            getMethod.setRequestHeader("Translate", "f");
            try {
                httpClient.executeMethod(getMethod);
                this.vTimezone = new VObject(
                        "BEGIN:VTIMEZONE" + StringUtil.getToken(getMethod.getResponseBodyAsString(),
                                "BEGIN:VTIMEZONE", "END:VTIMEZONE") + "END:VTIMEZONE\r\n");
            } finally {
                getMethod.releaseConnection();
            }
        }

        // delete temporary folder
        deleteFolder("davmailtemp");
    } catch (IOException e) {
        LOGGER.warn("Unable to get VTIMEZONE info: " + e, e);
    }
}

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

/**
 * Create message in specified folder./*  ww  w .  j a v  a 2  s .  com*/
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}