Example usage for javax.servlet.http HttpServletResponse SC_BAD_REQUEST

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

Status code (400) indicating the request sent by the client was syntactically incorrect.

Usage

From source file:org.geogig.geoserver.rest.GeogigDispatcher.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    try {/*  www . j a  va  2  s  .c o m*/
        converter.service(req, resp);
    } catch (Exception e) {
        if (e instanceof CommandSpecException) {
            String msg = e.getMessage();
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            if (msg != null) {
                resp.getOutputStream().write(msg.getBytes(Charsets.UTF_8));
            }
            return null;
        }
        RestletException re = null;
        if (e instanceof RestletException) {
            re = (RestletException) e;
        }
        if (re == null && e.getCause() instanceof RestletException) {
            re = (RestletException) e.getCause();
        }

        if (re != null) {
            resp.setStatus(re.getStatus().getCode());

            String reStr = re.getRepresentation().getText();
            if (reStr != null) {
                LOG.severe(reStr);
                resp.setContentType("text/plain");
                resp.getOutputStream().write(reStr.getBytes());
            }

            // log the full exception at a higher level
            LOG.log(Level.SEVERE, "", re);
        } else {
            LOG.log(Level.SEVERE, "", e);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            if (e.getMessage() != null) {
                resp.getOutputStream().write(e.getMessage().getBytes());
            }
        }
        resp.getOutputStream().flush();
    }

    return null;
}

From source file:com.oneops.cms.ws.rest.CmRestController.java

@ExceptionHandler(CmsException.class)
public void handleCmsException(CmsException e, HttpServletResponse response) throws IOException {
    sendError(response, HttpServletResponse.SC_BAD_REQUEST, e);
}

From source file:eu.trentorise.smartcampus.profileservice.controllers.rest.ExtendedProfileController.java

/**
 * Creates a extended profile for a user given application and profileId
 * Valid only if userId is the authenticated user
 * // ww w . j av a2  s .  c  o  m
 * @param response
 * @param userId
 * @param profileId
 * @param content
 * @throws IOException
 * @throws ProfileServiceException
 */
@RequestMapping(method = RequestMethod.POST, value = "/extprofile/app/{userId}/{profileId:.*}")
public void createExtendedProfile(HttpServletResponse response, @PathVariable("userId") String userId,
        @PathVariable("profileId") String profileId, @RequestBody Map<String, Object> content)
        throws IOException, ProfileServiceException {

    ExtendedProfile extProfile = new ExtendedProfile();
    extProfile.setProfileId(profileId);
    extProfile.setUserId(userId);
    extProfile.setContent(content);
    extProfile.setUser(userId);
    extProfile.setUpdateTime(System.currentTimeMillis());

    try {
        User user = getUserObject(userId);
        if (user == null) {
            throw new SmartCampusException("No user found for id " + userId);
        }
        profileManager.create(user, extProfile);
    } catch (AlreadyExistException e) {
        logger.error(
                String.format("Extended profile already exists userId:%s, profileId:%s", userId, profileId), e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (SmartCampusException e) {
        logger.error("General exception creating extended profile for user " + userId, e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

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

/**
 * Lists pending runs, obtains status, or show logs of a particular run.<ol>
 * <li>Pending: http://..../pending/</li>
 * <li>Status:  http://..../status/${runid}</li>
 * <li>Logs:    http://..../logs/${runid}</li>
 * <li>Tail Logs: http://..../logs/${runid}/tail</li>
 * <li>Follow Logs: http://..../logs/${runid}/follow</li>
 * <li>Combination of tail and follow, postfix /tail/follow</li>
 * </ol>./*from  ww w  . j  a v a 2 s .c  om*/
 * @param request The request object
 * @param response The response object
 * @throws ServletException Error executing servlet
 * @throws IOException I/O error
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String[] reqC = getPathComponents(request);
    if ("/status".equals(reqC[0])) {
        sendStatus(reqC, response);
    } else if ("/pending".equals(reqC[0])) {
        sendPending(response);
    } else if ("/logs".equals(reqC[0])) {
        sendLogs(reqC, response);
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Request string " + reqC[0] + " not understood!");
    }
}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

/**
 * Process a GET request for the specified resource.
 *
 * @param request// ww  w  .  ja  v  a 2 s  .c om
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        JsonGenerator jg = null;
        String jsonpcb = null;
        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            // "callback" parameter implies JSONP outpout
            jsonpcb = request.getParameter(CALLBACK_PARAM);
            if (jsonpcb != null) {
                response.setContentType("application/javascript; charset=utf8");
                writer.write(jsonpcb + "(");
            } else {
                response.setContentType("application/json; charset=utf8");
            }

            jg = jsonFactory.createGenerator(writer);
            jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
            jg.useDefaultPrettyPrinter();
            jg.writeStartObject();

            // query per mbean attribute
            String getmethod = request.getParameter("get");
            if (getmethod != null) {
                String[] splitStrings = getmethod.split("\\:\\:");
                if (splitStrings.length != 2) {
                    jg.writeStringField("result", "ERROR");
                    jg.writeStringField("message", "query format is not as expected.");
                    jg.flush();
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                listBeans(jg, new ObjectName(splitStrings[0]), splitStrings[1], response);
                return;
            }

            // query per mbean
            String qry = request.getParameter("qry");
            if (qry == null) {
                qry = "*:*";
            }
            listBeans(jg, new ObjectName(qry), null, response);
        } finally {
            if (jg != null) {
                jg.close();
            }
            if (jsonpcb != null) {
                writer.write(");");
            }
            if (writer != null) {
                writer.close();
            }
        }
    } catch (IOException e) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:uk.ac.ebi.eva.server.ws.StudyWSServer.java

@RequestMapping(value = "/{study}/view", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "The info of a study", response = QueryResponse.class)
public QueryResponse getStudy(@PathVariable("study") String study,
        @RequestParam(name = "species") String species, HttpServletResponse response)
        throws UnknownHostException, IllegalOpenCGACredentialsException, IOException {
    initializeQueryOptions();//from  w w  w  . j  a v  a 2s .  c o m

    StudyDBAdaptor studyMongoDbAdaptor = DBAdaptorConnector.getStudyDBAdaptor(species);

    QueryResult idQueryResult = studyMongoDbAdaptor.findStudyNameOrStudyId(study, queryOptions);
    if (idQueryResult.getNumResults() == 0) {
        QueryResult queryResult = new QueryResult();
        queryResult.setErrorMsg("Study identifier not found");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return setQueryResponse(queryResult);
    }

    BasicDBObject id = (BasicDBObject) idQueryResult.getResult().get(0);
    QueryResult finalResult = studyMongoDbAdaptor
            .getStudyById(id.getString(DBObjectToVariantSourceConverter.STUDYID_FIELD), queryOptions);
    finalResult.setDbTime(finalResult.getDbTime() + idQueryResult.getDbTime());

    return setQueryResponse(finalResult);
}

From source file:ch.admin.suis.msghandler.servlet.TriggerServlet.java

/**
 * Processes the incoming requests.//from  w ww. j  av  a 2 s. c  o m
 *
 * @param request  An HTTP Request.
 * @param response The Response
 * @throws ServletException Something went wront in the servlet !
 * @throws IOException      Classical IO problems.
 */
private void doProcess(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(TEXT);

    final String action = request.getParameter("action");

    try {
        if (StringUtils.equalsIgnoreCase(action, "send")) {
            dispatchSendRequest(request, response);
        } else if (StringUtils.equalsIgnoreCase(action, "receive")) {
            handleReceive(response);
        } else if (StringUtils.equalsIgnoreCase(action, "poll")) {
            handlePoll(response);
        } else {
            String msg = "No valid parameter found. Valid parameter: action={send,receive,poll}";
            LOG.warn(msg);
            response.getWriter().println(msg);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (SchedulerException ex) {
        String msg = "cannot trigger an immediate job";
        LOG.fatal(msg, ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(msg, ex);
    }
}

From source file:com.thinkberg.webdav.PropPatchHandler.java

/**
 * Handle a PROPPATCH request.//from  w  w w.  java2s  . c om
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = VFSBackend.resolveFile(request.getPathInfo());

    try {
        if (!LockManager.getInstance().evaluateCondition(object, getIf(request)).result) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }
    } catch (LockException e) {
        response.sendError(SC_LOCKED);
        return;
    } catch (ParseException e) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    if (object.exists()) {
        SAXReader saxReader = new SAXReader();
        try {
            Document propDoc = saxReader.read(request.getInputStream());
            logXml(propDoc);

            Element propUpdateEl = propDoc.getRootElement();
            List<Element> requestedProperties = new ArrayList<Element>();
            for (Object elObject : propUpdateEl.elements()) {
                Element el = (Element) elObject;
                String command = el.getName();
                if (AbstractDavResource.TAG_PROP_SET.equals(command)
                        || AbstractDavResource.TAG_PROP_REMOVE.equals(command)) {
                    for (Object propElObject : el.elements()) {
                        for (Object propNameElObject : ((Element) propElObject).elements()) {
                            Element propNameEl = (Element) propNameElObject;
                            requestedProperties.add(propNameEl);
                        }
                    }
                }
            }

            // respond as XML encoded multi status
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(SC_MULTI_STATUS);

            Document multiStatusResponse = getMultiStatusResponse(object, requestedProperties,
                    getBaseUrl(request));

            logXml(multiStatusResponse);

            // write the actual response
            XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
            writer.write(multiStatusResponse);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            LOG.error("invalid request: " + e.getMessage());
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        }
    } else {
        LOG.error(object.getName().getPath() + " NOT FOUND");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.magnum.mobilecloud.video.VideoServiceCtrl.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}", method = RequestMethod.GET)
public @ResponseBody Video getVideoById(@PathVariable("id") long id, HttpServletResponse response) {
    Video video = null;//from   www .jav  a 2 s .  com
    try {
        video = videos.findOne(id);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
    return video;

}

From source file:org.energyos.espi.datacustodian.web.api.ManageRESTController.java

/**
 * Provides access to administrative commands through the pattern:
 * DataCustodian/manage?command=[resetDataCustodianDB |
 * initializeDataCustodianDB]//from   w  ww  .j a  va  2s.c  o m
 * 
 * @param response
 *            Contains text version of stdout of the command
 * @param params
 *            [["command" . ["resetDataCustodianDB" |
 *            "initializeDataCustodianDB"]]]
 * @param stream
 * @throws IOException
 */
@RequestMapping(value = Routes.DATA_CUSTODIAN_MANAGE, method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public void doCommand(HttpServletResponse response, @RequestParam Map<String, String> params,
        InputStream stream) throws IOException {

    response.setContentType(MediaType.TEXT_PLAIN_VALUE);

    try {
        try {
            String commandString = params.get("command");
            System.out.println("[Manage] " + commandString);
            ServletOutputStream output = response.getOutputStream();

            output.println("[Manage] Restricted Management Interface");
            output.println("[Manage] Request: " + commandString);

            String command = null;

            // parse command
            if (commandString.contains("resetDataCustodianDB")) {
                command = "/etc/OpenESPI/DataCustodian/resetDatabase.sh";
            } else if (commandString.contains("initializeDataCustodianDB")) {
                command = "/etc/OpenESPI/DataCustodian/initializeDatabase.sh";

            }

            if (command != null) {
                Process p = Runtime.getRuntime().exec(command);
                p.waitFor();
                output.println("[Manage] Result: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = reader.readLine();

                while (line != null) {
                    System.out.println("[Manage] " + line);
                    output.println("[Manage]: " + line);
                    line = reader.readLine();
                }
                reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                output.println("[Manage] Errors: ");
                line = reader.readLine();
                while (line != null) {
                    System.out.println("[Manage] " + line);
                    output.println("[Manage]: " + line);
                    line = reader.readLine();
                }
            }

        } catch (IOException e1) {
        } catch (InterruptedException e2) {
        }

        System.out.println("[Manage] " + "Done");

    } catch (Exception e) {
        System.out.printf("**** [Manage] Error: %s\n", e.toString());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}