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:be.usgictprofessionals.usgfinancewebapp.restresources.RESTDataResources.java

/**
 *
 * @param response/*from w ww. j  a v  a 2 s  . c  om*/
 * @param id
 * @return XmlRootElement class which will automatically be translated into
 * JSON. 409 error code will be send if there hasn't been any input
 * get the data required for the return ratio overview page
 */
@GET
@Path("/return/{id}")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<ReturnRatioData> getReturn(@Context final HttpServletResponse response,
        @PathParam("id") String id) {
    if (!DataDAO.getInstance().inputHasBeenReceived()) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
    }
    return DataDAO.getInstance().getReturn(Integer.parseInt(id));
}

From source file:de.tub.av.pe.xcapsrv.XCAPResultFactory.java

private static XCAPResult conflictNOTXmlAttValue() {
    XCAPResult result = new XCAPResult();
    result.setStatusCode(HttpServletResponse.SC_CONFLICT);
    StringBuilder content = new StringBuilder(ERROR_DOCUMENT_PREFIX);
    content.append("<" + XDMSConstants.NOT_XML_ATT_VALUE + "/>");
    content.append(ERROR_DOCUMENT_SUFFIX);
    result.setBody(content.toString());/*ww  w .  jav  a  2 s.c o  m*/
    result.setMimeType(XDMSConstants.MIME_TYPE_CONFLICT);
    return result;
}

From source file:fi.hoski.web.forms.EventServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    Event event;//w ww  .j  ava2s .c o m
    String[] eventKeys = request.getParameterValues("event");
    if (eventKeys == null) {
        log("Event parameter missing");
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id=\"eNoEvent\">Event parameter missing</div>");
        return;
    } else if (Arrays.asList(eventKeys).contains(Event.EVENT_KEY_CHOOSE)) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                "<div id='eChooseEvent'>Choose the event</div>");
        return;
    }

    int count = 1;
    try {
        for (String eventKey : eventKeys) {
            if (!eventKey.isEmpty()) {
                try {
                    event = eventManager.getEvent(eventKey);
                } catch (Exception e) {
                    log(eventKey);
                    log(e.getMessage(), e);
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event not found</div>");
                    return;
                }

                Reservation reservation = new Reservation(event);

                @SuppressWarnings("unchecked")
                Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();

                reservation.set(Reservation.CREATOR, request.getRemoteUser());
                reservation.populate(params);
                String[] bk = params.get(Repository.VENEET_KEY);
                if (bk != null) {
                    Key boatKey = KeyFactory.stringToKey(bk[0]);
                    reservation.set(Repository.VENEID, boatKey);
                }

                eventManager.createReservation(reservation, false);
            } else {
                if (count == 1) {
                    sendError(response, HttpServletResponse.SC_BAD_REQUEST,
                            "<div id=\"eNoEvent\">Event key not found</div>");
                    return;
                }
            }
            count++;
        }
    } catch (EntityNotFoundException ex) {
        throw new ServletException(ex);
    } catch (DoubleBookingException ex) {
        if (count == 1) {
            log(ex.getMessage(), ex);
            sendError(response, HttpServletResponse.SC_CONFLICT,
                    "<div id=\"eDoubleBooking\">Double booking.</div>");
        }
    } catch (EventFullException e) {
        if (count == 1) {
            log(e.getMessage(), e);
            sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eEventFull\">Event full.</div>");
        }
    } catch (BoatNotFoundException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eBoatNotFound\">Boat not found.</div>");

    } catch (MandatoryPropertyMissingException e) {
        log(e.getMessage(), e);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eMandatoryPropertyMissing\">"
                + e.getMessage() + " mandatory property missing.</div>");

    } catch (ConcurrentModificationException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT,
                "<div id=\"eConcurrentModification\">Concurrent modification.</div>");
    }
    response.setContentType("UTF-8");
    response.getWriter().write("Ilmoittautumisesi on vastaanotettu.");
}

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

/**
 * Register a new plugin to the backend.
 *
 * @param response the HTTP response object.
 * @param plugin   the plugin object to register.
 *//*from ww  w.  j a  va  2 s .  c o m*/
@ResponseBody
@RequestMapping(value = "/plugin", method = RequestMethod.POST, produces = "application/json")
public Object addPlugin(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute final Plugin plugin) throws IOException {
    LOGGER.info(request.getRemoteAddr());

    final ApiResponse apiResponse = new ApiResponse();
    final String contextType = plugin.getContextType();
    if (contextType == null || plugin.getName() == null || plugin.getImageUrl() == null
            || plugin.getFilename() == null || plugin.getInstallUrl() == null || plugin.getDescription() == null
            || plugin.getRuntimeFactoryClass() == null || plugin.getUserId() == null) {
        LOGGER.info("wrong data: " + plugin);
        String errorMessage = "error";
        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 Set<Plugin> existingPlugins = pluginRepository.findByContextType(contextType);
        if (existingPlugins.isEmpty()) {
            LOGGER.info("addPlugin: " + plugin);
            pluginRepository.save(plugin);
            apiResponse.setStatus(HttpServletResponse.SC_OK);
            apiResponse.setMessage("ok");
            apiResponse.setValue(plugin);
            return apiResponse;
        } else {
            LOGGER.info("plugin exists: " + plugin);
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "a plugin with this contextType already exists");
        }
    }
    return null;
}

From source file:org.jboss.fuse.rhaccess.servlet.SupportServlet.java

/**
 * This method is triggered after the Case has been created on Red Hat support website.
 * It's responsible of attaching files to the already created case
 * <p/>/*  w ww .j a v  a 2s.  c  om*/
 * frond-end POSTs selected option (returned from GET) request that was checked,
 * we're expected to obtain and upload particular attachment to RHA
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        StringBuilder sb = readInput(request, response);

        //input is loaded into a JSON object
        JSONObject jsonObject = new JSONObject(sb.toString());
        if (log.isDebugEnabled()) {
            log.debug("JSon message: {}", sb.toString());
        }

        String authToken = jsonObject.getString("authToken");
        String attachment = jsonObject.getString("attachment");
        String caseNum = jsonObject.getString("caseNum");

        log.info("Selected attachments: " + attachment);

        API api = prepareApiInvocation(jsonObject, authToken);

        String type = attachment.split(":")[0].trim();
        Resource r = Resource.valueOf(type);
        File file = null;
        switch (r) {
        case LOG:
            String option = attachment.split(":")[1];
            file = obtainLogFile(option);
            break;

        case THREADDUMP:
            file = obtainThreadDump();
            break;

        case HEAPDUMP:
            file = obtainHeapDump();
            break;

        case SUPPORT_ZIP:
            file = obtainSupportInfos();
            break;

        case ETC:
            file = obtainEtcFiles();
            break;

        default:
            log.warn("Invoked an unregistered operation: " + r);
        }

        log.info("Adding file {} with size {} bytes to case", file.getAbsolutePath(), file.length());
        api.getAttachments().add(caseNum, /*publicly visible*/false, /*filename*/file.getAbsolutePath(),
                attachment /*description*/);

    } catch (Exception e) {
        if (e.getLocalizedMessage().contains("401")) {
            log.error("Unauthorized", e);
            response.sendError(HttpServletResponse.SC_CONFLICT, "Unauthorized");
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
            log.error("Failed to create attachment", e);
        }
    }
}

From source file:de.tub.av.pe.xcapsrv.XCAPResultFactory.java

private static XCAPResult conflictNoWellFormed() {
    XCAPResult result = new XCAPResult();
    result.setStatusCode(HttpServletResponse.SC_CONFLICT);
    StringBuilder content = new StringBuilder(ERROR_DOCUMENT_PREFIX);
    content.append("<" + XDMSConstants.NO_WELL_FORMED + "/>");
    content.append(ERROR_DOCUMENT_SUFFIX);
    result.setBody(content.toString());/*from w w  w .  jav a  2s  . c  o m*/
    result.setMimeType(XDMSConstants.MIME_TYPE_CONFLICT);
    return result;
}

From source file:org.eclipse.orion.server.cf.commands.BindRouteCommand.java

@Override
protected ServerStatus _doIt() {
    /* multi server status */
    MultiServerStatus status = new MultiServerStatus();

    try {/*from ww  w.  j a v  a 2 s.c o  m*/

        if (noRoute)
            /* nothing to do */
            return status;

        /* get available domains */
        GetDomainsCommand getDomainsCommand = new GetDomainsCommand(target);
        ServerStatus jobStatus = (ServerStatus) getDomainsCommand.doIt(); /* FIXME: unsafe type cast */
        status.add(jobStatus);

        if (!jobStatus.isOK())
            return status;

        List<Domain> domains = getDomainsCommand.getDomains();
        if (domains == null || domains.size() == 0) {
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST,
                    "Failed to find available domains in target", null));
            return status;
        }

        if (!appDomain.isEmpty()) {
            /* look if the domain is available */
            for (Iterator<Domain> iterator = domains.iterator(); iterator.hasNext();) {
                Domain domain = iterator.next();
                if (appDomain.equals(domain.getDomainName())) {
                    this.domain = domain;
                    break;
                }
            }

            /* client requested an unavailable domain, fail */
            if (domain == null) {
                String msg = NLS.bind("Failed to find domain {0} in target", appDomain);
                status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
                return status;
            }
        } else {
            /* client has not requested a specific domain, get the first available */
            this.domain = domains.get(0);
        }

        /* find out whether the declared host can be reused */
        String routeGUID = null;
        FindRouteCommand findRouteCommand = new FindRouteCommand(target, getApplication(), domain.getGuid());
        jobStatus = (ServerStatus) findRouteCommand.doIt(); /* FIXME: unsafe type cast */
        status.add(jobStatus);

        if (jobStatus.isOK()) {
            /* extract route guid */
            route = jobStatus.getJsonData();
            routeGUID = route.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                    .getString(CFProtocolConstants.V2_KEY_GUID);

            /* attach route to application */
            AttachRouteCommand attachRoute = new AttachRouteCommand(target, getApplication(), routeGUID);
            jobStatus = (ServerStatus) attachRoute.doIt(); /* FIXME: unsafe type cast */
            status.add(jobStatus);

            if (jobStatus.isOK())
                return status;

            /* the route is bound to another space */
            String msg = NLS.bind("The host {0} is already used in another space.",
                    findRouteCommand.getAppHost());
            status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_CONFLICT, msg, null));
            return status;
        }

        /* create a new route */
        CreateRouteCommand createRoute = new CreateRouteCommand(target, domain, getApplication());
        jobStatus = (ServerStatus) createRoute.doIt(); /* FIXME: unsafe type cast */
        status.add(jobStatus);

        if (!jobStatus.isOK())
            return status;

        /* extract route guid */
        route = jobStatus.getJsonData();
        routeGUID = route.getJSONObject(CFProtocolConstants.V2_KEY_METADATA)
                .getString(CFProtocolConstants.V2_KEY_GUID);

        /* attach route to application */
        AttachRouteCommand attachRoute = new AttachRouteCommand(target, getApplication(), routeGUID);
        jobStatus = (ServerStatus) attachRoute.doIt(); /* FIXME: unsafe type cast */
        status.add(jobStatus);

        if (!jobStatus.isOK())
            return status;

        return status;

    } catch (Exception e) {
        String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
        logger.error(msg, e);
        status.add(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return status;
    }
}

From source file:be.usgictprofessionals.usgfinancewebapp.restresources.RESTDataResources.java

/**
 *
 * @param response//  www . j  av  a2  s  .  co m
 * @param id
 * @return XmlRootElement class which will automatically be translated into
 * JSON. 409 error code will be send if there hasn't been any input
 * get the data required for the turnover ratio overview page
 */
@GET
@Path("/turnover/{id}")
@Produces(MediaType.APPLICATION_JSON)
public ArrayList<TurnoverRatioData> getTurnover(@Context final HttpServletResponse response,
        @PathParam("id") String id) {
    if (!DataDAO.getInstance().inputHasBeenReceived()) {
        response.setStatus(HttpServletResponse.SC_CONFLICT);
    }
    return DataDAO.getInstance().getTurnover(Integer.parseInt(id));
}

From source file:org.brekka.paveway.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    UploadingFilesContext filesContext = getFilesContext(req);

    String fileName = null;//  w w  w .j ava 2  s . c o m
    String contentDispositionStr = req.getHeader(ContentDisposition.HEADER);
    if (contentDispositionStr != null) {
        String encoding = req.getCharacterEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }
        ContentDisposition contentDisposition = ContentDisposition.valueOf(contentDispositionStr, encoding);
        fileName = contentDisposition.getFilename();
    }
    String accept = req.getHeader("Accept");
    String contentType = req.getHeader("Content-Type");
    String contentLengthStr = req.getHeader("Content-Length");
    String contentRangeStr = req.getHeader(ContentRange.HEADER);

    FileItemFactory factory;
    try {
        if (contentType.equals("multipart/form-data")) {
            if (fileName == null) {
                // Handles a standard file upload
                factory = new EncryptedFileItemFactory(0, null, getPavewayService(), filesContext.getPolicy());
                handle(factory, filesContext, req, resp);
            } else {
                throw new UnsupportedOperationException("This mode is no longer supported");
            }
        } else {
            ContentRange contentRange;
            if (contentRangeStr == null && contentLengthStr == null) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content-Range or Content-Length must be specified");
                return;
            } else if (contentRangeStr != null) {
                contentRange = ContentRange.valueOf(contentRangeStr);
            } else if (contentLengthStr != null) {
                Long contentLength = Long.valueOf(contentLengthStr);
                contentRange = new ContentRange(0, contentLength.longValue() - 1, contentLength.longValue());
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Only one of Content-Range or Content-Length must be specified");
                return;
            }
            UUID id = processUpload(fileName, contentRange, contentType, req);
            if (accept != null && accept.contains("application/json")) {
                resp.setContentType("application/json");
                resp.getWriter().printf("{\"id\": \"%s\"}", id);
            }
        }
    } catch (PavewayException e) {
        switch ((PavewayErrorCode) e.getErrorCode()) {
        case PW700:
            resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
            return;
        case PW701:
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        default:
            throw e;
        }
    } catch (FileUploadException e) {
        throw new PavewayException(PavewayErrorCode.PW800, e, "");
    }

    resp.setStatus(HttpServletResponse.SC_OK);
}

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

/**
 * Handler for HTTP Post request that takes an xform, parses, and saves a 
 * parsed version in the datastore /* w  w  w  . j a  v a 2 s . com*/
 * 
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();

    // verify user is logged in
    if (!verifyCredentials(req, resp)) {
        return;
    }

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

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

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

        FormParserForJavaRosa parser = null;
        String formName = null;
        String formXml = null;
        String xmlFileName = "default.xml";

        if (formNameData != null) {
            formName = formNameData.getStream().toString("UTF-8");
        }
        if (formXmlData != null) {
            // TODO: changed added output stream writer. probably something better exists
            formXml = formXmlData.getStream().toString("UTF-8");
            xmlFileName = formXmlData.getFilename();
        }

        // persist form
        EntityManager em = EMFactory.get().createEntityManager();

        if (formName != null && formXml != null) {
            try {
                parser = new FormParserForJavaRosa(formName, user.getNickname(), formXml, xmlFileName, em);
            } catch (ODKFormAlreadyExistsException e) {
                resp.sendError(HttpServletResponse.SC_CONFLICT, ErrorConsts.FORM_WITH_ODKID_EXISTS);
                return;
            }
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ErrorConsts.MISSING_FORM_INFO);
            return;
        }

        // TODO: do better error handling
        try {
            Form form = parser.getForm();
            em.persist(form);
            form.printDataTree(System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        em.close();
        resp.sendRedirect(FormsServlet.ADDR);

    } catch (FileUploadException e) {
        e.printStackTrace(resp.getWriter());
    }

}