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

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

Introduction

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

Prototype

int SC_PRECONDITION_FAILED

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

Click Source Link

Document

<tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:com.owncloud.android.lib.resources.files.MoveRemoteFileOperation.java

/**
 * Performs the rename operation.//from   w  ww .j a  v  a2  s  .c  o m
 *
 * @param   client      Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {

    /// check parameters
    if (!FileUtils.isValidPath(mTargetRemotePath)) {
        return new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME);
    }

    if (mTargetRemotePath.equals(mSrcRemotePath)) {
        // nothing to do!
        return new RemoteOperationResult(ResultCode.OK);
    }

    if (mTargetRemotePath.startsWith(mSrcRemotePath)) {
        return new RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT);
    }

    /// perform remote operation
    //LocalMoveMethod move = null;
    MoveMethod move = null;
    RemoteOperationResult result = null;
    try {
        move = new MoveMethod(client.getWebdavUri() + WebdavUtils.encodePath(mSrcRemotePath),
                client.getWebdavUri() + WebdavUtils.encodePath(mTargetRemotePath), mOverwrite);
        int status = client.executeMethod(move, MOVE_READ_TIMEOUT, MOVE_CONNECTION_TIMEOUT);

        /// process response
        if (status == HttpStatus.SC_MULTI_STATUS) {
            result = processPartialError(move);

        } else if (status == HttpStatus.SC_PRECONDITION_FAILED && !mOverwrite) {

            result = new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
            client.exhaustResponse(move.getResponseBodyAsStream());

            /// for other errors that could be explicitly handled, check first:
            /// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4

        } else {

            result = new RemoteOperationResult(isSuccess(status), // move.succeeded()? trustful?
                    status, move.getResponseHeaders());
            client.exhaustResponse(move.getResponseBodyAsStream());
        }

        Log.i(TAG, "Move " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage());

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log.e(TAG, "Move " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage(), e);

    } finally {
        if (move != null)
            move.releaseConnection();
    }

    return result;
}

From source file:com.cerema.cloud2.lib.resources.files.CopyRemoteFileOperation.java

/**
 * Performs the rename operation.//from ww w  .ja  v a 2  s  .co  m
 *
 * @param client Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {

    OwnCloudVersion version = client.getOwnCloudVersion();
    boolean versionWithForbiddenChars = (version != null && version.isVersionWithForbiddenCharacters());

    /// check parameters
    if (!FileUtils.isValidPath(mTargetRemotePath, versionWithForbiddenChars)) {
        return new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME);
    }

    if (mTargetRemotePath.equals(mSrcRemotePath)) {
        // nothing to do!
        return new RemoteOperationResult(ResultCode.OK);
    }

    if (mTargetRemotePath.startsWith(mSrcRemotePath)) {
        return new RemoteOperationResult(ResultCode.INVALID_COPY_INTO_DESCENDANT);
    }

    /// perform remote operation
    CopyMethod copyMethod = null;
    RemoteOperationResult result = null;
    try {
        copyMethod = new CopyMethod(client.getWebdavUri() + WebdavUtils.encodePath(mSrcRemotePath),
                client.getWebdavUri() + WebdavUtils.encodePath(mTargetRemotePath), mOverwrite);
        int status = client.executeMethod(copyMethod, COPY_READ_TIMEOUT, COPY_CONNECTION_TIMEOUT);

        /// process response
        if (status == HttpStatus.SC_MULTI_STATUS) {
            result = processPartialError(copyMethod);

        } else if (status == HttpStatus.SC_PRECONDITION_FAILED && !mOverwrite) {

            result = new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
            client.exhaustResponse(copyMethod.getResponseBodyAsStream());

            /// for other errors that could be explicitly handled, check first:
            /// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4

        } else if (status == 400) {
            result = new RemoteOperationResult(copyMethod.succeeded(), copyMethod.getResponseBodyAsString(),
                    status);
        } else {
            result = new RemoteOperationResult(isSuccess(status), // copy.succeeded()? trustful?
                    status, copyMethod.getResponseHeaders());
            client.exhaustResponse(copyMethod.getResponseBodyAsStream());
        }

        Log.i(TAG, "Copy " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage());

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log.e(TAG, "Copy " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage(), e);

    } finally {
        if (copyMethod != null)
            copyMethod.releaseConnection();
    }

    return result;
}

From source file:com.cerema.cloud2.lib.resources.files.MoveRemoteFileOperation.java

/**
 * Performs the rename operation./*from ww  w .  ja va 2 s.c om*/
 * 
 * @param   client      Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {

    OwnCloudVersion version = client.getOwnCloudVersion();
    boolean versionWithForbiddenChars = (version != null && version.isVersionWithForbiddenCharacters());

    /// check parameters
    if (!FileUtils.isValidPath(mTargetRemotePath, versionWithForbiddenChars)) {
        return new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME);
    }

    if (mTargetRemotePath.equals(mSrcRemotePath)) {
        // nothing to do!
        return new RemoteOperationResult(ResultCode.OK);
    }

    if (mTargetRemotePath.startsWith(mSrcRemotePath)) {
        return new RemoteOperationResult(ResultCode.INVALID_MOVE_INTO_DESCENDANT);
    }

    /// perform remote operation
    //LocalMoveMethod move = null;
    MoveMethod move = null;
    RemoteOperationResult result = null;
    try {
        move = new MoveMethod(client.getWebdavUri() + WebdavUtils.encodePath(mSrcRemotePath),
                client.getWebdavUri() + WebdavUtils.encodePath(mTargetRemotePath), mOverwrite);
        int status = client.executeMethod(move, MOVE_READ_TIMEOUT, MOVE_CONNECTION_TIMEOUT);

        /// process response
        if (status == HttpStatus.SC_MULTI_STATUS) {
            result = processPartialError(move);

        } else if (status == HttpStatus.SC_PRECONDITION_FAILED && !mOverwrite) {

            result = new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
            client.exhaustResponse(move.getResponseBodyAsStream());

            /// for other errors that could be explicitly handled, check first:
            /// http://www.webdav.org/specs/rfc4918.html#rfc.section.9.9.4

        } else if (status == 400) {
            result = new RemoteOperationResult(move.succeeded(), move.getResponseBodyAsString(), status);
        } else {
            result = new RemoteOperationResult(isSuccess(status), // move.succeeded()? trustful?
                    status, move.getResponseHeaders());
            client.exhaustResponse(move.getResponseBodyAsStream());
        }

        Log.i(TAG, "Move " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage());

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log.e(TAG, "Move " + mSrcRemotePath + " to " + mTargetRemotePath + ": " + result.getLogMessage(), e);

    } finally {
        if (move != null)
            move.releaseConnection();
    }

    return result;
}

From source file:com.owncloud.android.operations.UploadFileOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    boolean localCopyPassed = false, nameCheckPassed = false;
    File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
    try {//from www .j a  v  a  2  s.  c o m
        // / rename the file to upload, if necessary
        if (!mForceOverwrite) {
            String remotePath = getAvailableRemotePath(client, mRemotePath);
            mWasRenamed = !remotePath.equals(mRemotePath);
            if (mWasRenamed) {
                createNewOCFile(remotePath);
            }
        }
        nameCheckPassed = true;

        String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
                                                                                            // not
                                                                                            // before
                                                                                            // getAvailableRemotePath()
                                                                                            // !!!
        expectedFile = new File(expectedPath);

        // check location of local file; if not the expected, copy to a
        // temporal file before upload (if COPY is the expected behaviour)
        if (!mOriginalStoragePath.equals(expectedPath)
                && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {

            if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
                result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
                return result; // error condition when the file should be
                               // copied

            } else {

                String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
                mFile.setStoragePath(temporalPath);
                temporalFile = new File(temporalPath);

                File temporalParent = temporalFile.getParentFile();
                temporalParent.mkdirs();
                if (!temporalParent.isDirectory()) {
                    throw new IOException("Unexpected error: parent directory could not be created");
                }
                temporalFile.createNewFile();
                if (!temporalFile.isFile()) {
                    throw new IOException("Unexpected error: target file could not be created");
                }

                InputStream in = null;
                OutputStream out = null;

                try {

                    // In case document provider schema as 'content://'
                    if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {

                        Uri uri = Uri.parse(mOriginalStoragePath);

                        in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
                        out = new FileOutputStream(temporalFile);

                        int nRead;
                        byte[] data = new byte[16384];

                        while (!mCancellationRequested.get() && (nRead = in.read(data, 0, data.length)) != -1) {
                            out.write(data, 0, nRead);
                        }
                        out.flush();

                    } else {
                        if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
                            // weird
                            // but
                            // possible
                            // situation

                            in = new FileInputStream(originalFile);
                            out = new FileOutputStream(temporalFile);
                            byte[] buf = new byte[1024];
                            int len;
                            while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        }
                    }

                    if (mCancellationRequested.get()) {
                        result = new RemoteOperationResult(new OperationCancelledException());
                    }

                } catch (Exception e) {
                    result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
                    return result;

                } finally {
                    try {
                        if (in != null)
                            in.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath
                                + " (ignoring)", e);
                    }
                    try {
                        if (out != null)
                            out.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath
                                + " (ignoring)", e);
                    }
                }
            }
        }
        localCopyPassed = (result == null);

        /// perform the upload
        if (mChunked
                && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
            mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
                    mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict());
        } else {
            mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
                    mFile.getMimetype(), mFile.getEtagInConflict());
        }
        Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
        while (listener.hasNext()) {
            mUploadOperation.addDatatransferProgressListener(listener.next());
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }

        result = mUploadOperation.execute(client);

        /// move local temporal file or original file to its corresponding
        // location in the ownCloud local folder
        if (result.isSuccess()) {
            if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
                mFile.setStoragePath(null);

            } else {
                mFile.setStoragePath(expectedPath);
                File fileToMove = null;
                if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
                    // ; see where temporalFile was
                    // set
                    fileToMove = temporalFile;
                } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
                    fileToMove = originalFile;
                }
                if (!expectedFile.equals(fileToMove)) {
                    File expectedFolder = expectedFile.getParentFile();
                    expectedFolder.mkdirs();
                    if (!expectedFolder.isDirectory() || !fileToMove.renameTo(expectedFile)) {
                        mFile.setStoragePath(null); // forget the local file
                        // by now, treat this as a success; the file was
                        // uploaded; the user won't like that the local file
                        // is not linked, but this should be a very rare
                        // fail;
                        // the best option could be show a warning message
                        // (but not a fail)
                        // result = new
                        // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
                        // return result;
                    }
                }
            }

        } else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
        } else {
            if (result.getException() != null) {
                String complement = "";
                if (!nameCheckPassed) {
                    complement = " (while checking file existence in server)";
                } else if (!localCopyPassed) {
                    complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
                            + ")";
                }
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage() + complement, result.getException());
            } else {
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage());
            }
        }
    }

    return result;
}

From source file:com.cerema.cloud2.operations.UploadFileOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    boolean localCopyPassed = false, nameCheckPassed = false;
    File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
    try {//from w ww.j a  v a 2s.  c om
        // / rename the file to upload, if necessary
        if (!mForceOverwrite) {
            String remotePath = getAvailableRemotePath(client, mRemotePath);
            mWasRenamed = !remotePath.equals(mRemotePath);
            if (mWasRenamed) {
                createNewOCFile(remotePath);
            }
        }
        nameCheckPassed = true;

        String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
                                                                                            // not
                                                                                            // before
                                                                                            // getAvailableRemotePath()
                                                                                            // !!!
        expectedFile = new File(expectedPath);

        // check location of local file; if not the expected, copy to a
        // temporal file before upload (if COPY is the expected behaviour)
        if (!mOriginalStoragePath.equals(expectedPath)
                && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {

            if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
                result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
                return result; // error condition when the file should be
                               // copied

            } else {

                String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
                mFile.setStoragePath(temporalPath);
                temporalFile = new File(temporalPath);

                File temporalParent = temporalFile.getParentFile();
                temporalParent.mkdirs();
                if (!temporalParent.isDirectory()) {
                    throw new IOException("Unexpected error: parent directory could not be created");
                }
                temporalFile.createNewFile();
                if (!temporalFile.isFile()) {
                    throw new IOException("Unexpected error: target file could not be created");
                }

                InputStream in = null;
                OutputStream out = null;

                try {

                    // In case document provider schema as 'content://'
                    if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {

                        Uri uri = Uri.parse(mOriginalStoragePath);

                        in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
                        out = new FileOutputStream(temporalFile);

                        int nRead;
                        byte[] data = new byte[16384];

                        while (!mCancellationRequested.get() && (nRead = in.read(data, 0, data.length)) != -1) {
                            out.write(data, 0, nRead);
                        }
                        out.flush();

                    } else {
                        if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
                            // weird
                            // but
                            // possible
                            // situation

                            in = new FileInputStream(originalFile);
                            out = new FileOutputStream(temporalFile);
                            byte[] buf = new byte[1024];
                            int len;
                            while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        }
                    }

                    if (mCancellationRequested.get()) {
                        result = new RemoteOperationResult(new OperationCancelledException());
                    }

                } catch (Exception e) {
                    result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
                    return result;

                } finally {
                    try {
                        if (in != null)
                            in.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath
                                + " (ignoring)", e);
                    }
                    try {
                        if (out != null)
                            out.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath
                                + " (ignoring)", e);
                    }
                }
            }
        }
        localCopyPassed = (result == null);

        /// perform the upload
        if (mChunked
                && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
            mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
                    mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict());
        } else {
            mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
                    mFile.getMimetype(), mFile.getEtagInConflict());
        }
        Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
        while (listener.hasNext()) {
            mUploadOperation.addDatatransferProgressListener(listener.next());
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }

        result = mUploadOperation.execute(client);

        /// move local temporal file or original file to its corresponding
        // location in the ownCloud local folder
        if (result.isSuccess()) {
            if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
                mFile.setStoragePath("");
            } else {
                mFile.setStoragePath(expectedPath);
                File fileToMove = null;
                if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
                    // ; see where temporalFile was
                    // set
                    fileToMove = temporalFile;
                } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
                    fileToMove = originalFile;
                }
                if (!expectedFile.equals(fileToMove)) {
                    File expectedFolder = expectedFile.getParentFile();
                    expectedFolder.mkdirs();

                    if (expectedFolder.isDirectory()) {
                        if (!fileToMove.renameTo(expectedFile)) {
                            // try to copy and then delete
                            expectedFile.createNewFile();
                            FileChannel inChannel = new FileInputStream(fileToMove).getChannel();
                            FileChannel outChannel = new FileOutputStream(expectedFile).getChannel();

                            try {
                                inChannel.transferTo(0, inChannel.size(), outChannel);
                                fileToMove.delete();
                            } catch (Exception e) {
                                mFile.setStoragePath(null); // forget the local file
                                // by now, treat this as a success; the file was
                                // uploaded; the user won't like that the local file
                                // is not linked, but this should be a very rare
                                // fail;
                                // the best option could be show a warning message
                                // (but not a fail)
                                // result = new
                                // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
                                // return result;
                            } finally {
                                if (inChannel != null)
                                    inChannel.close();
                                if (outChannel != null)
                                    outChannel.close();
                            }
                        }

                    } else {
                        mFile.setStoragePath(null);
                    }
                }
            }
            FileDataStorageManager.triggerMediaScan(originalFile.getAbsolutePath());
            FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
        } else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
        } else {
            if (result.getException() != null) {
                String complement = "";
                if (!nameCheckPassed) {
                    complement = " (while checking file existence in server)";
                } else if (!localCopyPassed) {
                    complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
                            + ")";
                }
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage() + complement, result.getException());
            } else {
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage());
            }
        }
    }

    return result;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Build Http Exception from methode status
 *
 * @param method Http Method//ww w.  ja va 2  s .c  o  m
 * @return Http Exception
 */
public static HttpException buildHttpException(HttpMethod method) {
    int status = method.getStatusCode();
    StringBuilder message = new StringBuilder();
    message.append(status).append(' ').append(method.getStatusText());
    try {
        message.append(" at ").append(method.getURI().getURI());
        if (method instanceof CopyMethod || method instanceof MoveMethod) {
            message.append(" to ").append(method.getRequestHeader("Destination"));
        }
    } catch (URIException e) {
        message.append(method.getPath());
    }
    // 440 means forbidden on Exchange
    if (status == 440) {
        return new LoginTimeoutException(message.toString());
    } else if (status == HttpStatus.SC_FORBIDDEN) {
        return new HttpForbiddenException(message.toString());
    } else if (status == HttpStatus.SC_NOT_FOUND) {
        return new HttpNotFoundException(message.toString());
    } else if (status == HttpStatus.SC_PRECONDITION_FAILED) {
        return new HttpPreconditionFailedException(message.toString());
    } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        return new HttpServerErrorException(message.toString());
    } else {
        return new HttpException(message.toString());
    }
}

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

@Test
public void testAndroidMeetingSeries() throws Exception {
    Account dav1 = users[1].create();//w  w  w  .jav a  2  s  . c  o  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:davmail.caldav.CaldavConnection.java

/**
 * Send Http error response for exception
 *
 * @param e exception//from   www .  ja  va2s.c o  m
 * @throws IOException on error
 */
public void sendErr(Exception e) throws IOException {
    String message = e.getMessage();
    if (message == null) {
        message = e.toString();
    }
    if (e instanceof HttpNotFoundException) {
        sendErr(HttpStatus.SC_NOT_FOUND, message);
    } else if (e instanceof HttpPreconditionFailedException) {
        sendErr(HttpStatus.SC_PRECONDITION_FAILED, message);
    } else {
        sendErr(HttpStatus.SC_SERVICE_UNAVAILABLE, message);
    }
}

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

@Test
public void testCreateContactWithIfNoneMatchTesting() throws ServiceException, IOException {
    Account dav1 = users[1].create();//from   w  w  w . ja  v  a  2 s.  c o  m
    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:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc//from  www  . ja  va2s  . co  m
 */
@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();
    }
}