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.haulmont.cuba.core.controllers.LogDownloadController.java

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;/*from  ww w.  ja v a 2  s. c o m*/
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    UserSession session = userSessions.getAndRefresh(sessionUUID);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);

    return session;
}

From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.servlets.JSONDumpServlet.java

private void handleRequest(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException, RepositoryException, ServletException {

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    // Generate current date and time for filename
    DateFormat df = new SimpleDateFormat("yyyyddMM_HHmmss");
    Date today = Calendar.getInstance().getTime();
    String filename = df.format(today);

    response.setHeader("Content-Disposition", "filename=jcr-checksum-" + filename + ".json");

    String optionsName = request.getParameter(ServletConstants.OPTIONS_NAME);
    ChecksumGeneratorOptions options = ChecksumGeneratorOptionsFactory.getOptions(request, optionsName);

    if (log.isDebugEnabled()) {
        log.debug(options.toString());/*from w  w  w. ja va2 s. c  o  m*/
    }

    Set<String> paths = RequestChecksumGeneratorOptions.getPaths(request);

    if (CollectionUtils.isEmpty(paths)) {
        try {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().print("ERROR: At least one path must be specified");
        } catch (IOException ioe) {
            throw ioe;
        }
    } else {
        Session session = request.getResourceResolver().adaptTo(Session.class);

        JsonWriter jsonWriter = new JsonWriter(response.getWriter());

        try {
            JSONGenerator.generateJSON(session, paths, options, jsonWriter);
            jsonWriter.close();
        } catch (RepositoryException e) {
            throw new ServletException("Error accessing repository", e);
        } catch (IOException e) {
            throw new ServletException("Unable to generate json", e);
        }
    }
}

From source file:io.wcm.caconfig.editor.impl.ConfigPersistServlet.java

@Override
@SuppressWarnings("null")
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!editorConfig.isEnabled()) {
        sendForbiddenWithMessage(response, "Configuration editor is disabled.");
        return;//from w  w  w. j  a va 2 s.  c o m
    }

    // get parameters
    String configName = request.getParameter(RP_CONFIGNAME);
    if (StringUtils.isBlank(configName)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    boolean collection = BooleanUtils.toBoolean(request.getParameter(RP_COLLECTION));

    ConfigurationMetadata configMetadata = configManager.getConfigurationMetadata(configName);
    if (configMetadata != null && configMetadata.isCollection() != collection) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Collection parameter mismatch.");
        return;
    }

    // parse JSON parameter data
    ConfigurationPersistData persistData = null;
    ConfigurationCollectionPersistData collectionPersistData = null;
    try {
        String jsonDataString = IOUtils.toString(request.getInputStream(), CharEncoding.UTF_8);
        JSONObject jsonData = new JSONObject(jsonDataString);
        if (collection) {
            collectionPersistData = parseCollectionConfigData(jsonData, configMetadata);
        } else {
            persistData = parseConfigData(jsonData, configMetadata);
        }
    } catch (JSONException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JSON data: " + ex.getMessage());
        return;
    }

    // persist data
    try {
        if (collection) {
            configManager.persistConfigurationCollection(request.getResource(), configName,
                    collectionPersistData);
        } else {
            configManager.persistConfiguration(request.getResource(), configName, persistData);
        }
    } catch (ConfigurationPersistenceAccessDeniedException ex) {
        sendForbiddenWithMessage(response, ex.getMessage());
    } catch (ConfigurationPersistenceException ex) {
        log.warn("Unable to persist data for " + configName + (collection ? "[col]" : ""), ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Unable to persist data: " + ex.getMessage());
    }
    /*CHECKSTYLE:OFF*/ catch (Exception ex) { /*CHECKSTYLE:ON*/
        log.error("Error getting configuration for " + configName + (collection ? "[col]" : ""), ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:org.attribyte.api.pubsub.impl.server.APIServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    List<String> path = splitPath(request);
    if (path.size() == 0) {
        sendServletResponse(NO_OPERATION_RESPONSE, response);
        return;/*from w ww. j a  va  2s.  co  m*/
    }

    Iterator<String> pathIter = path.iterator();
    String op = pathIter.next();
    switch (op) {
    case "topics":
        if (!pathIter.hasNext()) {
            sendServletResponse(NO_TOPIC_RESPONSE, response);
            return;
        } else {
            doTopicPost(request, pathIter.next(), response);
        }
        break;
    default:
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The operation, '" + op + "' is not supported");
        break;
    }
}

From source file:com.devicehive.util.ServerResponsesFactory.java

public static DeviceEquipmentVO parseDeviceEquipmentNotification(DeviceNotification notification,
        DeviceVO device) {//from   ww  w. j ava2s . c o m
    final String notificationParameters = notification.getParameters().getJsonString();
    if (notificationParameters == null) {
        throw new HiveException(Messages.NO_NOTIFICATION_PARAMS, HttpServletResponse.SC_BAD_REQUEST);
    }
    Gson gson = GsonFactory.createGson();
    JsonElement parametersJsonElement = gson.fromJson(notificationParameters, JsonElement.class);
    JsonObject jsonEquipmentObject;
    if (parametersJsonElement instanceof JsonObject) {
        jsonEquipmentObject = (JsonObject) parametersJsonElement;
    } else {
        throw new HiveException(Messages.PARAMS_NOT_JSON, HttpServletResponse.SC_BAD_REQUEST);
    }
    return constructDeviceEquipmentObject(jsonEquipmentObject, device);
}

From source file:com.fpmislata.banco.presentation.controladores.EntidadBancariaController.java

@RequestMapping(value = {
        "/entidadbancaria" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {/*from  ww w.  j a va2  s  . c  o  m*/
        EntidadBancaria entidadBancaria = (EntidadBancaria) jsonTransformer.fromJsonToObject(jsonEntrada,
                EntidadBancaria.class);
        entidadBancariaService.insert(entidadBancaria);

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        httpServletResponse.getWriter().println(jsonTransformer.ObjectToJson(entidadBancaria));

    } catch (BusinessException ex) {
        List<BusinessMessage> bussinessMessage = ex.getBusinessMessages();
        String jsonSalida = jsonTransformer.ObjectToJson(bussinessMessage);
        //System.out.println(jsonSalida);

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo Lista de Mensajes", ex1);
        }
    } catch (Exception ex1) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex1.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex2) {
            Logger.getLogger(EntidadBancariaController.class.getName()).log(Level.SEVERE,
                    "Error devolviendo la traza", ex2);
        }
    }
}

From source file:com.amazon.dtasdk.v2.servlets.InstantAccessServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {//  w w w.  j a va2s  .  c  o m
        Request req = new Request(request);

        if (!signer.verify(req, getCredentialStore())) {
            throw new SigningException("Request validation failed.");
        }

        String requestBody = req.getBody();

        // deserialize the content to a InstantAccessRequest object so we can check which operation is going
        // to be called
        InstantAccessRequest iaRequest = serializer.decode(requestBody, InstantAccessRequest.class);

        // process the request according to the operation
        InstantAccessResponse<?> iaResponse = processOperation(iaRequest.getOperation(), requestBody);

        response.setStatus(HttpServletResponse.SC_OK);
        response.getOutputStream().write(serializer.encode(iaResponse).getBytes(CHARSET));
    } catch (IOException e) {
        log.error("Unable to read the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (SigningException e) {
        log.error("Unable to verify the request against the credential store.", e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } catch (SerializationException e) {
        log.error("Serialization error.", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } catch (Exception e) {
        log.error("Unable to process the request.", e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    // Extraction of the authentication header
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // First test if we will by pass the security with a token
    String bypassSecurityToken = httpRequest
            .getHeader(SecurityUtils.ADDITIONAL_BYPASS_SECURITY_TOKEN_HEADER_NAME);
    if (StringUtils.isEmpty(bypassSecurityToken)) {
        // check in the parameters
        bypassSecurityToken = httpRequest
                .getParameter(SecurityUtils.ADDITIONAL_BYPASS_SECURITY_TOKEN_HEADER_NAME);
    }//  w w  w  . jav  a2s .  co  m
    if (StringUtils.isNotEmpty(bypassSecurityToken)) {
        // bypass security check
        String[] tokenParts = bypassSecurityToken.split(":");
        if (tokenParts.length != 2) {
            sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong token format", httpResponse);
        }
        String accessKeyId = tokenParts[0];
        String token = tokenParts[1];
        try {
            final TokenContext tokenContext = bypassSecurityTokenStore.removeToken(token);
            if (StringUtils.equals(accessKeyId, tokenContext.getPrincipalName())) {
                final S securityContext = findSecurityContext(accessKeyId);
                if (securityContext != null) {
                    // marking the request in order to filter it out later
                    httpRequest.setAttribute(SecurityUtils.SECURITY_BYPASSED_BY_TOKEN_ATTRIBUTE_NAME,
                            Boolean.TRUE);
                    doFilterWhenSecurityOK(httpRequest, httpResponse, chain, accessKeyId, securityContext);
                } else {
                    rejectAccessKeyId(accessKeyId, httpResponse);
                }
            } else {
                sendError(HttpServletResponse.SC_BAD_REQUEST, "Token is not yours", httpResponse);
            }
        } catch (Exception e) {
            sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid token", httpResponse, e);
        }
    } else {
        // classical security check
        final String authorizationHeader = httpRequest.getHeader(SecurityUtils.AUTHORIZATION_HEADER_NAME);
        if (authorizationHeader == null) {
            sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "Need " + SecurityUtils.AUTHORIZATION_HEADER_NAME + " header", httpResponse);
        } else {
            final Matcher matcher = AUTHORIZATION_HEADER_PATTERN.matcher(authorizationHeader);
            if (matcher.find()) {
                final String accessKeyId = matcher.group(1);
                final String signature = matcher.group(2);
                String date = httpRequest.getHeader("Date");
                // Handle the additional date header
                final String additionalDate = httpRequest.getHeader(SecurityUtils.ADDITIONAL_DATE_HEADER_NAME);
                if (additionalDate != null) {
                    date = additionalDate;
                }
                try {
                    final S securityContext = findSecurityContext(accessKeyId);
                    if (securityContext != null) {
                        if (handleParsedDate(DateUtil.parseDate(date), securityContext, httpRequest,
                                httpResponse)) {
                            // Let's process the signature in order to compare it
                            final String secretAccessKey = securityContext.getSecretAccessKey();
                            try {
                                final MultiReadHttpServletRequest multiReadHttpRequest = new MultiReadHttpServletRequest(
                                        httpRequest);
                                final String serverSignature = SecurityUtils.computeSignature(secretAccessKey,
                                        new HttpServletRequestToSign(multiReadHttpRequest));
                                if (serverSignature.equalsIgnoreCase(signature)) {
                                    doFilterWhenSecurityOK(multiReadHttpRequest, httpResponse, chain,
                                            accessKeyId, securityContext);
                                } else {
                                    rejectSignature(signature, serverSignature, httpResponse);
                                }
                            } catch (final NoSuchAlgorithmException e) {
                                throw new ServletException(e);
                            } catch (final InvalidKeyException e) {
                                sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid key", httpResponse, e);
                            }
                        }
                    } else {
                        rejectAccessKeyId(accessKeyId, httpResponse);
                    }
                } catch (final ParseException e) {
                    sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid date", httpResponse,
                            "Have to parse '" + date + "'", e);
                } finally {
                    doFinallyAfterFindSecurityContext();
                }
            } else {
                sendError(HttpServletResponse.SC_BAD_REQUEST, "Request incorrectly formated", httpResponse,
                        "Got " + authorizationHeader);
            }
        }
    }
}

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

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)//from  www  .j  av a2s .co  m
public void likeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal p) {
    Video v = videos.findOne(id);
    if (v == null) {
        sendError(response, HttpServletResponse.SC_NOT_FOUND, "Video not found");
        return;
    }
    if (!v.likeVideo(p.getName())) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Video already liked by user");
        return;
    }
    videos.save(v);
}