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.orion.server.cf.servlets.AbstractRESTHandler.java

/**
 * A helper method which handles returning a 409 HTTP error status.
 * @param request The request being handled.
 * @param response The response associated with the request.
 * @param path Path mapped to the handled request. Used to display the error message.
 * @return <code>true</code> iff the 409 has been sent, <code>false</code> otherwise.
 *///from w w  w  .j  av a 2  s.c o  m
protected boolean handleConflictingResource(HttpServletRequest request, HttpServletResponse response,
        String path) throws ServletException {
    String msg = NLS.bind("Failed to handle request for {0}", path); //$NON-NLS-1$
    ServerStatus status = new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, msg, null);
    return statusHandler.handleRequest(request, response, status);
}

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

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path)
        throws CoreException, IOException, JSONException, ServletException, URISyntaxException,
        ConfigInvalidException {/*from  w  ww . j  a va2  s.  co  m*/
    Path p = new Path(path);
    if (p.segment(0).equals(Clone.RESOURCE) && p.segment(1).equals("file")) { //$NON-NLS-1$
        // expected path /gitapi/config/clone/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        if (gitDir == null)
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND,
                            NLS.bind("No repository found under {0}", p.removeFirstSegments(1)), null));
        Repository db = FileRepositoryBuilder.create(gitDir);
        URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.CONFIG);
        JSONObject toPost = OrionServlet.readJSONRequest(request);
        String key = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_KEY, null);
        if (key == null || key.isEmpty())
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Config entry key must be provided", null));
        String value = toPost.optString(GitConstants.KEY_CONFIG_ENTRY_VALUE, null);
        if (value == null || value.isEmpty())
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Config entry value must be provided", null));
        try {
            ConfigOption configOption = new ConfigOption(cloneLocation, db, key);
            boolean present = configOption.exists();
            if (present)
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT,
                                NLS.bind("Config entry for {0} already exists", key), null));
            save(configOption, value);

            JSONObject result = configOption.toJSON();
            OrionServlet.writeJSONResponse(request, response, result);
            response.setHeader(ProtocolConstants.HEADER_LOCATION,
                    result.getString(ProtocolConstants.KEY_LOCATION));
            response.setStatus(HttpServletResponse.SC_CREATED);
            return true;
        } catch (IllegalArgumentException e) {
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), e));
        }
    }
    return false;
}

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

/**
 *
 * <p>/*from w w  w  . ja v a 2 s .co  m*/
 * Creates a new role.
 * </p>
 *
 * <pre>
 * <b>Request</b>
 *
 * role data:
 * {
  *   "cn": "Name of the role"
  *   "description": "Description for the role"
  *   }
 * </pre>
 * <pre>
 * <b>Response</b>
 *
 * <b>- Success case</b>
 *
 * {
 *  "cn": "Name of the role",
 *  "description": "Description for the role"
 * }
 * </pre>
 *
 * @param request
 * @param response
 * @throws IOException
 */
@RequestMapping(value = REQUEST_MAPPING, method = RequestMethod.POST)
@PreAuthorize("hasRole('SUPERUSER')")
public void create(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        Role role = createRoleFromRequestBody(request.getInputStream());
        this.roleDao.insert(role);
        RoleResponse roleResponse = new RoleResponse(role, this.filter);
        String jsonResponse = roleResponse.asJsonString();
        ResponseUtil.buildResponse(response, jsonResponse, HttpServletResponse.SC_OK);

    } catch (DuplicatedCommonNameException emailex) {

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

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

    } catch (DataServiceException dsex) {
        LOG.error(dsex.getMessage());
        ResponseUtil.buildResponse(response, buildErrorResponse(dsex.getMessage()),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new IOException(dsex);
    } catch (IllegalArgumentException ex) {
        String jsonResponse = ResponseUtil.buildResponseMessage(Boolean.FALSE, ILLEGAL_CHARACTER);
        ResponseUtil.buildResponse(response, jsonResponse, HttpServletResponse.SC_CONFLICT);
    }
}

From source file:org.eclipse.orion.internal.server.servlets.site.SiteConfigurationResourceHandler.java

private boolean handleDelete(HttpServletRequest req, HttpServletResponse resp, SiteInfo site)
        throws CoreException {
    UserInfo user = OrionConfiguration.getMetaStore().readUser(getUserName(req));
    ISiteHostingService hostingService = Activator.getDefault().getSiteHostingService();
    IHostedSite runningSite = hostingService.get(site, user);
    if (runningSite != null) {
        String msg = NLS.bind("Site configuration is running at {0}. Must be stopped before it can be deleted",
                runningSite.getHost());//from  w  w w  .  j a v  a2s.c om
        throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, msg, null));
    }
    site.delete(user);
    return true;
}

From source file:gr.cti.android.experimentation.controller.PluginController.java

/**
 * Update an existing plugin.//  w  w  w.  j av  a2  s.  c  o  m
 *
 * @param response the HTTP response object.
 * @param plugin   the plugin object to update.
 * @param pluginId the id of the plugin to update.
 */
@ResponseBody
@RequestMapping(value = "/plugin/{pluginId}", method = RequestMethod.POST, produces = "application/json")
public Object addPlugin(HttpServletResponse response, @ModelAttribute final Plugin plugin,
        @PathVariable("pluginId") final long pluginId) throws IOException {

    final ApiResponse apiResponse = new ApiResponse();
    final String contextType = plugin.getContextType();
    if (pluginId != plugin.getId() || contextType == null || plugin.getName() == null
            || plugin.getImageUrl() == null
            //                || plugin.getFilename() == null
            //                || plugin.getInstallUrl() == null
            || plugin.getDescription() == null || plugin.getRuntimeFactoryClass() == null
            || plugin.getUserId() == null) {
        LOGGER.error("wrong data: " + plugin);
        String errorMessage = "error";
        if (pluginId != plugin.getId()) {
            errorMessage = "pluginId does not match submitted plugin description";
        } else if (contextType == null) {
            errorMessage = "contextType cannot be null";
        } else if (plugin.getName() == null) {
            errorMessage = "name cannot be null";
        } else if (plugin.getImageUrl() == null) {
            errorMessage = "imageUrl cannot be null";
            //            } else if (plugin.getFilename() == null) {
            //                errorMessage = "filename cannot be null";
            //            } else if (plugin.getInstallUrl() == null) {
            //                errorMessage = "url cannot be null";
        } else if (plugin.getDescription() == null) {
            errorMessage = "description cannot be null";
        } else if (plugin.getRuntimeFactoryClass() == null) {
            errorMessage = "runtimeFactoryClass cannot be null";
        } else if (plugin.getUserId() == null) {
            errorMessage = "userId cannot be null";
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
    } else {
        final Plugin storedPlugin = pluginRepository.findById((int) pluginId);
        if (storedPlugin != null) {

            final Set<Plugin> existingPlugins = pluginRepository.findByContextType(contextType);
            for (final Plugin existingPlugin : existingPlugins) {
                if (existingPlugin.getId() != pluginId) {
                    final String errorMessage = "this context type is already reserved by another plugin";
                    response.sendError(HttpServletResponse.SC_CONFLICT, errorMessage);
                }
            }

            LOGGER.info("updatePlugin: " + plugin);
            plugin.setId((int) pluginId);
            if (plugin.getFilename() == null || plugin.getFilename().equals("")) {
                plugin.setFilename(storedPlugin.getFilename());
            }
            if (plugin.getInstallUrl() == null || plugin.getInstallUrl().equals("")) {
                plugin.setInstallUrl(storedPlugin.getInstallUrl());
            }
            pluginRepository.save(plugin);
            apiResponse.setStatus(HttpServletResponse.SC_OK);
            apiResponse.setMessage("ok");
            apiResponse.setValue(plugin);
            return apiResponse;
        } else {
            LOGGER.error("plugin not found: " + plugin);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "a plugin with this id does not exist");
        }
    }
    return null;
}

From source file:org.mypackage.spring.controllers.EmailsSpringController.java

/**
 *
 * @param id/* ww  w. j  av a2 s . c  o m*/
 * @param emailId
 * @param address
 * @param categoryValue
 * @return
 */
@RequestMapping(value = "/contacts/{id}/modify/update_email/{emailId}/email_updated", method = RequestMethod.POST)
public ModelAndView postUpdateEmail(@PathVariable String id, @PathVariable String emailId,
        @RequestParam("address") String address, @RequestParam("category") String categoryValue) {
    ModelAndView modelAndView = new ModelAndView();
    try {
        updateEmailController.updateEmail(emailId, address, categoryValue, id);
        List<Email> emailsList = contactsController.retrieveAllEmails(id);
        modelAndView.addObject("emailList", emailsList);
        modelAndView.addObject("contactId", id);
        modelAndView.setViewName("redirect:/contacts/" + id + "/modify");
    } catch (DalException ex) {
        logger.error("A database error occured while trying to delete contact with ID = " + id, ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "There was a an internal database error.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage",
                "An error occured because of a malformed id." + id + " Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedCategoryException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_CONFLICT);
        modelAndView.addObject("errorMessage",
                "An internal conflict concerning the category of the email occured. Please try again.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (DuplicateEmailException ex) {
        modelAndView = getUpdateEmail(id, emailId);
        modelAndView.addObject("errorMessage",
                "The address you tried to submit already exists. Please enter a different one.");
    }
    return modelAndView;
}

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

@RequestMapping(method = RequestMethod.PUT, value = "/itinerary/{itineraryId}")
public @ResponseBody Boolean updateItinerary(HttpServletResponse response,
        @RequestBody(required = false) BasicItinerary itinerary, @PathVariable String itineraryId)
        throws Exception {
    try {//from  w w w.  j a  va2s  .c  o m
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

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

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("clientId", itineraryId);

        ItineraryObject res = domainStorage.searchDomainObject(pars, ItineraryObject.class);

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

            res.setClientId(itinerary.getClientId());
            res.setUserId(userId);
            res.setOriginalFrom(itinerary.getOriginalFrom());
            res.setOriginalTo(itinerary.getOriginalTo());
            res.setName(itinerary.getName());
            res.setData(itinerary.getData());
            if (itinerary.getAppId() == null || itinerary.getAppId().isEmpty()) {
                res.setAppId(NotificationHelper.MS_APP);
            } else {
                res.setAppId(itinerary.getAppId());
            }
            res.setRecurrency(itinerary.getRecurrency());

            domainStorage.saveItinerary(res);

            SavedTrip st = new SavedTrip(new Date(), res, RequestMethod.PUT.toString());
            domainStorage.saveSavedTrips(st);

            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:gr.cti.android.experimentation.controller.ExperimentController.java

/**
 * Adds a new {@see Experiment} to the system.
 *
 * @param response   the {@see HttpServletResponse}.
 * @param experiment the information about the {@see Experiment}.
 * @return the information of the {@see Experiment} added.
 * @throws IOException//from   w ww  .  j av a 2 s  .com
 */
@ResponseBody
@RequestMapping(value = "/experiment", method = RequestMethod.POST, produces = "application/json")
public ApiResponse addExperiment(HttpServletResponse response, @ModelAttribute BaseExperiment experiment)
        throws IOException {
    final ApiResponse apiResponse = new ApiResponse();
    LOGGER.info("addExperiment " + experiment);
    if (experiment.getName() == null || experiment.getDescription() == null
            || experiment.getUrlDescription() == null || experiment.getUrl() == null
            || experiment.getFilename() == null || experiment.getSensorDependencies() == null
            || experiment.getUserId() == null) {
        LOGGER.info("wrong data: " + experiment);
        String errorMessage = "error";
        if (experiment.getName() == null) {
            errorMessage = "name cannot be null";
        } else if (experiment.getDescription() == null) {
            errorMessage = "description cannot be null";
        } else if (experiment.getUrlDescription() == null) {
            errorMessage = "urlDescription cannot be null";
        } else if (experiment.getFilename() == null) {
            errorMessage = "filename cannot be null";
        } else if (experiment.getUrl() == null) {
            errorMessage = "url cannot be null";
        } else if (experiment.getSensorDependencies() == null) {
            errorMessage = "sensorDependencies cannot be null";
        } else if (experiment.getUserId() == null) {
            errorMessage = "userId cannot be null";
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage);
    } else {
        final Set<Experiment> existingExperiments = experimentRepository
                .findByNameAndUserId(experiment.getName(), experiment.getUserId());
        if (existingExperiments.isEmpty()) {
            Experiment experimentObj = new Experiment();
            experimentObj.setName(experiment.getName());
            experimentObj.setDescription(experiment.getDescription());
            experimentObj.setUrlDescription(experiment.getUrl());

            if (experiment.getFilename() != null && !experiment.getFilename().equals("")) {
                experimentObj.setFilename(experiment.getFilename());
            }
            if (experiment.getUrl() != null && !experiment.getUrl().equals("")) {
                experimentObj.setUrl(experiment.getUrl());
            }
            experimentObj.setContextType(EXPERIMENT_CONTEXT_TYPE);
            experimentObj.setSensorDependencies(experiment.getSensorDependencies());
            experimentObj.setUserId(experiment.getUserId());

            experimentObj.setEnabled(true);
            experimentObj.setStatus("1");
            LOGGER.info("addExperiment: " + experiment);
            experimentObj.setTimestamp(System.currentTimeMillis());
            experimentRepository.save(experimentObj);
            apiResponse.setStatus(HttpServletResponse.SC_OK);
            apiResponse.setMessage("ok");
            apiResponse.setValue(experimentObj);
            return apiResponse;
        } else {
            LOGGER.info("experiment exists: " + experiment);
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "an experiment with this name already exists for this user");
        }
    }
    return null;
}

From source file:aiai.ai.launchpad.server.ServerController.java

private HttpEntity<AbstractResource> returnEmptyAsConflict(HttpServletResponse response) throws IOException {
    response.sendError(HttpServletResponse.SC_CONFLICT);
    return new HttpEntity<>(new ByteArrayResource(new byte[0]), getHeader(0));
}

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

@DeleteMapping(value = "/tb-ui/authoring/rest/weblog/{id}")
public void deleteWeblog(@PathVariable String id, Principal p, HttpServletResponse response) {
    ResponseEntity maybeError = checkIfOwnerOfValidWeblog(id, p);
    if (maybeError == null) {
        Weblog weblog = weblogRepository.findById(id).orElse(null);
        if (weblog != null) {
            try {
                weblogManager.removeWeblog(weblog);
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_CONFLICT);
                log.error("Error removing weblog - {}", weblog.getHandle(), ex);
            }/*from  w  w  w .ja  v a 2  s.  co m*/
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        response.setStatus(maybeError.getStatusCode().value());
    }
}