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

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

Introduction

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

Prototype

int SC_CONFLICT

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

Click Source Link

Document

<tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:com.owncloud.android.lib.test_project.test.CopyFileTest.java

/**
 * Test copy folder// w  ww . jav a2  s . com
 */
public void testCopyRemoteFileOperation() {
    Log.v(LOG_TAG, "testCopyFolder in");

    /// successful cases

    // copy file
    CopyRemoteFileOperation copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_1,
            TARGET_PATH_TO_FILE_1, false);
    RemoteOperationResult result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy & rename file, different location
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_2, TARGET_PATH_TO_FILE_2_RENAMED, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy & rename file, same location (rename file)
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_3, SRC_PATH_TO_FILE_3_RENAMED, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy empty folder
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_EMPTY_FOLDER, TARGET_PATH_TO_EMPTY_FOLDER, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy non-empty folder
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FULL_FOLDER_1, TARGET_PATH_TO_FULL_FOLDER_1, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy & rename folder, different location
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FULL_FOLDER_2, TARGET_PATH_TO_FULL_FOLDER_2_RENAMED,
            false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy & rename folder, same location (rename folder)
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FULL_FOLDER_3, SRC_PATH_TO_FULL_FOLDER_3_RENAMED,
            false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy for nothing (success, but no interaction with network)
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_4, SRC_PATH_TO_FILE_4, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // copy overwriting
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FULL_FOLDER_4,
            TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4, true);
    result = copyOperation.execute(mClient);
    assertTrue(result.isSuccess());

    /// Failed cases

    // file to copy does not exist
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_NON_EXISTENT_FILE, TARGET_PATH_TO_NON_EXISTENT_FILE,
            false);
    result = copyOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.FILE_NOT_FOUND);

    // folder to copy into does no exist
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_5,
            TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.getHttpCode() == HttpStatus.SC_CONFLICT);

    // target location (renaming) has invalid characters
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_6, TARGET_PATH_RENAMED_WITH_INVALID_CHARS,
            false);
    result = copyOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);

    // name collision
    copyOperation = new CopyRemoteFileOperation(SRC_PATH_TO_FILE_1, TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7,
            false);
    result = copyOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);

    // copy a folder into a descendant
    copyOperation = new CopyRemoteFileOperation(SRC_BASE_FOLDER, SRC_PATH_TO_EMPTY_FOLDER, false);
    result = copyOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_COPY_INTO_DESCENDANT);
}

From source file:com.owncloud.android.lib.test_project.test.MoveFileTest.java

/**
 * Test move folder/*from   w ww.  j  a  va2s  .  com*/
 */
public void testMoveRemoteFileOperation() {
    Log.v(LOG_TAG, "testMoveFolder in");

    /// successful cases

    // move file
    MoveRemoteFileOperation moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_1,
            mBaseFolderPath + TARGET_PATH_TO_FILE_1, false);
    RemoteOperationResult result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move & rename file, different location
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_2,
            mBaseFolderPath + TARGET_PATH_TO_FILE_2_RENAMED, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move & rename file, same location (rename file)
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_3,
            mBaseFolderPath + SRC_PATH_TO_FILE_3_RENAMED, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move empty folder
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_EMPTY_FOLDER,
            mBaseFolderPath + TARGET_PATH_TO_EMPTY_FOLDER, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move non-empty folder
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FULL_FOLDER_1,
            mBaseFolderPath + TARGET_PATH_TO_FULL_FOLDER_1, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move & rename folder, different location
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FULL_FOLDER_2,
            mBaseFolderPath + TARGET_PATH_TO_FULL_FOLDER_2_RENAMED, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move & rename folder, same location (rename folder)
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FULL_FOLDER_3,
            mBaseFolderPath + SRC_PATH_TO_FULL_FOLDER_3_RENAMED, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move for nothing (success, but no interaction with network)
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_4,
            mBaseFolderPath + SRC_PATH_TO_FILE_4, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    // move overwriting
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FULL_FOLDER_4,
            mBaseFolderPath + TARGET_PATH_TO_ALREADY_EXISTENT_EMPTY_FOLDER_4, true);
    result = moveOperation.execute(mClient);
    assertTrue(result.isSuccess());

    /// Failed cases

    // file to move does not exist
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_NON_EXISTENT_FILE,
            mBaseFolderPath + TARGET_PATH_TO_NON_EXISTENT_FILE, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.FILE_NOT_FOUND);

    // folder to move into does no exist
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_5,
            mBaseFolderPath + TARGET_PATH_TO_FILE_5_INTO_NON_EXISTENT_FOLDER, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.getHttpCode() == HttpStatus.SC_CONFLICT);

    // target location (renaming) has invalid characters
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_6,
            mBaseFolderPath + TARGET_PATH_RENAMED_WITH_INVALID_CHARS, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME);

    // name collision
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_PATH_TO_FILE_7,
            mBaseFolderPath + TARGET_PATH_TO_ALREADY_EXISTENT_FILE_7, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_OVERWRITE);

    // move a folder into a descendant
    moveOperation = new MoveRemoteFileOperation(mBaseFolderPath + SRC_BASE_FOLDER,
            mBaseFolderPath + SRC_PATH_TO_EMPTY_FOLDER, false);
    result = moveOperation.execute(mClient);
    assertTrue(result.getCode() == ResultCode.INVALID_MOVE_INTO_DESCENDANT);

}

From source file:org.alfresco.integrations.google.docs.webscripts.CreateContent.java

/**
 * Create a new content item for a document, spreadsheet or presentation which is to be edited in Google Docs
 *
 * <p>The name of the file is generated automatically, based on the type of content. In the event of a clash with
 * an existing file, the file name will have a numeric suffix placed on the end of it before the file extension,
 * which will be incremented until a valid name is found.</p>
 *
 * @param parentNodeRef NodeRef identifying the folder where the content will be created
 * @param contentType   The type of content to be created, one of 'document', 'spreadsheet' or 'presentation'
 * @param mimetype  The mimetype of the new content item, used to determine the file extension to add
 * @return  A FileInfo object representing the new content item. Call fileInfo.getNodeRef() to get the nodeRef
 *//*w ww .  j a v a2 s . c om*/
private NodeRef createFile(final NodeRef parentNodeRef, final String contentType, final String mimetype) {
    String baseName = getNewFileName(contentType), fileExt = fileNameUtil.getExtension(mimetype);
    final StringBuffer sb = new StringBuffer(baseName);
    if (fileExt != null && !fileExt.equals("")) {
        sb.append(".").append(fileExt);
    }
    int i = 0, maxCount = 1000; // Limit the damage should something go horribly wrong and a FileExistsException is always thrown

    while (i <= maxCount) {
        List<String> parts = new ArrayList<String>(1);
        parts.add(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, sb.toString()).toPrefixString());
        try {
            if (fileFolderService.resolveNamePath(parentNodeRef, parts, false) == null) {
                return fileFolderService.create(parentNodeRef, sb.toString(), ContentModel.TYPE_CONTENT)
                        .getNodeRef();
            } else {
                log.debug("Filename " + sb.toString() + " already exists");
                String name = fileNameUtil.incrementFileName(sb.toString());
                sb.replace(0, sb.length(), name);
                if (log.isDebugEnabled())
                    log.debug("new file name " + sb.toString());
            }
        } catch (FileNotFoundException e) // We should never catch this because we set mustExist=false
        {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR,
                    "Unexpected FileNotFoundException", e);
        }
        i++;
    }
    throw new WebScriptException(HttpStatus.SC_CONFLICT,
            "Too many untitled files. Try renaming some existing documents.");
}

From source file:org.alfresco.integrations.google.docs.webscripts.DiscardContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/*w  w  w  .j  av  a  2  s .  c o m*/

    Map<String, Object> model = new HashMap<String, Object>();

    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);

    if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
        try {
            boolean deleted = false;

            if (!Boolean.valueOf(map.get(JSON_KEY_OVERRIDE).toString())) {
                SiteInfo siteInfo = siteService.getSite(nodeRef);
                if (siteInfo == null
                        || siteService.isMember(siteInfo.getShortName(), AuthenticationUtil.getRunAsUser())) {

                    if (googledocsService.hasConcurrentEditors(nodeRef)) {
                        throw new WebScriptException(HttpStatus.SC_CONFLICT,
                                "Node: " + nodeRef.toString() + " has concurrent editors.");
                    }
                } else {
                    throw new AccessDeniedException(
                            "Access Denied.  You do not have the appropriate permissions to perform this operation.");
                }
            }

            deleted = delete(nodeRef);

            model.put(MODEL_SUCCESS, deleted);

        } catch (InvalidNodeRefException ine) {
            throw new WebScriptException(HttpStatus.SC_NOT_FOUND, ine.getMessage());
        } catch (IOException ioe) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
        } catch (GoogleDocsAuthenticationException gdae) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
        } catch (GoogleDocsRefreshTokenException gdrte) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
        } catch (GoogleDocsServiceException gdse) {
            if (gdse.getPassedStatusCode() > -1) {
                throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
            } else {
                throw new WebScriptException(gdse.getMessage());
            }
        } catch (AccessDeniedException ade) {
            // This code will make changes after the rollback has occurred to clean up the node: remove the lock and the Google
            // Docs aspect. If it has the temporary aspect it will also remove the node from Alfresco
            AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
                public void afterRollback() {
                    transactionService.getRetryingTransactionHelper()
                            .doInTransaction(new RetryingTransactionCallback<Object>() {
                                public Object execute() throws Throwable {
                                    DriveFile driveFile = googledocsService.getDriveFile(nodeRef);
                                    googledocsService.unlockNode(nodeRef);
                                    boolean deleted = googledocsService.deleteContent(nodeRef, driveFile);

                                    if (deleted) {
                                        AuthenticationUtil
                                                .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                                    public Object doWork() throws Exception {
                                                        if (nodeService.hasAspect(nodeRef,
                                                                ContentModel.ASPECT_TEMPORARY)) {
                                                            nodeService.deleteNode(nodeRef);
                                                        }

                                                        return null;
                                                    }
                                                });
                                    }

                                    return null;
                                }
                            }, false, true);
                }
            });

            throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
        } catch (Exception e) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }
    } else {
        throw new WebScriptException(HttpStatus.SC_NOT_ACCEPTABLE,
                "Missing Google Docs Aspect on " + nodeRef.toString());
    }

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.SaveContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/*from  www . ja  v a  2 s  .  c o  m*/

    Map<String, Object> model = new HashMap<String, Object>();

    boolean success = false;

    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);
    log.debug("Saving Node to Alfresco from Google: " + nodeRef);

    try {
        SiteInfo siteInfo = siteService.getSite(nodeRef);
        if (siteInfo == null
                || siteService.isMember(siteInfo.getShortName(), AuthenticationUtil.getRunAsUser())) {

            if (!(Boolean) map.get(JSON_KEY_OVERRIDE)) {
                log.debug("Check for Concurent Users.");
                if (googledocsService.hasConcurrentEditors(nodeRef)) {
                    throw new WebScriptException(HttpStatus.SC_CONFLICT,
                            "Node: " + nodeRef.toString() + " has concurrent editors.");
                }
            }

            // Should the content be removed from the users Google Drive Account
            boolean removeFromDrive = (map.get(JSON_KEY_REMOVEFROMDRIVE) != null)
                    ? (Boolean) map.get(JSON_KEY_REMOVEFROMDRIVE)
                    : true;

            String contentType = googledocsService.getContentType(nodeRef);
            log.debug("NodeRef: " + nodeRef + "; ContentType: " + contentType);
            if (contentType.equals(GoogleDocsConstants.DOCUMENT_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getDocument(nodeRef);
                    } else {
                        googledocsService.getDocument(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getDocument return boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else if (contentType.equals(GoogleDocsConstants.SPREADSHEET_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getSpreadSheet(nodeRef);
                    } else {
                        googledocsService.getSpreadSheet(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getSpreadsheet return
                                    // boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else if (contentType.equals(GoogleDocsConstants.PRESENTATION_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getPresentation(nodeRef);
                    } else {
                        googledocsService.getPresentation(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getPresentation return
                                    // boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else {
                throw new WebScriptException(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
                        "Content Type: " + contentType + " unknown.");
            }

            // Finish this off with a version create or update
            Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
            if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
                versionProperties.put(Version2Model.PROP_VERSION_TYPE, map.get(JSON_KEY_MAJORVERSION));
                versionProperties.put(Version2Model.PROP_DESCRIPTION, map.get(JSON_KEY_DESCRIPTION));
            } else {
                versionProperties.put(Version2Model.PROP_VERSION_TYPE, VersionType.MAJOR);

                nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION, true);
                nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION_PROPS, true);
            }

            log.debug("Version Node:" + nodeRef + "; Version Properties: " + versionProperties);
            Version version = versionService.createVersion(nodeRef, versionProperties);

            model.put(MODEL_VERSION, version.getVersionLabel());

            if (!removeFromDrive) {
                googledocsService.lockNode(nodeRef);
            }

        } else {
            throw new AccessDeniedException(
                    "Access Denied.  You do not have the appropriate permissions to perform this operation.");
        }

    } catch (GoogleDocsAuthenticationException gdae) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
    } catch (GoogleDocsServiceException gdse) {
        if (gdse.getPassedStatusCode() > -1) {
            throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
        } else {
            throw new WebScriptException(gdse.getMessage());
        }
    } catch (GoogleDocsRefreshTokenException gdrte) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
    } catch (ConstraintException ce) {
        throw new WebScriptException(GoogleDocsConstants.STATUS_INTEGIRTY_VIOLATION, ce.getMessage(), ce);
    } catch (AccessDeniedException ade) {
        // This code will make changes after the rollback has occurred to clean up the node (remove the lock and the Google Docs
        // aspect
        AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
            public void afterRollback() {
                log.debug("Rollback Save to node: " + nodeRef);
                transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Object>() {
                            public Object execute() throws Throwable {
                                return AuthenticationUtil
                                        .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                            public Object doWork() throws Exception {
                                                googledocsService.unlockNode(nodeRef);
                                                googledocsService.unDecorateNode(nodeRef);

                                                // If the node was just created ('Create Content') it will have the temporary aspect and should
                                                // be completely removed.
                                                if (nodeService.hasAspect(nodeRef,
                                                        ContentModel.ASPECT_TEMPORARY)) {
                                                    nodeService.deleteNode(nodeRef);
                                                }

                                                return null;
                                            }
                                        });
                            }
                        }, false, true);
            }
        });

        throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
    } catch (Exception e) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }

    model.put(MODEL_SUCCESS, success);

    return model;
}

From source file:org.alfresco.repo.jive.rest.SocializeDocumentsWebScript.java

/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache)
 *///ww  w .ja  v  a2  s .c o  m
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status, final Cache cache) {
    if (log.isTraceEnabled())
        log.trace("SocializeDocumentsWebScript.executeImpl called");

    Map<String, Object> result = null;
    List<NodeRef> nodeRefs = parseNodeRefs(req);
    long communityId = parseCommunityId(req);

    cache.setNeverCache(true);

    try {
        if (log.isDebugEnabled())
            log.debug("Socializing documents " + Arrays.toString(nodeRefs.toArray()) + " to Jive community "
                    + communityId);
        jiveService.socializeDocuments(nodeRefs, communityId);
    } catch (final FileNotFoundException fnfe) {
        throw new WebScriptException(HttpStatus.SC_NOT_FOUND, fnfe.getMessage(), fnfe);
    } catch (final NotAFileException nafe) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, nafe.getMessage(), nafe);
    } catch (final JiveServiceException jse) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, jse.getMessage(), jse);
    } catch (final ServiceUnavailableException sue) {
        throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue);
    } catch (final DocumentSizeException dse) {
        throw new WebScriptException(HttpStatus.SC_CONFLICT, dse.getMessage(), dse);
    }

    return (result);
}

From source file:org.alfresco.rest.api.tests.TestNodeComments.java

@Test
public void testNodeCommentsAndLocking() throws Exception {
    Comments commentsProxy = publicApiClient.comments();

    // locked node - cannot add/edit/delete comments (MNT-14945, MNT-16446)

    try {/*from w w w  .j  a v  a 2s  .c o m*/
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        Comment comment = new Comment();
        comment.setContent("my comment");
        Comment createdComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);

        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                repoService.lockNode(nodeRef1);
                return null;
            }
        }, person11.getId(), network1.getId());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        // test GET for a locked node

        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems);
        commentsProxy.getNodeComments(nodeRef1.getId(), createParams(paging, null));

        // test POST for a locked node
        try {
            comment = new Comment();
            comment.setContent("my other comment");
            createdComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);

            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_CONFLICT, e.getHttpResponse().getStatusCode());
        }

        // test PUT for a locked node
        try {
            Comment updatedComment = new Comment();
            updatedComment.setContent("my comment");
            commentsProxy.updateNodeComment(nodeRef1.getId(), createdComment.getId(), updatedComment);

            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_CONFLICT, e.getHttpResponse().getStatusCode());
        }

        // test DELETE for a locked node
        try {
            commentsProxy.removeNodeComment(nodeRef1.getId(), createdComment.getId());

            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_CONFLICT, e.getHttpResponse().getStatusCode());
        }
    } finally {
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                repoService.unlockNode(nodeRef1);
                return null;
            }
        }, person11.getId(), network1.getId());
    }
}

From source file:org.alfresco.rest.api.tests.TestSiteMembers.java

@Test
public void testSiteMembers() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    final TestNetwork testNetwork = networksIt.next();
    final List<String> networkPeople = testNetwork.getPersonIds();
    String personId = networkPeople.get(0);

    Sites sitesProxy = publicApiClient.sites();

    {/*from   w ww  .  jav  a  2  s.c o  m*/
        final List<SiteMember> expectedSiteMembers = new ArrayList<SiteMember>();

        // Create a private site and invite some users
        // TODO create site members using public api rather than directly using the services
        TestSite testSite = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite testSite = testNetwork.createSite(SiteVisibility.PRIVATE);
                for (int i = 1; i <= 5; i++) {
                    String inviteeId = networkPeople.get(i);
                    testSite.inviteToSite(inviteeId, SiteRole.SiteConsumer);
                    SiteMember sm = new SiteMember(inviteeId, repoService.getPerson(inviteeId),
                            testSite.getSiteId(), SiteRole.SiteConsumer.toString());
                    expectedSiteMembers.add(sm);
                }

                return testSite;
            }
        }, personId, testNetwork.getId());

        {
            SiteMember sm = new SiteMember(personId, repoService.getPerson(personId), testSite.getSiteId(),
                    SiteRole.SiteManager.toString());
            expectedSiteMembers.add(sm);
            Collections.sort(expectedSiteMembers);
        }

        // Test Case cloud-1482
        {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(testSite.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);
        }

        {
            int skipCount = 2;
            int maxItems = 10;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(testSite.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);

            HttpResponse response = sitesProxy.getAll("sites", testSite.getSiteId(), "members", null,
                    createParams(paging, Collections.singletonMap("includeSource", "true")),
                    "Failed to get all site members");
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(),
                    SiteMember.parseSiteMembers(testSite.getSiteId(), response.getJsonResponse()));
            JSONObject source = sitesProxy.parseListSource(response.getJsonResponse());
            Site sourceSite = SiteImpl.parseSite(source);
            assertNotNull(sourceSite);
            testSite.expected(sourceSite);
        }

        // invalid site id
        try {
            int skipCount = 2;
            int maxItems = 10;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.getSiteMembers(GUID.generate(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // invalid methods
        try {
            SiteMember siteMember = expectedSiteMembers.get(0);

            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.update("sites", testSite.getSiteId(), "members", null, siteMember.toJSON().toString(),
                    "Unable to PUT site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // Test Case cloud-1965
        try {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.create("sites", testSite.getSiteId(), "members", siteMember1.getMemberId(),
                    siteMember1.toJSON().toString(), "Unable to POST to a site member");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.update("sites", testSite.getSiteId(), "members", null, siteMember1.toJSON().toString(),
                    "Unable to PUT site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.remove("sites", testSite.getSiteId(), "members", null, "Unable to DELETE site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // update site member
        {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            SiteMember ret = sitesProxy.updateSiteMember(testSite.getSiteId(), siteMember1);
            assertEquals(siteMember1.getRole(), ret.getRole());
            Person expectedSiteMember = repoService.getPerson(siteMember1.getMemberId());
            expectedSiteMember.expected(ret.getMember());
        }

        // GET single site member
        {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            SiteMember ret = sitesProxy.getSingleSiteMember(testSite.getSiteId(), siteMember1.getMemberId());
            siteMember1.expected(ret);
        }
    }

    // test: user is member of different tenant, but has site membership(s) in common with the http request user
    {
        Iterator<TestNetwork> accountsIt = getTestFixture().getNetworksIt();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network1 = accountsIt.next();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network2 = accountsIt.next();

        final List<TestPerson> people = new ArrayList<TestPerson>();

        // Create users
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);

                return null;
            }
        }, network1.getId());

        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network2.createUser();
                people.add(person);

                return null;
            }
        }, network2.getId());

        final TestPerson person1 = people.get(0);
        final TestPerson person2 = people.get(1);
        final TestPerson person3 = people.get(2);
        final TestPerson person4 = people.get(3);

        // Create site
        final TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite site = network1.createSite(SiteVisibility.PUBLIC);
                return site;
            }
        }, person2.getId(), network1.getId());

        // invalid role - 400
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(), new SiteMember(person1.getId(), "dodgyRole"));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        // user in network but not site member, try to create site member
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person3.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // unknown invitee - 404
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember("dodgyUser", SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // unknown site - 404
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember("dodgySite",
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // inviter is not a member of the site
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // inviter is not a member of the site nor a member of the tenant
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person4.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode()); // TODO check that 404 is correct here - external user of network can't see public site??
        }

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember sm = new SiteMember(person1.getId(), SiteRole.SiteConsumer.toString());
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(), sm);
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteConsumer.toString(), siteMember.getRole());
        }

        // already invited
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_CONFLICT, e.getHttpResponse().getStatusCode());
        }

        // inviter is consumer member of the site, should not be able to add site member
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person4.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // invitee from another network
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person4.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // check site membership in GET
        List<SiteMember> expectedSiteMembers = site.getMembers();

        {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);
        }
    }

    // test: create site membership, remove it, get list of site memberships
    {
        Iterator<TestNetwork> accountsIt = getTestFixture().getNetworksIt();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network1 = accountsIt.next();

        assertTrue(accountsIt.hasNext());

        final List<TestPerson> people = new ArrayList<TestPerson>();

        // Create user
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);

                return null;
            }
        }, network1.getId());

        TestPerson person1 = people.get(0);
        TestPerson person2 = people.get(1);

        // Create site
        TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite site = network1.createSite(SiteVisibility.PRIVATE);
                return site;
            }
        }, person2.getId(), network1.getId());

        // remove site membership

        // for -me- user (PUBLICAPI-90)
        {
            // create a site member
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteContributor.toString(), siteMember.getRole());

            SiteMember toRemove = new SiteMember("-me-");
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.removeSiteMember(site.getSiteId(), toRemove);
        }

        {
            // create a site member
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteContributor.toString(), siteMember.getRole());

            // unknown site
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(GUID.generate(), siteMember);
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // unknown user
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(site.getSiteId(), new SiteMember(GUID.generate()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(site.getSiteId(), siteMember);
            }

            // check site membership in GET
            List<SiteMember> expectedSiteMembers = site.getMembers();
            assertFalse(expectedSiteMembers.contains(siteMember));

            {
                int skipCount = 0;
                int maxItems = Integer.MAX_VALUE;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                        createParams(paging, null));
                checkList(
                        expectedSiteMembers.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), siteMembers);
            }

            // update site membership

            // unknown site
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(GUID.generate(), siteMember);
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // unknown user
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(), new SiteMember(GUID.generate()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // invalid role
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(), new SiteMember(person1.getId(), "invalidRole"));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
            }

            // user is not a member of the site - 400
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(),
                        new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
            }

            // successful update
            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));

                SiteMember sm = new SiteMember(person1.getId(), SiteRole.SiteContributor.toString());
                SiteMember ret = sitesProxy.createSiteMember(site.getSiteId(), sm);
                assertEquals(SiteRole.SiteContributor.toString(), ret.getRole());
                person1.expected(ret.getMember());

                sm = new SiteMember(person1.getId(), SiteRole.SiteCollaborator.toString());
                ret = sitesProxy.updateSiteMember(site.getSiteId(), sm);
                assertEquals(SiteRole.SiteCollaborator.toString(), ret.getRole());
                person1.expected(ret.getMember());

                // check site membership in GET
                expectedSiteMembers = site.getMembers();
                SiteMember toCheck = null;
                for (SiteMember sm1 : expectedSiteMembers) {
                    if (sm1.getMemberId().equals(person1.getId())) {
                        toCheck = sm1;
                    }
                }
                assertNotNull(toCheck); // check that the update site membership is present
                assertEquals(sm.getRole(), toCheck.getRole()); // check that the role is correct

                int skipCount = 0;
                int maxItems = Integer.MAX_VALUE;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                        createParams(paging, null));
                checkList(
                        expectedSiteMembers.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), siteMembers);
            }
        }
    }
}

From source file:org.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to handle the HTTP Response/*  ww w .j a  v  a 2  s  . c  om*/
 *
 * @param msgContext - The MessageContext of the message
 * @param method     - The HTTP method used
 * @throws IOException - Thrown in case an exception occurs
 */
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException {
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    Set<Integer> nonErrorCodes = (Set<Integer>) msgContext
            .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES);
    Set<Integer> errorCodes = new HashSet<Integer>();
    String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing
    // ESBJAVA-3178
    if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) {
        for (String strRetryErrorCode : strRetryErrorCodes.split(",")) {
            try {
                errorCodes.add(Integer.valueOf(strRetryErrorCode));
            } catch (NumberFormatException e) {
                log.warn(strRetryErrorCode + " is not a valid status code");
            }
        }
    }
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
            || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) {
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
        return;
    } else {
        // Since we don't process the response, we must release the connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Puts the file via PUT (leveraging WebDAV). Creates the intermediate folders as well.
 * @param targetURL//w  w w.j  a v a  2  s . c  om
 * @param file
 * @throws MojoExecutionException
 * @see <a href="https://tools.ietf.org/html/rfc4918#section-9.7.1">RFC 4918</a>
 */
protected void putViaWebDav(String targetURL, File file) throws MojoExecutionException {

    boolean success = false;
    int status;

    try {
        status = performPut(targetURL, file);
        if (status >= 200 && status < 300) {
            success = true;
        } else if (status == HttpStatus.SC_CONFLICT) {

            getLog().debug(
                    "Bundle not installed due missing parent folders. Attempting to create parent structure.");
            createIntermediaryPaths(targetURL);

            getLog().debug("Re-attempting bundle install after creating parent folders.");
            status = performPut(targetURL, file);
            if (status >= 200 && status < 300) {
                success = true;
            }
        }

        if (!success) {
            String msg = "Installation failed, cause: " + HttpStatus.getStatusText(status);
            if (failOnError) {
                throw new MojoExecutionException(msg);
            } else {
                getLog().error(msg);
            }
        }
    } catch (Exception ex) {
        throw new MojoExecutionException("Installation on " + targetURL + " failed, cause: " + ex.getMessage(),
                ex);
    }
}