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:com.pymegest.applicationserver.api.UsuarioController.java

@RequestMapping(value = { "/Usuario" }, method = RequestMethod.POST)
public void insert(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonInput) {

    try {/*from www.ja  v a2  s . c  o m*/

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Usuario usuario = (Usuario) objectMapper.readValue(jsonInput, Usuario.class);

        if (usuario != null) {

            usuarioDAO.insert(usuario);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(usuario);
            response.getWriter().println(jsonOutput);

        }

        else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("Imposible insertar un usuario.");

            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

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

@RequestMapping(value = Routes.ROOT_METER_READING_MEMBER, method = RequestMethod.DELETE)
public void delete(HttpServletResponse response, @PathVariable Long meterReadingId) {
    try {//from   www . j  a  v  a2 s.c  om
        resourceService.deleteById(meterReadingId, MeterReading.class);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.pymegest.applicationserver.api.ProductoController.java

@RequestMapping(value = { "/Producto" }, method = RequestMethod.POST)
public void insert(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonInput) {

    try {/*from www . j av  a2s  .c o m*/

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Producto producto = (Producto) objectMapper.readValue(jsonInput, Producto.class);

        if (producto != null) {

            productoDAO.insert(producto);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(producto);
            response.getWriter().println(jsonOutput);
        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("Imposible insertar un producto.");

            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:com.pymegest.applicationserver.api.EmpleadoController.java

@RequestMapping(value = { "/Empleado" }, method = RequestMethod.POST)
public void insert(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonInput) {

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

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Empleado empleado = (Empleado) objectMapper.readValue(jsonInput, Empleado.class);

        if (empleado != null) {

            empleadoDAO.insert(empleado);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(empleado);
            response.getWriter().println(jsonOutput);
        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("Imposible insertar un empleado.");

            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

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

@RequestMapping(value = Routes.ROOT_ELECTRIC_POWER_USAGE_SUMMARY_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/*  ww w.java2s  .co  m*/
public void update(HttpServletResponse response, @PathVariable Long electricPowerUsageSummaryId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException, FeedException {

    ElectricPowerUsageSummary electricPowerUsageSummary = electricPowerUsageSummaryService
            .findById(electricPowerUsageSummaryId);

    if (electricPowerUsageSummary != null) {
        try {
            ElectricPowerUsageSummary newElectricPowerUsageSummary = electricPowerUsageSummaryService
                    .importResource(stream);
            electricPowerUsageSummary.merge(newElectricPowerUsageSummary);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/query.{type}", method = RequestMethod.GET)
public void queryByGet(@PathVariable String type, @RequestParam(value = "e") String entityName,
        @RequestParam(value = "q") String queryStr,
        @RequestParam(value = "view", required = false) String viewName,
        @RequestParam(value = "first", required = false) Integer firstResult,
        @RequestParam(value = "max", required = false) Integer maxResults,
        @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "dynamicAttributes", required = false) Boolean dynamicAttributes,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {

    if (!connect(sessionId, response))
        return;/*w  w  w.j  ava  2s  . co  m*/

    try {
        MetaClass metaClass = metadata.getClass(entityName);
        if (metaClass == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Persistent entity " + entityName + " does not exist");
            return;
        }

        if (!entityOpPermitted(metaClass, EntityOp.READ)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        Map<String, String[]> queryParams = new HashMap<>(request.getParameterMap());
        queryParams.remove("e");
        queryParams.remove("q");
        queryParams.remove("view");
        queryParams.remove("first");
        queryParams.remove("s");
        queryParams.remove("max");
        queryParams.remove("dynamicAttributes");

        LoadContext loadCtx = new LoadContext(metaClass);
        loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(dynamicAttributes));
        LoadContext.Query query = new LoadContext.Query(queryStr);
        loadCtx.setQuery(query);
        if (firstResult != null)
            query.setFirstResult(firstResult);
        if (maxResults != null)
            query.setMaxResults(maxResults);

        for (Map.Entry<String, String[]> entry : queryParams.entrySet()) {
            String paramKey = entry.getKey();
            if (paramKey.endsWith("_type"))
                continue;

            if (entry.getValue().length != 1) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            String paramValue = entry.getValue()[0];
            Object parsedParam = parseQueryParameter(paramKey, paramValue, queryParams);
            query.setParameter(paramKey, parsedParam);
        }

        if (viewName == null) {
            View view = metadata.getViewRepository().getView(metaClass, View.LOCAL);
            loadCtx.setView(new View(view, "local-with-system-props", true));
        } else {
            loadCtx.setView(viewName);
        }
        List<Entity> entities = dataService.loadList(loadCtx);
        Converter converter = conversionFactory.getConverter(type);
        String result = converter.process(entities, metaClass, loadCtx.getView());
        writeResponse(response, result, converter.getMimeType());
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:com.eucalyptus.www.X509Download.java

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    String code = request.getParameter(PARAMETER_CODE);
    String userName = request.getParameter(PARAMETER_USERNAME);
    String accountName = request.getParameter(PARAMETER_ACCOUNTNAME);
    String mimetype = "application/zip";
    if (accountName == null || "".equals(accountName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No account name provided", response);
        return;//from  w ww  . j  a  v a2s. c o m
    }
    if (userName == null || "".equals(userName)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "No user name provided", response);
        return;
    }
    if (code == null || "".equals(code)) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "Wrong user security code", response);
        return;
    }

    User user = null;
    try {
        Account account = Accounts.lookupAccountByName(accountName);
        user = account.lookupUserByName(userName);
        if (!user.isEnabled() || !RegistrationStatus.CONFIRMED.equals(user.getRegistrationStatus())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (AuthException e) {
        hasError(HttpServletResponse.SC_BAD_REQUEST, "User does not exist", response);
        return;
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to retrieve user data", response);
        return;
    }
    try {
        if (!code.equals(user.resetToken())) {
            hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response);
            return;
        }
    } catch (Exception e) {
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can not reset user security code", response);
        return;
    }
    response.setContentType(mimetype);
    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + X509Download.NAME_SHORT + "-" + userName + "-x509.zip\"");
    LOG.info("pushing out the X509 certificate for user " + userName);

    byte[] x509zip = null;
    try {
        x509zip = getX509Zip(user);
    } catch (Exception e) {
        LOG.debug(e, e);
        hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to return user credentials", response);
        return;
    }
    try {
        ServletOutputStream op = response.getOutputStream();

        response.setContentLength(x509zip.length);

        op.write(x509zip);
        op.flush();

    } catch (Exception e) {
        LOG.error(e, e);
    }
}

From source file:org.onehippo.forge.camel.demo.rest.services.AbstractRestUpdateResource.java

/**
 * Invoke Solr Update Service based on the given <code>action</code> and <code>id</code>.
 * @param action Update action name. It should be either 'addOrReplace' or 'delete'.
 * @param handleUuid The document handle identifier.
 * @return//from   w w w.j  a v a 2  s. c o  m
 */
@POST
@Path("/")
public Response update(@QueryParam("action") @DefaultValue(INDEX_ACTION) String action,
        @QueryParam("id") String handleUuid) {

    log.info("Updating ('{}') document from search index: {}", action, handleUuid);

    if (StringUtils.isNotEmpty(handleUuid)) {
        try {
            HstRequestContext requestContext = RequestContextProvider.get();

            if (INDEX_ACTION.equals(action)) {

                Node node = requestContext.getSession().getNodeByIdentifier(handleUuid);
                HippoBean bean = (HippoBean) getObjectConverter(requestContext).getObject(node);

                if (bean instanceof BaseHippoDocument) {
                    BaseHippoDocument document = (BaseHippoDocument) bean;
                    JSONObject payload = createDocumentAddPayload(document);

                    if (payload != null) {
                        HttpResponse httpResponse = invokeUpdateService(action, payload);

                        if (httpResponse.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
                            return Response.status(httpResponse.getStatusLine().getStatusCode()).build();
                        }
                    }
                } else {
                    log.warn("The bean from '{}' is not a BaseHippoDocument.", handleUuid);
                }

            } else if (DELETE_ACTION.equals(action)) {

                JSONObject payload = createDocumentDeletePayload(handleUuid);
                HttpResponse httpResponse = invokeUpdateService(action, payload);

                final int status = httpResponse.getStatusLine().getStatusCode();

                if (status >= HttpServletResponse.SC_BAD_REQUEST) {
                    if (status == HttpServletResponse.SC_NOT_FOUND || status == HttpServletResponse.SC_GONE) {
                        log.info("The document is not found or no more exists: '{}'.", handleUuid);
                    } else if (status != HttpServletResponse.SC_OK) {
                        return Response.status(httpResponse.getStatusLine().getStatusCode()).build();
                    }
                }

            } else {

                log.warn("Unknown action: '{}'.", action);

            }
        } catch (ItemNotFoundException e) {
            log.warn("The news is not found by the identifier: '{}'", handleUuid);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.warn("Failed to find news by identifier.", e);
            } else {
                log.warn("Failed to find news by identifier. {}", e.toString());
            }

            throw new WebApplicationException(e, buildServerErrorResponse(e));
        }
    }

    return Response.ok().build();
}

From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentexams")
public @ResponseBody StudentInfoExams getStudentExams(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws InvocationException {
    try {/*from w ww. j  av  a2s.c o m*/
        User user = getCurrentUser();
        String userId = getUserId(user);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(token);
        StudentInfoExams result = getStudentExams(idAda);
        if (result != null) {
            return result;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:com.janrain.backplane.provision.ProvisioningController.java

/**
 * Handle all other errors//from www .  jav a2 s  .  c o  m
 */
@ExceptionHandler
@ResponseBody
public Map<String, String> handle(final Exception e, HttpServletResponse response) {
    logger.error("Error handling provisioning request", bpConfig.getDebugException(e));
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return new HashMap<String, String>() {
        {
            put(ERR_MSG_FIELD, e.getMessage());
        }
    };
}