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.sakaiproject.kernel.rest.RestUserProvider.java

/**
 * @param request/*from  ww w  .  java  2  s .  c  o m*/
 * @return
 * @throws JCRNodeFactoryServiceException
 * @throws RepositoryException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
private Map<String, Object> createUser(HttpServletRequest request, HttpServletResponse response)
        throws RepositoryException, JCRNodeFactoryServiceException, IOException, NoSuchAlgorithmException {
    String firstName = request.getParameter(FIRST_NAME_PARAM);
    String lastName = request.getParameter(LAST_NAME_PARAM);
    String email = request.getParameter(EMAIL_PARAM);
    String externalId = request.getParameter(EXTERNAL_USERID_PARAM);
    String password = request.getParameter(PASSWORD_PARAM);
    String userType = request.getParameter(USER_TYPE_PARAM);

    if (StringUtils.isEmpty(firstName)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, FIRST_NAME_PARAM + " is empty");
    }
    if (StringUtils.isEmpty(lastName)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, LAST_NAME_PARAM + " is empty");
    }
    if (StringUtils.isEmpty(email)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, EMAIL_PARAM + " is empty");
    }
    if (StringUtils.isEmpty(externalId)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST,
                EXTERNAL_USERID_PARAM + " is empty");
    }
    if (StringUtils.isEmpty(password)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, PASSWORD_PARAM + " is empty");
    }
    if (StringUtils.isEmpty(userType)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, USER_TYPE_PARAM + " is empty");
    }

    if (anonymousAccounting) {
        authzResolverService.setRequestGrant("Creating User For Anon User");
    } else {
        String loggedInUser = request.getRemoteUser();
        if (loggedInUser == null || "anon".equals(loggedInUser)) {
            throw new RestServiceFaultException(HttpServletResponse.SC_FORBIDDEN,
                    "User Creation is not allowed");
        } else {
            UserEnvironment ue = userEnvironmentResolverService.resolve(loggedInUser);
            if (ue.isSuperUser()) {
                authzResolverService.setRequestGrant("Creating User For Super User");
            } else {
                throw new RestServiceFaultException(HttpServletResponse.SC_FORBIDDEN,
                        "User Creation is only allowed by Super Users");
            }
        }
    }

    User u = userResolverService.resolve(externalId);
    if (u != null) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                "Conflict, unable to create new user. Perhaps user already exists?");
    }

    u = userFactoryService.createNewUser(externalId);

    UserEnvironment ue = userEnvironmentResolverService.create(u, externalId, password, userType);
    if (ue == null) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "Unable to create new user");
    }

    UserProfile userProfile = profileResolverService.create(u.getUuid(), userType);
    Map<String, Object> profileMap = userProfile.getProperties();

    profileMap.put("firstName", firstName);
    profileMap.put("lastName", lastName);
    profileMap.put("email", email);

    userProfile.setProperties(profileMap);
    userProfile.save();

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

}

From source file:eu.dasish.annotation.backend.rest.PrincipalResource.java

/**
 * //  w w  w.  j  a v a 2  s  .co  m
 * @param name the name of the principal to be registered.
 * @param remoteId the remote shibboleth id.
 * @param email the email.
 * @return a {@link Principal} element representing the just registered principal.
 * @throws IOException if sending an error fails.
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_XML)
@Path("register/shibboleth")
public JAXBElement<Principal> registerShibbolizedPrincipal(@FormParam("name") String name,
        @FormParam("remoteId") String remoteId, @FormParam("email") String email) throws IOException {
    dbDispatcher.setResourcesPaths(this.getRelativeServiceURI());
    Principal newPrincipal = new Principal();
    newPrincipal.setDisplayName(name);
    newPrincipal.setEMail(email);
    Map params = new HashMap<String, Object>();
    params.put("remoteId", remoteId);
    params.put("newPrincipal", newPrincipal);

    dbDispatcher.setResourcesPaths(this.getRelativeServiceURI());
    try {
        return (new RequestWrappers(this)).wrapAddPrincipalRequest(params, new RegisterShibbolizedPrincipal());
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    } catch (PrincipalExists e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_CONFLICT, e2.getMessage());
        return new ObjectFactory().createPrincipal(new Principal());
    }
}

From source file:org.apache.qpid.systest.rest.VirtualHostRestTest.java

public void testPutCreateSortedQueueWithoutKey() throws Exception {
    String queueName = getTestQueueName() + "-sorted";
    int responseCode = tryCreateQueue(queueName, "sorted", null);
    assertEquals("Unexpected response code", HttpServletResponse.SC_CONFLICT, responseCode);

    Map<String, Object> hostDetails = getRestTestHelper().getJsonAsSingletonList("/rest/virtualhost/test");

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> queues = (List<Map<String, Object>>) hostDetails
            .get(VirtualHostRestTest.VIRTUALHOST_QUEUES_ATTRIBUTE);
    Map<String, Object> testQueue = getRestTestHelper().find(Queue.NAME, queueName, queues);

    assertNull("Sorted queue without a key was created ", testQueue);
}

From source file:org.logger.event.web.controller.EventController.java

/**
 * /*from  w w w .  ja v  a  2 s . c om*/
 * @param request
 * @param apiKey
 * @param eventName
 * @param response
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.PUT)
public void createEvent(HttpServletRequest request,
        @RequestParam(value = "apiKey", required = true) String apiKey,
        @RequestParam(value = EVENT_NAME, required = true) String eventName, HttpServletResponse response)
        throws IOException {

    // add cross domain support
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers",
            "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
    response.setHeader("Access-Control-Allow-Methods", "PUT");

    boolean isValid = eventService.ensureValidRequest(request, response);
    if (!isValid) {
        eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, "Invalid API Key");
        return;
    }

    response.setContentType("application/json");
    if (!eventName.contains(".") || eventName.startsWith(".")) {
        eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN,
                "Invalid Event Name it should be noun.verb ");
        return;
    }
    Map<String, String> status = new HashMap<String, String>();
    if (eventService.createEvent(eventName, apiKey)) {
        status.put(EVENT_NAME, eventName);
        status.put("status", "Created");
        response.getWriter().write(new JSONObject(status).toString());
    } else {
        eventService.sendErrorResponse(request, response, HttpServletResponse.SC_CONFLICT,
                " Event Already Exists : " + eventName);
        return;
    }

}

From source file:org.dasein.cloud.rackspace.compute.CloudServerImages.java

@Override
public void remove(@Nonnull String providerImageId, boolean checkState)
        throws CloudException, InternalException {
    Logger logger = RackspaceCloud.getLogger(CloudServerImages.class, "std");

    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + CloudServerImages.class.getName() + ".remove(" + providerImageId + ")");
    }/*from w ww.  java2  s  . com*/
    try {
        RackspaceMethod method = new RackspaceMethod(provider);
        long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR;

        do {
            try {
                method.deleteServers("/images", providerImageId);
                return;
            } catch (RackspaceException e) {
                if (e.getHttpCode() != HttpServletResponse.SC_CONFLICT) {
                    throw e;
                }
            }
            try {
                Thread.sleep(CalendarWrapper.MINUTE);
            } catch (InterruptedException e) {
                /* ignore */ }
        } while (System.currentTimeMillis() < timeout);
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + CloudServerImages.class.getName() + ".remove()");
        }
    }
}

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

/**
 * @param params//from  w w  w .  j  a  va 2s.  com
 * @param request
 * @param response
 * @return
 * @throws RepositoryException
 * @throws JCRNodeFactoryServiceException
 * @throws IOException
 */
private Map<String, Object> doAcceptConnect(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");
    }

    myFriendBean.updateStatus(FriendStatus.ACCEPTED);
    friendFriendBean.updateStatus(FriendStatus.ACCEPTED);
    authzResolverService.setRequestGrant("Saving Accept Connect");
    try {
        myFriends.save();
        friendFriends.save();
        jcrService.getSession().save();
    } finally {
        authzResolverService.clearRequestGrant();
    }
    return OK;
}

From source file:org.opendatakit.aggregate.servlet.FormUploadServlet.java

/**
 * Handler for HTTP Post request that takes an xform, parses, and saves a
 * parsed version in the datastore//from   ww  w . j a  v a2 s .c  o  m
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    Double openRosaVersion = getOpenRosaVersion(req);

    // verify request is multipart
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.NO_MULTI_PART_CONTENT);
        return;
    }

    StringBuilder warnings = new StringBuilder();
    // TODO Add in form title process so it will update the changes in the XML
    // of form

    try {
        // process form
        MultiPartFormData uploadedFormItems = new MultiPartFormData(req);

        FormParserForJavaRosa parser = null;

        MultiPartFormItem formNameData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_NAME_PRAM);
        MultiPartFormItem formXmlData = uploadedFormItems.getFormDataByFieldName(ServletConsts.FORM_DEF_PRAM);

        String formName = null;
        String inputXml = null;
        String xmlFileName = "default.xml";

        if (formNameData != null) {
            formName = formNameData.getStream().toString(HtmlConsts.UTF8_ENCODE);
        }
        if (formXmlData != null) {
            // TODO: changed added output stream writer. probably something better
            // exists
            inputXml = formXmlData.getStream().toString(HtmlConsts.UTF8_ENCODE);
            xmlFileName = formXmlData.getFilename();
        }

        try {
            parser = new FormParserForJavaRosa(formName, formXmlData, inputXml, xmlFileName, uploadedFormItems,
                    warnings, cc);
            logger.info("Upload form successful: " + parser.getFormId());
            // GAE requires some settle time before these entries will be
            // accurately retrieved. Do not re-fetch the form after it has been
            // uploaded.
            resp.setStatus(HttpServletResponse.SC_CREATED);
            resp.setHeader("Location", cc.getServerURL() + BasicConsts.FORWARDSLASH + ADDR);
            if (openRosaVersion == null) {
                // web page -- show HTML response
                resp.setContentType(HtmlConsts.RESP_TYPE_HTML);
                resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);
                PrintWriter out = resp.getWriter();
                out.write(HtmlConsts.HTML_OPEN);
                out.write(HtmlConsts.BODY_OPEN);
                if (warnings.length() != 0) {
                    out.write("<p>Form uploaded with warnings. There are value fields in the form that do not "
                            + "have <code>&lt;bind/&gt;</code> declarations or those <code>&lt;bind/&gt;</code> "
                            + "declarations do not have a <code>type</code> attribute that "
                            + "identifies the data type of that field (e.g., boolean, int, decimal, date, dateTime, time, string, "
                            + "select1, select, barcode, geopoint or binary).</p>"
                            + "<p><b>All these value fields have been declared as string values.</b> It will use "
                            + "lexical ordering on those fields.  E.g., the value 100 will be considered less than 11.</p>"
                            + "<p><font color=\"red\">If these value fields hold date, dateTime, time or numeric data (e.g., decimal or int), then "
                            + "ODK Aggregate will produce erroneous sortings and erroneous filtering results against those value fields.</font></p>"
                            + "<table><th><td>Field Name</td></th>");
                    out.write(warnings.toString());
                    out.write("</table>");
                } else {
                    out.write("<p>Successful form upload.</p>");
                }
                out.write("<p>Click ");

                out.write(HtmlUtil.createHref(cc.getWebApplicationURL(ADDR), "here", false));
                out.write(" to return to add new form page.</p>");
                out.write(HtmlConsts.BODY_CLOSE);
                out.write(HtmlConsts.HTML_CLOSE);
            } else {
                addOpenRosaHeaders(resp);
                resp.setContentType(HtmlConsts.RESP_TYPE_XML);
                resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);
                PrintWriter out = resp.getWriter();
                out.write("<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">");
                if (warnings.length() != 0) {
                    StringBuilder b = new StringBuilder();
                    b.append("<p>Form uploaded with warnings. There are value fields in the form that do not "
                            + "have <code>&lt;bind/&gt;</code> declarations or those <code>&lt;bind/&gt;</code> "
                            + "declarations do not have a <code>type</code> attribute that "
                            + "identifies the data type of that field (e.g., boolean, int, decimal, date, dateTime, time, string, "
                            + "select1, select, barcode, geopoint or binary).</p>"
                            + "<p><b>All these value fields have been declared as string values.</b> It will use "
                            + "lexical ordering on those fields.  E.g., the value 100 will be considered less than 11.</p>"
                            + "<p><font color=\"red\">If these value fields hold date, dateTime, time or numeric data (e.g., decimal or int), then "
                            + "ODK Aggregate will produce erroneous sortings and erroneous filtering results against those value fields.</font></p>"
                            + "<table><th><td>Field Name</td></th>");
                    b.append(warnings.toString());
                    b.append("</table>");
                    out.write("<message>");
                    out.write(StringEscapeUtils.escapeXml10(b.toString()));
                    out.write("</message>");
                } else {
                    out.write("<message>Successful upload.</message>");
                }
                out.write("</OpenRosaResponse>");
            }

        } catch (ODKFormAlreadyExistsException e) {
            logger.info("Form already exists: " + e.toString());
            resp.sendError(HttpServletResponse.SC_CONFLICT,
                    ErrorConsts.FORM_WITH_ODKID_EXISTS + "\n" + e.toString());
        } catch (ODKIncompleteSubmissionData e) {
            logger.warn("Form upload parsing error: " + e.toString());
            switch (e.getReason()) {
            case TITLE_MISSING:
                createTitleQuestionWebpage(resp, inputXml, xmlFileName, cc);
                return;
            case ID_MALFORMED:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        ErrorConsts.JAVA_ROSA_PARSING_PROBLEM + "\n" + e.toString());
                return;
            case ID_MISSING:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_ID);
                return;
            case MISSING_XML:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_INFO);
                return;
            case BAD_JR_PARSE:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        ErrorConsts.JAVA_ROSA_PARSING_PROBLEM + "\n" + e.toString());
                return;
            case MISMATCHED_SUBMISSION_ELEMENT:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.FORM_INVALID_SUBMISSION_ELEMENT);
                return;
            default:
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.INVALID_PARAMS);
                return;
            }
        } catch (ODKEntityPersistException e) {
            // TODO NEED TO FIGURE OUT PROPER ACTION FOR ERROR
            logger.error("Form upload persistence error: " + e.toString());
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
        } catch (ODKDatastoreException e) {
            logger.error("Form upload persistence error: " + e.toString());
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
        } catch (ODKParseException e) {
            // unfortunately, the underlying javarosa utility swallows the parsing
            // error.
            logger.error("Form upload persistence error: " + e.toString());
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    ErrorConsts.PARSING_PROBLEM + "\n" + e.toString());
        }
    } catch (FileUploadException e) {
        logger.error("Form upload persistence error: " + e.toString());
        e.printStackTrace(resp.getWriter());
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ErrorConsts.UPLOAD_PROBLEM);
    }
}

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

/**
 * @param params/*from   w ww  .  ja  va2  s . c om*/
 * @param request
 * @param response
 * @return
 * @throws RepositoryException
 * @throws JCRNodeFactoryServiceException
 * @throws IOException
 */
private Map<String, Object> doCancelConnect(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.PENDING) || !friendFriendBean.isInState(FriendStatus.INVITED)) {
        throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT,
                "The invitation to connect is not current");
    }

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

From source file:org.apache.qpid.systest.rest.VirtualHostRestTest.java

public void testPutCreateQueueOfUnsupportedType() throws Exception {
    String queueName = getTestQueueName();
    int responseCode = tryCreateQueue(queueName, "unsupported", null);
    assertEquals("Unexpected response code", HttpServletResponse.SC_CONFLICT, responseCode);

    Map<String, Object> hostDetails = getRestTestHelper().getJsonAsSingletonList("/rest/virtualhost/test");

    @SuppressWarnings("unchecked")
    List<Map<String, Object>> queues = (List<Map<String, Object>>) hostDetails
            .get(VirtualHostRestTest.VIRTUALHOST_QUEUES_ATTRIBUTE);
    Map<String, Object> queue = getRestTestHelper().find(Queue.NAME, queueName, queues);

    assertNull("Queue of unsupported type was created", queue);
}

From source file:com.newatlanta.appengine.datastore.CachingDatastoreService.java

@SuppressWarnings("unchecked")
private static void doWriteBehindTask(HttpServletRequest req, HttpServletResponse res) throws IOException {
    Object payload = null;/*from   w ww  . ja  v a2 s.  c  o m*/
    try {
        payload = deserialize(req);
        if (payload == null) {
            return;
        }
    } catch (Exception e) {
        log.warning(e.toString());
        return;
    }
    MemcacheService memcache = getMemcacheService();
    List<Key> keys;
    if (payload instanceof Key) {
        keys = new ArrayList<Key>();
        keys.add((Key) payload);
        // delete flag that prevents multiple tasks from being queued
        memcache.delete(keyToString((Key) payload));
    } else if (payload instanceof List) {
        keys = (List) payload;
    } else {
        log.warning(payload.getClass().getName());
        return;
    }
    Map<String, Entity> entityMap = (Map) memcache.getAll((List) keys);
    if ((entityMap != null) && !entityMap.isEmpty()) {
        try {
            if (getDatastoreService().put(entityMap.values()).size() != entityMap.size()) {
                log.info("failed to write all entities - retrying");
                res.sendError(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
        } catch (DatastoreTimeoutException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT);
        } catch (ConcurrentModificationException e) { // retry task
            log.info(e.getMessage());
            res.sendError(HttpServletResponse.SC_CONFLICT);
        } catch (Exception e) { // don't retry
            log.warning(e.toString());
        }
    }
}