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.eclipse.userstorage.tests.util.USSServer.java

protected void deleteBlob(HttpServletRequest request, HttpServletResponse response, File blobFile,
        File etagFile, boolean exists) throws IOException {
    if (exists) {
        String etag = IOUtil.readUTF(etagFile);
        String ifMatch = getETag(request, "If-Match");
        if (ifMatch != null && !ifMatch.equals(etag)) {
            response.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }/*from  w  w  w.j  a v  a  2  s  .c  om*/
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    IOUtil.delete(blobFile);
    IOUtil.delete(etagFile);

    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}

From source file:edu.stanford.epad.epadws.xnat.XNATCreationOperations.java

public static int createXNATProject(String xnatProjectLabel, String projectName, String description,
        String jsessionID) {/*from   w  ww. j  a  v a 2s  .c om*/
    String xnatProjectURL = XNATUtil.buildXNATProjectCreationURL(xnatProjectLabel, projectName, description);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(xnatProjectURL);
    int xnatStatusCode;

    method.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID);

    try {
        log.info("Invoking XNAT with URL " + xnatProjectURL);
        xnatStatusCode = client.executeMethod(method);
        if (XNATUtil.unexpectedXNATCreationStatusCode(xnatStatusCode))
            log.warning("Failure calling XNAT to create project; status code = " + xnatStatusCode);
        else
            eventTracker.recordProjectEvent(jsessionID, projectName);
    } catch (IOException e) {
        log.warning("IO exception calling XNAT to create project", e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    if (xnatStatusCode == HttpServletResponse.SC_CONFLICT)
        xnatStatusCode = HttpServletResponse.SC_OK;

    return xnatStatusCode;
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java

protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w  w  w .  j a  v a 2 s . c  om
        // prevent multiple configuration changes from stacking up
        if (XACMLPdpServlet.queue.remainingCapacity() <= 0) {
            logger.error("Queue capacity reached");
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "Multiple configuration changes waiting processing.");
            return;
        }
        //
        // Read the properties data into an object.
        //
        Properties newProperties = new Properties();
        newProperties.load(request.getInputStream());
        // should have something in the request
        if (newProperties.size() == 0) {
            logger.error("No properties in PUT");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property");
            return;
        }
        //
        // Which set of properties are they sending us? Whatever they send gets
        // put on the queue (if there is room).
        //
        if (config.equals("policies")) {
            newProperties = XACMLProperties.getPolicyProperties(newProperties, true);
            if (newProperties.size() == 0) {
                logger.error("No policy properties in PUT");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "PUT with cache=policies must contain at least one policy property");
                return;
            }
            XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null));
        } else if (config.equals("pips")) {
            newProperties = XACMLProperties.getPipProperties(newProperties);
            if (newProperties.size() == 0) {
                logger.error("No pips properties in PUT");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "PUT with cache=pips must contain at least one pip property");
                return;
            }
            XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties));
        } else if (config.equals("all")) {
            Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true);
            if (newPolicyProperties.size() == 0) {
                logger.error("No policy properties in PUT");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "PUT with cache=all must contain at least one policy property");
                return;
            }
            Properties newPipProperties = XACMLProperties.getPipProperties(newProperties);
            if (newPipProperties.size() == 0) {
                logger.error("No pips properties in PUT");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "PUT with cache=all must contain at least one pip property");
                return;
            }
            XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties));
        } else {
            //
            // Invalid value
            //
            logger.error("Invalid config value: " + config);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Config must be one of 'policies', 'pips', 'all'");
            return;
        }
    } catch (Exception e) {
        logger.error("Failed to process new configuration.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        return;
    }
}

From source file:org.sakaiproject.citation.servlet.CitationServlet.java

public void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    if (M_log.isDebugEnabled()) {
        M_log.debug("doDelete() " + req.getMethod());
    }//ww  w .ja  va  2  s.com
    // process any login that might be present
    basicAuth.doLogin(req);

    // catch the login helper posts
    String option = req.getPathInfo();
    String[] parts = option.split("/");

    if ((parts.length == 2) && ((parts[1].equals("login")))) {
        doLogin(req, res, null);
    } else if (parts.length < 3) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, rb.getString("savesite.delete.missing_params"));
        return;
    } else {

        String citationId = parts[2];
        String resourceUuid = parts[1];

        if (M_log.isDebugEnabled()) {
            M_log.debug("doDelete() citationId == " + citationId + "  resourceUuid == " + resourceUuid);
        }

        if (resourceUuid == null || resourceUuid.trim().equals("") || citationId == null
                || citationId.trim().equals("")) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, rb.getString("savesite.delete.missing_params"));
            return;
        }

        String resourceId = contentService.resolveUuid(resourceUuid);
        if (resourceId == null) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, rb.getString("savecite.delete.invalid_uuid"));
            return;
        }

        if (!citationService.allowReviseCitationList(resourceId)) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN, "savecite.delete.not_permitted");
            return;
        }

        try {
            ContentResource resource = this.contentService.getResource(resourceId);

            String citationCollectionId = new String(resource.getContent());
            if (citationCollectionId == null || citationCollectionId.trim().equals("")) {
                res.sendError(HttpServletResponse.SC_CONFLICT, rb.getString("savecite.delete.invalid_uuid"));
                return;
            }

            CitationCollection collection = this.citationService.getCollection(citationCollectionId);

            Citation item = collection.getCitation(citationId);

            collection.remove(item);
            this.citationService.save(collection);

            M_log.debug("doDelete() SUCCESS");

        } catch (IdUnusedException e) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, rb.getString("savecite.delete.invalid_uuid"));
        } catch (TypeException e) {
            res.sendError(HttpServletResponse.SC_CONFLICT, rb.getString("savecite.delete.invalid_uuid"));
        } catch (PermissionException e) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN, "savecite.delete.not_permitted");
        } catch (ServerOverloadException e) {
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    rb.getString("savecite.delete.internal"));
        }
    }
}

From source file:com.surevine.alfresco.audit.integration.UploadDocumentTest.java

/**
 * This test deals with the scenario where a file is uploaded using a the non-flash based uploader
 * and the target directory already has a visible file of the same name.  Need to be able to insert
 * HTML containing JSON into the response so that it the updated filename can be extracted.
 */// w  w w .  j  av  a 2s  .  c  o m
@Test
public void testNonFlashNameClashChangedByAlfresco() {

    try {
        // Setup the request object.
        mockRequest.setContentType("multipart/form-data; boundary=" + MIME_BOUNDARY_PARAMETER);
        String mimeContent = formatMimeType(nonFlashBasedUploadData, TEST_FILE, MIME_BOUNDARY);
        mockRequest.setContent(mimeContent.getBytes());
        mockRequest.setRequestURI("/alfresco/s/api/upload");

        mockResponse = new MockHttpServletResponse();

        // Setup the response object.
        JSONObject response = new JSONObject();
        response.put(AlfrescoJSONKeys.NODEREF, TEST_FILENODEREF_STRING);
        response.put("fileName", incrementedTestFilename);
        JSONObject status = new JSONObject();
        status.put("code", HttpServletResponse.SC_OK);
        status.put("name", "OK");
        status.put("description", "File uploaded successfully");
        response.put("status", status);

        mockChain = new ResponseModifiableMockFilterChain(
                htmlUploadSuccessStart + response.toString() + htmlUploadSuccessFinish,
                HttpServletResponse.SC_CONFLICT);

        springAuditFilterBean.doFilter(mockRequest, mockResponse, mockChain);

        Auditable audited = getSingleAuditedEvent();

        assertEquals(incrementedTestFilename, audited.getSource());

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:org.sakaiproject.kernel.rest.RestUserProvider.java

/**
 * @param request/*from  ww  w.  ja v  a 2 s .  com*/
 * @param response
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws UnsupportedEncodingException
 * @throws JCRNodeFactoryServiceException
 * @throws RepositoryException
 */
private Map<String, Object> changePassword(HttpServletRequest request, HttpServletResponse response,
        String externalId) throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException,
        RepositoryException, JCRNodeFactoryServiceException {
    Session session = sessionManagerService.getCurrentSession();
    if (session == null) {
        throw new RestServiceFaultException(HttpServletResponse.SC_UNAUTHORIZED);
    }
    UserEnvironment ue = userEnvironmentResolverService.resolve(session);
    if (ue == null) {
        throw new RestServiceFaultException(HttpServletResponse.SC_UNAUTHORIZED);
    }
    User thisUser = ue.getUser();
    if (thisUser == null || thisUser instanceof AnonUser) {
        throw new RestServiceFaultException(HttpServletResponse.SC_UNAUTHORIZED);
    }

    User user = thisUser;

    boolean superUser = false;
    if (externalId != null) {
        if (ue.isSuperUser()) {
            user = userResolverService.resolve(externalId);
            if (user == null) {
                throw new SecurityException("Specified user cant be found ");
            }
            superUser = true;
        } else {
            throw new SecurityException("User does not have permission to change others passwords");
        }
    } else {
        externalId = ((UserEnvironmentBean) ue).getEid();
    }
    if (thisUser.getUuid().equals(user.getUuid())) {
        superUser = false;
    }
    String password = request.getParameter(PASSWORD_PARAM);

    String passwordOld = request.getParameter(PASSWORD_OLD_PARAM);

    if (password == null || password.trim().length() < 5) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST,
                "Passwords are too short, minimum 5 characters");
    }
    String userEnvironmentPath = userFactoryService.getUserEnvPath(user.getUuid());
    Node userEnvNode = jcrNodeFactoryService.getNode(userEnvironmentPath);
    if (userEnvNode == null) {
        throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, "User does not exist");
    }
    if (!superUser) {
        if (passwordOld == null) {
            throw new RestServiceFaultException(HttpServletResponse.SC_FORBIDDEN,
                    "You must specify the old password in order to change the password.");
        }
        // set the password
        Property storedPassword = userEnvNode.getProperty(JcrAuthenticationResolverProvider.JCRPASSWORDHASH);
        if (storedPassword != null) {
            String storedPasswordString = storedPassword.getString();
            String oldPasswordHash = org.sakaiproject.kernel.util.StringUtils.sha1Hash(passwordOld);
            if (storedPasswordString != null) {
                if (!oldPasswordHash.equals(storedPasswordString)) {
                    throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                            "Old Password does not match ");
                }
            }
        }
    }

    JCRIdPwEvidence oldPrincipal = new JCRIdPwEvidence(externalId, passwordOld);
    JCRIdPwEvidence newPrincipal = new JCRIdPwEvidence(externalId, password);

    // Although the authentication manager service does perform the above tests,
    // providers could be outside the kernel, and so they may not be so strict.
    authenticationManagerService.setAuthentication(oldPrincipal, newPrincipal);

    Map<String, Object> r = new HashMap<String, Object>();
    r.put("response", "OK");
    r.put("uuid", user.getUuid());
    return r;

}

From source file:org.opendaylight.iotdm.onem2m.protocols.http.Onem2mHttpProvider.java

private int mapCoreResponseToHttpResponse(HttpServletResponse httpResponse, String rscString) {

    httpResponse.setHeader(Onem2m.HttpHeaders.X_M2M_RSC, rscString);
    switch (rscString) {
    case Onem2m.ResponseStatusCode.OK:
        return HttpServletResponse.SC_OK;
    case Onem2m.ResponseStatusCode.CREATED:
        return HttpServletResponse.SC_CREATED;
    case Onem2m.ResponseStatusCode.CHANGED:
        return HttpServletResponse.SC_OK;
    case Onem2m.ResponseStatusCode.DELETED:
        return HttpServletResponse.SC_OK;

    case Onem2m.ResponseStatusCode.NOT_FOUND:
        return HttpServletResponse.SC_NOT_FOUND;
    case Onem2m.ResponseStatusCode.OPERATION_NOT_ALLOWED:
        return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    case Onem2m.ResponseStatusCode.CONTENTS_UNACCEPTABLE:
        return HttpServletResponse.SC_BAD_REQUEST;
    case Onem2m.ResponseStatusCode.CONFLICT:
        return HttpServletResponse.SC_CONFLICT;

    case Onem2m.ResponseStatusCode.INTERNAL_SERVER_ERROR:
        return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    case Onem2m.ResponseStatusCode.NOT_IMPLEMENTED:
        return HttpServletResponse.SC_NOT_IMPLEMENTED;
    case Onem2m.ResponseStatusCode.TARGET_NOT_REACHABLE:
        return HttpServletResponse.SC_NOT_FOUND;
    case Onem2m.ResponseStatusCode.ALREADY_EXISTS:
        return HttpServletResponse.SC_FORBIDDEN;
    case Onem2m.ResponseStatusCode.TARGET_NOT_SUBSCRIBABLE:
        return HttpServletResponse.SC_FORBIDDEN;
    case Onem2m.ResponseStatusCode.NON_BLOCKING_REQUEST_NOT_SUPPORTED:
        return HttpServletResponse.SC_NOT_IMPLEMENTED;

    case Onem2m.ResponseStatusCode.INVALID_ARGUMENTS:
        return HttpServletResponse.SC_BAD_REQUEST;
    case Onem2m.ResponseStatusCode.INSUFFICIENT_ARGUMENTS:
        return HttpServletResponse.SC_BAD_REQUEST;
    }/*from   w ww.  j  a v  a  2  s . c  o  m*/
    return HttpServletResponse.SC_BAD_REQUEST;
}

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for analyzing the runs.
 * @param request/*from   www  . j  a  v  a 2s .  co  m*/
 * @param response
 * @return string
 * @throws java.io.IOException
 */
public String analyze(HttpServletRequest request, HttpServletResponse response) throws IOException {

    EditAnalysisModel model = new EditAnalysisModel();
    model.name = request.getParameter("output");
    model.type = request.getParameter("type");
    RunAnalyzer.Type type;
    if ("compare".equals(model.type)) {
        type = RunAnalyzer.Type.COMPARE;
    } else if ("average".equals(model.type)) {
        type = RunAnalyzer.Type.AVERAGE;
    } else {
        String msg = "Invalid analysis: " + model.name;
        response.getWriter().println(msg);
        logger.severe(msg);
        response.sendError(HttpServletResponse.SC_CONFLICT, msg);
        return null;
    }

    model.runIds = request.getParameterValues("select");
    boolean analyze = false;
    boolean redirect = false;
    if (RunAnalyzer.exists(model.name)) {
        String replace = request.getParameter("replace");
        if (replace == null) {
            request.setAttribute("editanalysis.model", model);
            return "/confirm_analysis.jsp";
        } else if ("Replace".equals(replace)) {
            analyze = true;
            redirect = true;
        } else {
            redirect = true;
        }
    } else {
        analyze = true;
        redirect = true;
    }
    if (analyze)
        try {
            RunAnalyzer.clear(model.name);
            UserEnv usrEnv = (UserEnv) request.getSession().getAttribute("usrEnv");
            new RunAnalyzer().analyze(type, model.runIds, model.name, usrEnv.getUser());
        } catch (IOException e) {
            String msg = e.getMessage();
            response.getWriter().println(msg);
            logger.log(Level.SEVERE, msg, e);
            response.sendError(HttpServletResponse.SC_CONFLICT, msg);
            return null;
        }

    if (redirect)
        //response.sendRedirect("/analysis/" + model.name + "/index.html");
        response.sendRedirect("/controller/view/xan_view/analysis/" + model.name + "/" + model.type + ".xan");

    return null;
}

From source file:edu.stanford.epad.epadws.xnat.XNATCreationOperations.java

public static int createXNATSubject(String xnatProjectLabel, String patientID, String patientName,
        String jsessionID) {/*from w  w  w .  j a  v a  2s.c  o  m*/
    String xnatSubjectLabel = XNATUtil.subjectID2XNATSubjectLabel(patientID);
    String xnatSubjectURL = XNATUtil.buildXNATSubjectCreationURL(xnatProjectLabel, xnatSubjectLabel,
            patientName);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(xnatSubjectURL);
    int xnatStatusCode;

    method.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID);

    try {
        log.info("Creating patient " + patientName + " in project " + xnatProjectLabel + " in XNAT");
        xnatStatusCode = client.executeMethod(method);
        if (XNATUtil.unexpectedXNATCreationStatusCode(xnatStatusCode))
            log.warning(
                    "Failure calling XNAT with URL " + xnatSubjectURL + "; status code = " + xnatStatusCode);
        else
            eventTracker.recordPatientEvent(jsessionID, xnatProjectLabel, xnatSubjectLabel);
    } catch (IOException e) {
        log.warning("Error calling XNAT with URL " + xnatSubjectURL, e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    if (xnatStatusCode == HttpServletResponse.SC_CONFLICT)
        xnatStatusCode = HttpServletResponse.SC_OK;

    return xnatStatusCode;
}

From source file:org.georchestra.console.ws.backoffice.roles.RolesController.java

/**
 * Modifies the role using the fields provided in the request body.
 * <p>/*from w w  w.  j a  v  a2  s .c o  m*/
 * The fields that are not present in the parameters will remain untouched
 * in the LDAP store.
 * </p>
 * 
 * <pre>
 * The request format is:
 * [BASE_MAPPING]/roles/{cn}
 *
 * Where <b>cn</b> is the name of role to update.
 * </pre>
 * <p>
 * The request body should contains a the fields to modify using the JSON
 * syntax.
 * </p>
 * <p>
 * Example:
 * </p>
 * 
 * <pre>
 * <b>Request</b>
 * [BASE_MAPPING]/roles/users
 *
 * <b>Body request: </b>
 * role data:
 * {
 *   "cn": "newName"
 *   "description": "new Description"
 *   }
 *
 * </pre>
 *
 * @param request
 *            [BASE_MAPPING]/roles/{cn} body request {"cn": value1,
 *            "description": value2 }
 * @param response
 *
 * @throws IOException
 *             if the uid does not exist or fails to access to the LDAP
 *             store.
 */
@RequestMapping(value = REQUEST_MAPPING + "/{cn:.+}", method = RequestMethod.PUT)
@PreAuthorize("hasRole('SUPERUSER')")
public void update(HttpServletRequest request, HttpServletResponse response, @PathVariable String cn)
        throws IOException {

    // searches the role
    Role role;
    try {
        role = this.roleDao.findByCommonName(cn);
    } catch (NameNotFoundException e) {
        ResponseUtil.writeError(response, NOT_FOUND);
        return;
    } catch (DataServiceException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new IOException(e);
    }

    // modifies the role data
    try {
        final Role modified = modifyRole(role, request.getInputStream());

        this.roleDao.update(cn, modified);

        RoleResponse roleResponse = new RoleResponse(role, this.filter);

        String jsonResponse = roleResponse.asJsonString();

        ResponseUtil.buildResponse(response, jsonResponse, HttpServletResponse.SC_OK);

        ResponseUtil.writeSuccess(response);

    } catch (NameNotFoundException e) {

        ResponseUtil.buildResponse(response, ResponseUtil.buildResponseMessage(Boolean.FALSE, NOT_FOUND),
                HttpServletResponse.SC_NOT_FOUND);

        return;

    } catch (DuplicatedCommonNameException e) {

        String jsonResponse = ResponseUtil.buildResponseMessage(Boolean.FALSE, DUPLICATED_COMMON_NAME);

        ResponseUtil.buildResponse(response, jsonResponse, HttpServletResponse.SC_CONFLICT);

        return;

    } catch (DataServiceException e) {
        LOG.error(e.getMessage());
        ResponseUtil.buildResponse(response, buildErrorResponse(e.getMessage()),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new IOException(e);
    }
}