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.openmrs.module.clinicalsummary.web.controller.service.ResponseController.java

@RequestMapping(method = RequestMethod.POST)
public void processResponse(@RequestParam(required = false, value = USERNAME) String username,
        @RequestParam(required = false, value = PASSWORD) String password, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    log.info("Processing responses from the android devices ...");

    try {/*w  ww .  j  av a  2s .  c  o  m*/
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);

        UtilService utilService = Context.getService(UtilService.class);
        // TODO: wanna puke with this code!!!!! super hacky!!!!!!!
        Map parameterMap = request.getParameterMap();
        for (Object parameterName : parameterMap.keySet()) {
            // skip the username and password request parameter
            if (!StringUtils.equalsIgnoreCase(USERNAME, String.valueOf(parameterName))
                    && !StringUtils.equalsIgnoreCase(PASSWORD, String.valueOf(parameterName))) {

                String id = String.valueOf(parameterName);
                String[] parameterValues = (String[]) parameterMap.get(id);

                log.info("ID: " + id);
                for (String parameterValue : parameterValues)
                    log.info("Parameter Values: " + String.valueOf(parameterValue));

                Patient patient = Context.getPatientService().getPatient(NumberUtils.toInt(id));
                if (patient != null)
                    processResponse(utilService, parameterValues, patient);
                else
                    processDeviceLogs(utilService, id, parameterValues);
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (ContextAuthenticationException e) {
        log.error("Authentication failure!", e);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        log.error("Unspecified exception happened when processing the request!", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.openmrs.module.hl7output.web.controller.RHEApatientController.java

@RequestMapping(value = "/{ecID}/encounters", method = RequestMethod.GET)
@ResponseBody//from ww w.  j a  v  a  2s . c o  m
public Object getEncounters(@PathVariable("ecID") String enterpriseId,
        @RequestParam(value = "encounterUniqueId", required = false) String encounterUniqueId,
        @RequestParam(value = "dateStart", required = false) String dateStart,
        @RequestParam(value = "dateEnd", required = false) String dateEnd, HttpServletRequest request,
        HttpServletResponse response) throws ResponseException {

    LogEncounterService service = Context.getService(LogEncounterService.class);

    Date fromDate = null;
    Date toDate = null;
    Patient p = null;
    ORU_R01 r01 = null;

    log.info("RHEA Controller call detected...");
    log.info("Enterprise Patient Id is :" + enterpriseId);
    log.info("encounterUniqueId is :" + encounterUniqueId);
    log.info("dateStart is :" + dateStart);

    GetEncounterLog getEncounterLog = new GetEncounterLog();
    getEncounterLog.setEncounterUniqueId(encounterUniqueId);

    // first, we create from and to data objects out of the String
    // parameters

    if (enterpriseId == null) {
        log.info("Error : missing enterpriseId");
        getEncounterLog.setResult("Error, missing enterpriseId");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    getEncounterLog.setEnterpriseId(enterpriseId);

    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    try {
        if (dateStart != null)
            fromDate = format.parse(dateStart);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied start date : " + dateStart);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("fromDate is :" + fromDate);

    try {
        if (dateEnd != null)
            toDate = format.parse(dateEnd);
    } catch (ParseException e) {
        log.info("Error : failed to parse specidied end date : " + dateEnd);
        getEncounterLog.setResult("Error, incorrectly parsed start date");
        service.saveGetEncounterLog(getEncounterLog);

        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    log.info("toDate is :" + toDate);

    getEncounterLog.setDateEnd(toDate);
    getEncounterLog.setDateStart(fromDate);

    // Next, we try to retrieve the matching patient object
    if (enterpriseId != null) {
        PatientIdentifierType patientIdentifierType = Context.getPatientService()
                .getPatientIdentifierTypeByName("ECID");
        List<PatientIdentifierType> identifierTypeList = new ArrayList<PatientIdentifierType>();
        identifierTypeList.add(patientIdentifierType);

        List<Patient> patients = Context.getPatientService().getPatients(null, enterpriseId, identifierTypeList,
                false);
        //I am not checking the identifier type here. Need to come back and add a check for this
        if (patients.size() == 1) {
            p = patients.get(0);
        }
    }

    // if the patient doesn't exist, we need to return 400-BAD REQUEST
    // because the parameters are malformed
    if (p == null) {
        log.info("Error : failed to retreive patient for the given uuid : " + enterpriseId);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    } else {
        log.info("Patient id : " + p.getPatientId() + "was retreived...");

        if (p != null) {
            //get all the encounters for this patient
            List<Encounter> encounterList = Context.getEncounterService().getEncountersByPatient(p);
            //if the enconteruniqueId is not null, we can isolate the given encounter

            if (encounterUniqueId != null) {
                Iterator<Encounter> i = encounterList.iterator();
                while (i.hasNext()) {
                    if (!i.next().getUuid().equals(encounterUniqueId))
                        i.remove();
                }
            }

            //If the encounterUniqueId was not given, we will try to filter encounters based on from and to dates
            List<Encounter> filteredEncounterList = new ArrayList<Encounter>();

            if (fromDate != null || toDate != null) {
                for (Encounter encounter : encounterList) {
                    if (fromDate != null && toDate != null) {
                        if ((encounter.getEncounterDatetime().after(fromDate))
                                && (encounter.getEncounterDatetime().before(toDate))) {
                            filteredEncounterList.add(encounter);
                        }

                    } else if (fromDate == null) {
                        if (encounter.getEncounterDatetime().before(toDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    } else {
                        if (encounter.getEncounterDatetime().after(fromDate)) {
                            filteredEncounterList.add(encounter);
                        }

                    }
                }

                log.info("The number of matching encounters are :" + filteredEncounterList.size());
                encounterList = filteredEncounterList;
            }
            log.info("Calling the ORU_R01 parser...");

            SortedSet<MatchingEncounters> encounterSet = new TreeSet<MatchingEncounters>();

            for (Encounter e : encounterList) {
                MatchingEncounters matchingEncounters = new MatchingEncounters();
                matchingEncounters.setGetEncounterLog(getEncounterLog);
                matchingEncounters.setEncounterId(e.getEncounterId());

                encounterSet.add(matchingEncounters);
            }

            getEncounterLog.setLogTime(new Date());
            if (encounterList.size() > 0)
                getEncounterLog.setResult("Results Retrived");
            if (encounterList.size() == 0)
                getEncounterLog.setResult("No Results Retrived");

            //Now we will generate the HL7 message

            GenerateORU_R01 R01Util = new GenerateORU_R01();
            try {
                r01 = R01Util.generateORU_R01Message(p, encounterList);
            } catch (Exception e) {
                getEncounterLog.setResult("Error : Processing hl7 message failed");
                service.saveGetEncounterLog(getEncounterLog);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }

            getEncounterLog.getMatchingEncounters().clear();
            getEncounterLog.setMatchingEncounters(encounterSet);

            service.saveGetEncounterLog(getEncounterLog);

        }

        try {
            // Convert the ORU_R01 object into a byte stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(r01);
            oos.flush();
            oos.close();
            bos.close();
            byte[] data = bos.toByteArray();

            // Write the bytestream into the HttpServletResponse
            ServletOutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();

            response.getWriter().flush();
            response.getWriter().close();

            //NOTE : Im returning the ORU_R01 object as a bytestream AND a session object. Why both ? remove one later !
            request.getSession().setAttribute("oru_r01", r01);

            response.setStatus(HttpServletResponse.SC_OK);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Return null for now
    return null;
}

From source file:com.samaxes.javax.rs.validation.PersonsIT.java

@Test
@RunAsClient//from ww w.j  av a  2s .co  m
@InSequence(40)
public void shouldReturnAValidationErrorWhenCreatingAPerson(@ArquillianResource URL baseURL) {
    Form form = new Form();

    Client client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build();
    Response response = client.target(baseURL + "r/persons/create").request(MediaType.APPLICATION_JSON)
            .header("Accept-Language", "pt").post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
    response.bufferEntity();

    logResponse("shouldReturnAValidationErrorWhenCreatingAPerson", response);
    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
}

From source file:com.ewcms.web.filter.PreviewFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String uri = request.getRequestURI();
    if (!StringUtils.endsWith(uri, PREVIEW_PATH)) {
        logger.debug("Uri is not preview address");
        chain.doFilter(req, rep);/*from  w ww  . jav a 2s  . co  m*/
        return;
    }

    HttpServletResponse response = (HttpServletResponse) rep;
    try {
        Integer channelId = getChannelId(request);
        Integer templateId = getTemplateId(request);
        Long articleId = getArticleId(request);
        if (templateId == null && (channelId == null || articleId == null)) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        String redirectUri = getRedirectUri(request, articleId, templateId);
        if (redirectUri == null) {
            logger.debug("Redirect's address is null");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            logger.debug("Redirect's address is {}", redirectUri);
            response.sendRedirect(redirectUri);
        }
    } catch (Exception e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.toString());
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.GraphServlet.java

private void graph(String termRefId, String mediaType, String orientation, String callback,
        HttpServletResponse response) {//ww w. j a  va  2 s  . c  om
    GraphOrientation graphOrientation = GraphOrientation.TB;

    if (orientation != null) {
        try {
            graphOrientation = GraphOrientation.valueOf(orientation);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentLength(0);
            return;
        }
    }

    if (mediaType == null) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);
        return;
    }

    try {
        String content = graphService.createGraph(termRefId, graphOrientation);
        // JSONP support
        if (callback != null) {
            StringBuilder builder = new StringBuilder(callback.length() + content.length() + 5);
            builder.append(callback);
            builder.append("(\"");
            builder.append(StringEscapeUtils.escapeJavaScript(content));
            builder.append("\");");
            content = builder.toString();
            mediaType = "application/javascript";
        }

        byte[] contentBytes = content.getBytes("UTF-8");

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType(mediaType + ";charset=utf-8");
        response.setHeader("Cache-Control", "public, max-age=0");
        response.getOutputStream().write(contentBytes);
    } catch (EntityNotFoundException e) {
        log("Failed to find term with reference id: " + termRefId, e);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } catch (Exception e) {
        log("Failed to create graph for term " + termRefId, e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentLength(0);
    }
}

From source file:com.groupon.odo.controllers.PathController.java

@RequestMapping(value = "/api/path", method = RequestMethod.POST)
public @ResponseBody String addPath(Model model, String profileIdentifier,
        @RequestParam(value = "pathName") String pathName, @RequestParam(value = "path") String path,
        @RequestParam(value = "bodyFilter", required = false) String bodyFilter,
        @RequestParam(value = "contentType", required = false) String contentType,
        @RequestParam(value = "requestType", required = false) Integer requestType,
        @RequestParam(value = "groups[]", required = false) Integer[] groups,
        @RequestParam(value = "global", defaultValue = "false") Boolean global, HttpServletResponse response)
        throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    // TODO: Update UI to display the appropriate error message for this
    if (pathName.equals("test")) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  \"test\" is a reserved path name.";
    }// w ww  .  j a v a  2  s  .c om

    if (pathName.contains("/")) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  Path names cannot contain \"/\"";
    }

    // test regex parsing of the path
    try {
        Pattern pattern = Pattern.compile(path);
    } catch (PatternSyntaxException pse) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "Cannot add path.  Path regular expression is not valid.";
    }

    int pathId = pathOverrideService.addPathnameToProfile(profileId, pathName, path);
    if (groups != null) {
        //then adds all the groups
        for (int j = 0; j < groups.length; j++)
            pathOverrideService.AddGroupByNumber(profileId, pathId, groups[j]);
    }

    pathOverrideService.setContentType(pathId, contentType);
    pathOverrideService.setRequestType(pathId, requestType);
    pathOverrideService.setGlobal(pathId, global);

    if (bodyFilter != null) {
        pathOverrideService.setBodyFilter(pathId, bodyFilter);
    }

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectWriter writer = objectMapper.writer();

    return writer.writeValueAsString(pathOverrideService.getPath(pathId));
}

From source file:net.siegmar.japtproxy.JaptProxyServlet.java

/**
 * Check the requested data and forward the request to internal sender.
 *
 * @param req the HttpServletRequest object
 * @param res the HttpServletResponse object
 * @throws ServletException {@inheritDoc}
 * @throws IOException      {@inheritDoc}
 *//*from ww w.  j ava2  s  . c  o  m*/
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    res.setBufferSize(Util.DEFAULT_BUFFER_SIZE);

    MDC.put("REQUEST_ID", DigestUtils.md5Hex(Long.toString(System.currentTimeMillis())));

    LOG.debug("Incoming request from IP '{}', " + "User-Agent '{}'", req.getRemoteAddr(),
            req.getHeader(HttpHeaderConstants.USER_AGENT));

    if (LOG.isDebugEnabled()) {
        logHeader(req);
    }

    try {
        japtProxy.handleRequest(req, res);
    } catch (final InvalidRequestException e) {
        LOG.warn(e.getMessage());
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
        return;
    } catch (final UnknownBackendException e) {
        LOG.info(e.getMessage());
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown backend");
        return;
    } catch (final ResourceUnavailableException e) {
        LOG.debug(e.getMessage(), e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    } catch (final HandlingException e) {
        LOG.error("HandlingException", e);
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } finally {
        MDC.clear();
    }

    res.flushBuffer();
}

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

@RequestMapping(value = "/{variantId}/exists", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "Checks if a variants exist", response = QueryResponse.class)
public QueryResponse checkVariantExists(@PathVariable("variantId") String variantId,
        @RequestParam(name = "studies", required = false) List<String> studies,
        @RequestParam("species") String species, HttpServletResponse response)
        throws IllegalOpenCGACredentialsException, UnknownHostException, IOException {
    initializeQueryOptions();//from ww  w  . j ava  2 s.c  om

    VariantDBAdaptor variantMongoDbAdaptor = DBAdaptorConnector.getVariantDBAdaptor(species);

    if (studies != null && !studies.isEmpty()) {
        queryOptions.put("studies", studies);
    }

    if (!variantId.contains(":")) { // Query by accession id
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return setQueryResponse(
                "Invalid position and alleles combination, please use chr:pos:ref or chr:pos:ref:alt");
    } else { // Query by chr:pos:ref:alt
        String parts[] = variantId.split(":", -1);
        if (parts.length < 3) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return setQueryResponse(
                    "Invalid position and alleles combination, please use chr:pos:ref or chr:pos:ref:alt");
        }

        Region region = new Region(parts[0], Integer.parseInt(parts[1]), Integer.parseInt(parts[1]));
        queryOptions.put("reference", parts[2]);
        if (parts.length > 3) {
            queryOptions.put("alternate", parts[3]);
        }

        QueryResult queryResult = variantMongoDbAdaptor.getAllVariantsByRegion(region, queryOptions);
        queryResult.setResult(Arrays.asList(queryResult.getNumResults() > 0));
        queryResult.setResultType(Boolean.class.getCanonicalName());
        return setQueryResponse(queryResult);
    }
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  w  w  .j  a v a2 s  . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        ServletInputStream sis = request.getInputStream();
        byte[] b = new byte[request.getContentLength()];
        sis.read(b, 0, b.length);
        String expression = new String(b);
        logger.debug("rule text: ", expression);
        EPStatement statement = epService.getEPAdministrator().createEPL(expression);
        logger.debug("statement json: " + Utils.Statement2JSONObject(statement));
        statement.addListener(new GenericListener());
        out.println(Utils.Statement2JSONObject(statement));
    } catch (EPException epe) {
        logger.error("creating statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:com.mockey.ui.JsonSchemaValidateServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Set<String> params = Sets.newHashSet();
    final Enumeration<String> enumeration = req.getParameterNames();

    // FIXME: no duplicates, it seems, but I cannot find the spec which
    // guarantees that
    while (enumeration.hasMoreElements())
        params.add(enumeration.nextElement());

    // We have required parameters
    if (!params.containsAll(ValidateRequest.REQUIRED_PARAMS)) {
        logger.warn("Missing parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
        return;/*from  ww  w.  j a v  a 2 s . c  o m*/
    }

    // We don't want extraneous parameters
    params.removeAll(ValidateRequest.VALID_PARAMS);

    if (!params.isEmpty()) {
        logger.warn("Invalid parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
        return;
    }

    final String rawSchema = req.getParameter(ValidateRequest.SCHEMA);
    final String data = req.getParameter(ValidateRequest.DATA);

    // Set correct content type
    resp.setContentType(MediaType.JSON_UTF_8.toString());

    final boolean useV3 = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_V3));
    final boolean useId = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_ID));

    final JsonNode ret = JsonSchemaUtil.buildResult(rawSchema, data, useV3, useId);

    final OutputStream out = resp.getOutputStream();

    try {
        out.write(ret.toString().getBytes(Charset.forName("UTF-8")));
        out.flush();
    } finally {
        Closeables.closeQuietly(out);
    }
}