Example usage for javax.servlet.http HttpServletResponse SC_CONFLICT

List of usage examples for javax.servlet.http HttpServletResponse SC_CONFLICT

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_CONFLICT.

Prototype

int SC_CONFLICT

To view the source code for javax.servlet.http HttpServletResponse SC_CONFLICT.

Click Source Link

Document

Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource.

Usage

From source file:org.osaf.cosmo.mc.MorseCodeServlet.java

/**
 * Handles publish requests./*from  w w w .jav  a 2 s . co  m*/
 */
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled())
        log.debug("handling PUT for " + req.getPathInfo());

    CollectionPath cp = CollectionPath.parse(req.getPathInfo());
    if (cp != null) {
        String parentUid = req.getParameter(PARAM_PARENT_UID);
        if (StringUtils.isEmpty(parentUid))
            parentUid = null;
        EimmlStreamReader reader = null;
        try {
            if (!checkWritePreconditions(req, resp))
                return;

            reader = new EimmlStreamReader(req.getReader());
            if (!reader.getCollectionUuid().equals(cp.getUid())) {

                String msg = "EIMML collection uid " + reader.getCollectionUuid()
                        + " does not match target collection uid " + cp.getUid();
                handleGeneralException(new BadRequestException(msg), resp);
                return;
            }

            EimmlStreamReaderIterator i = new EimmlStreamReaderIterator(reader);
            PubRecords records = new PubRecords(i, reader.getCollectionName(), reader.getCollectionHue());

            Set<TicketType> ticketTypes = null;
            try {
                ticketTypes = parseTicketTypes(req);
            } catch (IllegalArgumentException e) {
                handleGeneralException(new BadRequestException(e), resp);
                return;
            }

            PubCollection pubCollection = controller.publishCollection(cp.getUid(), parentUid, records,
                    ticketTypes);

            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.addHeader(HEADER_SYNC_TOKEN, pubCollection.getToken().serialize());
            for (Ticket ticket : pubCollection.getCollection().getTickets())
                resp.addHeader(HEADER_TICKET, formatTicket(ticket));

            return;
        } catch (CosmoSecurityException e) {
            if (e instanceof ItemSecurityException) {
                InsufficientPrivilegesException ipe = new InsufficientPrivilegesException(
                        (ItemSecurityException) e);
                handleGeneralException(ipe, resp);
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
            }
            return;
        } catch (IllegalArgumentException e) {
            String msg = "Parent uid must be specified when authenticated principal is not a user";
            handleGeneralException(new BadRequestException(msg), resp);
            return;
        } catch (EimmlStreamException e) {
            Throwable cause = e.getCause();
            String msg = "Unable to read EIM stream: " + e.getMessage();
            msg += cause != null ? ": " + cause.getMessage() : "";
            handleGeneralException(new BadRequestException(msg, e), resp);
            return;
        } catch (UidInUseException e) {
            handleGeneralException(new MorseCodeException(HttpServletResponse.SC_CONFLICT, e), resp);
            return;
        } catch (ServerBusyException e) {
            log.debug("received ServerBusyException during PUT");
            resp.setIntHeader(HEADER_RETRY_AFTER, 5);
            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The server was busy, try again later");
            return;
        } catch (MorseCodeException e) {
            Throwable root = e.getCause();
            if (root != null && root instanceof EimmlStreamException) {
                String msg = "Unable to read EIM stream: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            if (root != null && root instanceof EimSchemaException) {
                String msg = "Unable to process EIM records: " + root.getMessage();
                handleGeneralException(new BadRequestException(msg, e), resp);
                return;
            }
            handleGeneralException(e, resp);
            return;
        } catch (RuntimeException e) {
            handleGeneralException(new MorseCodeException(e), resp);
            return;
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:org.tightblog.ui.restapi.UserController.java

private ResponseEntity saveUser(User user, UserData newData, Principal p, HttpServletResponse response,
        boolean add) throws ServletException {
    try {/*  w ww.  j  a va2  s .  c  om*/
        if (user != null) {
            user.setScreenName(newData.user.getScreenName().trim());
            user.setEmailAddress(newData.user.getEmailAddress().trim());

            if (!UserStatus.ENABLED.equals(user.getStatus())
                    && StringUtils.isNotEmpty(newData.user.getActivationCode())) {
                user.setActivationCode(newData.user.getActivationCode());
            }

            if (add) {
                user.setStatus(newData.user.getStatus());
                if (userRepository.count() == 0) {
                    // first person in is always an admin
                    user.setGlobalRole(GlobalRole.ADMIN);
                } else {
                    user.setGlobalRole(webloggerPropertiesRepository.findOrNull().isUsersCreateBlogs()
                            ? GlobalRole.BLOGCREATOR
                            : GlobalRole.BLOGGER);
                }
            } else {
                // users can't alter own roles or status
                if (!user.getUserName().equals(p.getName())) {
                    user.setGlobalRole(newData.user.getGlobalRole());
                    user.setStatus(newData.user.getStatus());
                }
            }

            try {
                userRepository.saveAndFlush(user);
                userRepository.evictUser(user);
                // reset password if set
                if (newData.credentials != null) {
                    if (!StringUtils.isEmpty(newData.credentials.getPasswordText())) {
                        userManager.updateCredentials(user.getId(), newData.credentials.getPasswordText());
                    }
                    // reset MFA secret if requested
                    if (newData.credentials.isEraseMfaSecret()) {
                        userCredentialsRepository.eraseMfaCode(user.getId());
                    }
                }
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (RollbackException e) {
                return ResponseEntity.status(HttpServletResponse.SC_CONFLICT).body("Persistence Problem");
            }
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        UserData data = new UserData();
        data.setUser(user);
        UserCredentials creds = userCredentialsRepository.findByUserName(user.getUserName());
        data.setCredentials(creds);
        return ResponseEntity.ok(data);
    } catch (Exception e) {
        log.error("Error updating user", e);
        throw new ServletException(e);
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.ImageServlet.java

@Override
protected void doPut(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w ww . j a  v a 2 s.  c om
        ServletContext context = getServletContext();
        final FSImage nnImage = NameNodeHttpServer.getFsImageFromContext(context);
        final Configuration conf = (Configuration) getServletContext().getAttribute(JspHelper.CURRENT_CONF);
        final PutImageParams parsedParams = new PutImageParams(request, response, conf);
        final NameNodeMetrics metrics = NameNode.getNameNodeMetrics();

        validateRequest(context, conf, request, response, nnImage, parsedParams.getStorageInfoString());

        UserGroupInformation.getCurrentUser().doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {

                final long txid = parsedParams.getTxId();

                final NameNodeFile nnf = parsedParams.getNameNodeFile();

                if (!nnImage.addToCheckpointing(txid)) {
                    response.sendError(HttpServletResponse.SC_CONFLICT,
                            "Either current namenode is checkpointing or another"
                                    + " checkpointer is already in the process of "
                                    + "uploading a checkpoint made at transaction ID " + txid);
                    return null;
                }
                try {
                    if (nnImage.getStorage().findImageFile(nnf, txid) != null) {
                        response.sendError(HttpServletResponse.SC_CONFLICT,
                                "Either current namenode has checkpointed or "
                                        + "another checkpointer already uploaded an " + "checkpoint for txid "
                                        + txid);
                        return null;
                    }

                    InputStream stream = request.getInputStream();
                    try {
                        long start = monotonicNow();
                        MD5Hash downloadImageDigest = TransferFsImage.handleUploadImageRequest(request, txid,
                                nnImage.getStorage(), stream, parsedParams.getFileSize(), getThrottler(conf));
                        nnImage.saveDigestAndRenameCheckpointImage(nnf, txid, downloadImageDigest);
                        // Metrics non-null only when used inside name node
                        if (metrics != null) {
                            long elapsed = monotonicNow() - start;
                            metrics.addPutImage(elapsed);
                        }
                        // Now that we have a new checkpoint, we might be able to
                        // remove some old ones.
                        nnImage.purgeOldStorage(nnf);
                    } finally {
                        stream.close();
                    }
                } finally {
                    nnImage.removeFromCheckpointing(txid);
                }
                return null;
            }

        });
    } catch (Throwable t) {
        String errMsg = "PutImage failed. " + StringUtils.stringifyException(t);
        response.sendError(HttpServletResponse.SC_GONE, errMsg);
        throw new IOException(errMsg);
    }
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.PUT, value = "/recurrent/{itineraryId}")
public @ResponseBody Boolean updateRecurrentJourney(HttpServletResponse response,
        @RequestBody(required = false) BasicRecurrentJourney recurrent, @PathVariable String itineraryId)
        throws Exception {
    try {/*www . ja  v a 2  s.c o  m*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        String objectClientId = recurrent.getClientId();
        if (!itineraryId.equals(objectClientId)) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            return null;
        }

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("clientId", itineraryId);
        // RecurrentJourneyObject res =
        // domainStorage.searchDomainObjectFixForSpring(pars,
        // RecurrentJourneyObject.class);
        RecurrentJourneyObject res = domainStorage.searchDomainObject(pars, RecurrentJourneyObject.class);

        if (res != null) {
            if (!userId.equals(res.getUserId())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return null;
            }

            res.setData(recurrent.getData());
            res.setName(recurrent.getName());
            res.setMonitor(recurrent.isMonitor());

            domainStorage.saveRecurrent(res);

            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:org.sakaiproject.kernel.rest.friends.RestFriendsProvider.java

/**
 * @param params//w w w.  j a va 2 s. c  om
 * @param request
 * @param response
 * @return
 * @throws RepositoryException
 * @throws JCRNodeFactoryServiceException
 * @throws IOException
 */
private Map<String, Object> doRejectConnect(FriendsParams params, HttpServletRequest request,
        HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException {
    FriendsBean myFriends = friendsResolverService.resolve(params.uuid);
    FriendsBean friendFriends = friendsResolverService.resolve(params.friendUuid);
    if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND,
                " The friend connection is missing ");
    }
    FriendBean myFriendBean = myFriends.getFriend(params.friendUuid);
    FriendBean friendFriendBean = friendFriends.getFriend(params.uuid);
    if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                "The invitation to connect is not current");
    }

    myFriends.removeFriend(params.friendUuid);
    friendFriends.removeFriend(params.uuid);
    authzResolverService.setRequestGrant("Saving Reject Connect");
    try {
        myFriends.save();
        friendFriends.save();
        jcrService.getSession().save();
    } finally {
        authzResolverService.clearRequestGrant();
    }
    return OK;
}

From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoMethodHandler.java

/**
 * @see org.alfresco.module.vti.handler.MethodHandler#putResource(HttpServletRequest, HttpServletResponse)
 *//*from   w w  w  . ja v  a 2  s.  c  o m*/
public void putResource(HttpServletRequest request, HttpServletResponse response) {
    // Office 2008/2011 for Mac specific header
    final String lockTimeOut = request.getHeader(DAV_EXT_LOCK_TIMEOUT);

    if (request.getContentLength() == 0 && lockTimeOut == null) {
        return;
    }

    String decodedUrl = URLDecoder.decode(request.getRequestURI());
    if (decodedUrl.length() > getPathHelper().getAlfrescoContext().length()) {
        decodedUrl = decodedUrl.substring(getPathHelper().getAlfrescoContext().length() + 1);
    }

    FileInfo resourceFileInfo = getPathHelper().resolvePathFileInfo(decodedUrl);
    NodeRef resourceNodeRef = null;

    if (resourceFileInfo != null) {
        resourceNodeRef = resourceFileInfo.getNodeRef();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("The request lock timeout from response is " + lockTimeOut);
        logger.debug("The resource nodeRef is " + resourceNodeRef);
    }

    // Does the file already exist (false), or has it been created by this request? 
    boolean newlyCreated = false;

    // Office 2008/2011 for Mac
    if (resourceNodeRef == null && lockTimeOut != null) {
        try {
            final Pair<String, String> parentChild = VtiPathHelper.splitPathParentChild(decodedUrl);
            final FileInfo parent = getPathHelper().resolvePathFileInfo(parentChild.getFirst());

            RetryingTransactionCallback<NodeRef> cb = new RetryingTransactionCallback<NodeRef>() {
                @Override
                public NodeRef execute() throws Throwable {
                    NodeRef result = getFileFolderService()
                            .create(parent.getNodeRef(), parentChild.getSecond(), ContentModel.TYPE_CONTENT)
                            .getNodeRef();

                    int timeout = Integer.parseInt(lockTimeOut.substring(WebDAV.SECOND.length()));
                    getLockService().lock(result, getUserName(), timeout);

                    return result;
                }
            };

            resourceNodeRef = getTransactionService().getRetryingTransactionHelper().doInTransaction(cb);

            if (resourceNodeRef != null) {
                newlyCreated = true;
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Created new node " + resourceNodeRef);
            }

            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader(WebDAV.HEADER_LOCK_TOKEN, WebDAV.makeLockToken(resourceNodeRef, getUserName()));
            response.setHeader(DAV_EXT_LOCK_TIMEOUT, lockTimeOut);
        } catch (AccessDeniedException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    // Check we managed to find the node one way or another
    if (resourceNodeRef == null) {
        if (logger.isInfoEnabled()) {
            logger.info("No node found for resource " + decodedUrl);
        }

        // TODO Is this the correct status code to return if they've
        //  tried to query for something that doesn't exist?
        // Or should we return something else, or even create it?
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the working copy of it
    final NodeRef workingCopyNodeRef = getCheckOutCheckInService().getWorkingCopy(resourceNodeRef);

    // ALF-15984
    if (!expectedETagForNode(request, resourceNodeRef)) {
        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // updates changes on the server

    final BufferedHttpServletRequest bufferedRequest = new BufferedHttpServletRequest(request, streamFactory);
    final NodeRef finalResourceNodeRef = resourceNodeRef;
    final String finalDecodedUrl = decodedUrl;
    final boolean finalNewlyCreated = newlyCreated;
    final String siteId = davHelper.determineSiteId(getPathHelper().getRootNodeRef(), finalDecodedUrl);
    RetryingTransactionCallback<Void> work = new RetryingTransactionCallback<Void>() {
        @SuppressWarnings("deprecation")
        @Override
        public Void execute() throws Throwable {
            ContentWriter writer;
            boolean newlyCreated = finalNewlyCreated;
            FileFolderService fileFolderService = getFileFolderService();
            if (workingCopyNodeRef != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the workung copy " + workingCopyNodeRef);
                }
                if (fileFolderService.isHidden(workingCopyNodeRef)) {
                    fileFolderService.setHidden(workingCopyNodeRef, false);
                }

                // working copy writer
                writer = getContentService().getWriter(workingCopyNodeRef, ContentModel.PROP_CONTENT, true);
            } else {
                // ALF-17662, hidden node is the same as non-existed node for SPP
                if (fileFolderService.isHidden(finalResourceNodeRef)) {
                    // make it visible for client
                    fileFolderService.setHidden(finalResourceNodeRef, false);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Writing to the node " + finalResourceNodeRef);
                }
                // original document writer
                writer = getContentService().getWriter(finalResourceNodeRef, ContentModel.PROP_CONTENT, true);

            }

            String documentName = getNodeService().getProperty(finalResourceNodeRef, ContentModel.PROP_NAME)
                    .toString();
            String mimetype = getMimetypeService().guessMimetype(documentName);
            writer.setMimetype(mimetype);
            writer.putContent(bufferedRequest.getInputStream());

            // If needed, mark the node as having now had its content supplied
            if (getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT)) {
                // CLOUD-2209: newly created documents not shown in activity feed.
                newlyCreated = true;
                getNodeService().removeAspect(finalResourceNodeRef, ContentModel.ASPECT_WEBDAV_NO_CONTENT);
            }

            // If we actually have content, it's time to add the versionable aspect and save the current version
            ContentData contentData = writer.getContentData();
            if (workingCopyNodeRef == null
                    && !getNodeService().hasAspect(finalResourceNodeRef, ContentModel.ASPECT_VERSIONABLE)
                    && ContentData.hasContent(contentData) && contentData.getSize() > 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Creating a new major version for " + finalResourceNodeRef);
                }
                getVersionService().createVersion(finalResourceNodeRef, Collections
                        .<String, Serializable>singletonMap(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR));
            }

            if (siteId != null) {
                String tenantDomain = davHelper.determineTenantDomain();
                long fileSize = contentData.getSize();
                reportUploadEvent(finalDecodedUrl, siteId, tenantDomain, newlyCreated, mimetype, fileSize);
            }

            return null;
        }
    };

    try {
        getTransactionService().getRetryingTransactionHelper().doInTransaction(work);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("An exception occurred during writing the content.", e);
        }
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        return;
    } finally {
        if (bufferedRequest != null) {
            bufferedRequest.close();
        }
    }

    // original document properties
    Map<QName, Serializable> props = getNodeService().getProperties(resourceNodeRef);

    if (workingCopyNodeRef != null) {
        String workingCopyOwner = getNodeService()
                .getProperty(workingCopyNodeRef, ContentModel.PROP_WORKING_COPY_OWNER).toString();
        if (workingCopyOwner.equals(getAuthenticationService().getCurrentUserName())) {
            // working copy properties
            props = getNodeService().getProperties(workingCopyNodeRef);
        }
    }
    String guid = resourceNodeRef.getId().toUpperCase();
    Date lastModified = (Date) props.get(ContentModel.PROP_MODIFIED);
    response.setHeader("Repl-uid", VtiUtils.constructRid(guid));
    response.setHeader("ResourceTag", VtiUtils.constructResourceTag(guid, lastModified));
    response.setHeader("Last-Modified", VtiUtils.formatBrowserDate(lastModified));
    response.setHeader("ETag", VtiUtils.constructETag(guid, lastModified));

    ContentReader reader = getContentService().getReader(resourceNodeRef, ContentModel.PROP_CONTENT);
    String mimetype = reader == null ? null : reader.getMimetype();

    if (mimetype != null) {
        response.setContentType(mimetype);
    }
}

From source file:com.cloudbees.plugins.credentials.CredentialsStoreAction.java

/**
 * Creates a domain./*from  w  w  w  .  j  a va2s  .c o  m*/
 *
 * @param req the request.
 * @return the response.
 * @throws ServletException if something goes wrong.
 * @throws IOException      if something goes wrong.
 */
@SuppressWarnings("unused") // stapler web method
@Restricted(NoExternalUse.class)
@RequirePOST
public HttpResponse doCreateDomain(StaplerRequest req) throws ServletException, IOException {
    getStore().checkPermission(MANAGE_DOMAINS);
    if (!getStore().isDomainsModifiable()) {
        return HttpResponses.status(HttpServletResponse.SC_BAD_REQUEST);
    }
    String requestContentType = req.getContentType();
    if (requestContentType == null) {
        throw new Failure("No Content-Type header set");
    }

    if (requestContentType.startsWith("application/xml") || requestContentType.startsWith("text/xml")) {
        final StringWriter out = new StringWriter();
        try {
            XMLUtils.safeTransform(new StreamSource(req.getReader()), new StreamResult(out));
            out.close();
        } catch (TransformerException e) {
            throw new IOException("Failed to parse credential", e);
        } catch (SAXException e) {
            throw new IOException("Failed to parse credential", e);
        }

        Domain domain = (Domain) Items.XSTREAM
                .unmarshal(new XppDriver().createReader(new StringReader(out.toString())));
        if (getStore().addDomain(domain)) {
            return HttpResponses.ok();
        } else {
            return HttpResponses.status(HttpServletResponse.SC_CONFLICT);
        }
    } else {
        JSONObject data = req.getSubmittedForm();
        Domain domain = req.bindJSON(Domain.class, data);
        String domainName = domain.getName();
        if (domainName != null && getStore().addDomain(domain)) {
            return HttpResponses.redirectTo("./domain/" + Util.rawEncode(domainName));

        }
        return HttpResponses.redirectToDot();
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java

private boolean handlePut(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws GitAPIException, CoreException, IOException, JSONException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$

        // make sure a clone is addressed
        ProjectInfo webProject = GitUtils.projectFromPath(path);
        if (isAccessAllowed(request.getRemoteUser(), webProject)) {
            Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT);
            if (gitDirs.isEmpty()) {
                String msg = NLS.bind("Request path is not a git repository: {0}", path);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }//from   ww  w  .  ja va  2  s  . co m
            File gitDir = gitDirs.values().iterator().next();

            // make sure required fields are set
            JSONObject toCheckout = OrionServlet.readJSONRequest(request);
            JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
            String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null);
            String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null);
            boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false);
            if ((paths == null || paths.length() == 0) && branch == null && tag == null) {
                String msg = NLS.bind("Either '{0}' or '{1}' or '{2}' should be provided, got: {3}",
                        new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME,
                                GitConstants.KEY_TAG_NAME, toCheckout });
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            Git git = new Git(FileRepositoryBuilder.create(gitDir));
            if (paths != null) {
                Set<String> toRemove = new HashSet<String>();
                CheckoutCommand checkout = git.checkout();
                for (int i = 0; i < paths.length(); i++) {
                    String p = paths.getString(i);
                    if (removeUntracked && !isInIndex(git.getRepository(), p))
                        toRemove.add(p);
                    checkout.addPath(p);
                }
                checkout.call();
                for (String p : toRemove) {
                    File f = new File(git.getRepository().getWorkTree(), p);
                    f.delete();
                }
                return true;
            } else if (tag != null && branch != null) {
                CheckoutCommand co = git.checkout();
                try {
                    co.setName(branch).setStartPoint(tag).setCreateBranch(true).call();
                    return true;
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Tag not found: {0}", tag);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                } catch (GitAPIException e) {
                    if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS
                            .equals(co.getResult().getStatus())) {
                        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                                HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                    }
                    // TODO: handle other exceptions
                }
            } else if (branch != null) {

                if (!isLocalBranch(git, branch)) {
                    String msg = NLS.bind("{0} is not a branch.", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
                }

                CheckoutCommand co = git.checkout();
                try {
                    co.setName(Constants.R_HEADS + branch).call();
                    return true;
                } catch (CheckoutConflictException e) {
                    return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                            HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Branch name not found: {0}", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                } // TODO: handle other exceptions
            }
        } else {
            String msg = NLS.bind("Nothing found for the given ID: {0}", path);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

From source file:org.sakaiproject.kernel.rest.friends.RestFriendsProvider.java

/**
 * @param params/*from   w  w w  .  j a  va2s .  co  m*/
 * @param request
 * @param response
 * @return
 * @throws RepositoryException
 * @throws JCRNodeFactoryServiceException
 * @throws IOException
 */
private Map<String, Object> doIgnoreConnect(FriendsParams params, HttpServletRequest request,
        HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException {
    FriendsBean myFriends = friendsResolverService.resolve(params.uuid);
    FriendsBean friendFriends = friendsResolverService.resolve(params.friendUuid);
    if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND,
                " The friend connection is missing ");
    }
    FriendBean myFriendBean = myFriends.getFriend(params.friendUuid);
    FriendBean friendFriendBean = friendFriends.getFriend(params.uuid);
    if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                "The invitation to connect is not current");
    }

    myFriends.removeFriend(params.friendUuid);
    friendFriends.removeFriend(params.uuid);
    authzResolverService.setRequestGrant("Saving Ignore Connect");
    try {
        myFriends.save();
        friendFriends.save();
        jcrService.getSession().save();
    } finally {
        authzResolverService.clearRequestGrant();
    }
    return OK;
}

From source file:org.apache.archiva.webdav.AbstractRepositoryServletTestCase.java

protected void assertResponseConflictError(WebResponse response) {
    assertNotNull("Should have received a response", response);
    Assert.assertEquals("Should have been a 409/Conflict response code.", HttpServletResponse.SC_CONFLICT,
            response.getStatusCode());/*from  w  w w .j av a 2 s . c  om*/
}