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.imaginary.home.cloud.api.RestApi.java

public @Nullable String authenticate(@Nonnull String method, @Nonnull HttpServletRequest request,
        Map<String, Object> headers) throws RestException {
    Number timestamp = (Number) headers.get(TIMESTAMP);
    String apiKey = (String) headers.get(API_KEY);
    String signature = (String) headers.get(SIGNATURE);
    String version = (String) headers.get(VERSION);

    if (timestamp == null || apiKey == null || signature == null || version == null) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INCOMPLETE_HEADERS,
                "Incomplete authentication headers, requires: " + API_KEY + " - " + TIMESTAMP + " - "
                        + SIGNATURE + " - " + VERSION);
    }/*  w  w w.j a  v a 2  s.  c o  m*/
    if (signature.length() < 1) {
        throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SIGNATURE,
                "No signature was provided for authentication");
    }
    try {
        ControllerRelay relay = ControllerRelay.getRelay(apiKey);
        String userId = null;
        String customSalt;
        String secret;

        if (relay == null) {
            ApiKey key = ApiKey.getApiKey(apiKey);

            if (key == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_KEY,
                        "Invalid API key");
            }
            secret = key.getApiKeySecret();
            userId = key.getUserId();
            customSalt = userId;
        } else {
            secret = relay.getApiKeySecret();
            customSalt = relay.getLocationId();
        }
        String stringToSign;

        if (relay != null) {
            String token = Configuration.decrypt(relay.getLocationId(), relay.getToken());

            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + token + ":" + timestamp.longValue() + ":" + version;
        } else {
            stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":"
                    + timestamp.longValue() + ":" + version;
        }
        String expected;

        try {
            expected = CloudService.sign(Configuration.decrypt(customSalt, secret).getBytes("utf-8"),
                    stringToSign);
        } catch (Exception e) {
            throw new RestException(e);
        }
        if (!signature.equals(expected)) {
            throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.INVALID_SIGNATURE,
                    "String to sign was: " + stringToSign);
        }
        return userId;
    } catch (PersistenceException e) {
        throw new RestException(e);
    }
}

From source file:nl.surfnet.coin.teams.service.impl.GroupServiceBasicAuthentication10aTest.java

@Test
public void testGetGroupMembersEntryFaultyHttpResponse() {
    super.setResponseResource(new ByteArrayResource("not-even-valid-json".getBytes()));
    super.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    GroupMembersEntry groupMembersEntry = groupService.getGroupMembersEntry(provider, "personId", "whatever", 0,
            0);/*from w  w w .java2 s. c o m*/
    assertTrue(groupMembersEntry.getEntry().isEmpty());
}

From source file:com.amazon.speech.speechlet.servlet.SpeechletServlet.java

/**
 * Handles a POST request. Based on the request parameters, invokes the right method on the
 * {@code SpeechletV2}./*from   w w w .  ja  v  a 2s . c  o m*/
 *
 * @param request
 *            the object that contains the request the client has made of the servlet
 * @param response
 *            object that contains the response the servlet sends to the client
 * @throws IOException
 *             if an input or output error is detected when the servlet handles the request
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    byte[] serializedSpeechletRequest = IOUtils.toByteArray(request.getInputStream());
    byte[] outputBytes = null;

    try {
        if (disableRequestSignatureCheck) {
            log.warn("Warning: Speechlet request signature verification has been disabled!");
        } else {
            // Verify the authenticity of the request by checking the provided signature &
            // certificate.
            SpeechletRequestSignatureVerifier.checkRequestSignature(serializedSpeechletRequest,
                    request.getHeader(Sdk.SIGNATURE_REQUEST_HEADER),
                    request.getHeader(Sdk.SIGNATURE_CERTIFICATE_CHAIN_URL_REQUEST_HEADER));
        }

        outputBytes = speechletRequestHandler.handleSpeechletCall(speechlet, serializedSpeechletRequest);
    } catch (SpeechletRequestHandlerException | SecurityException ex) {
        int statusCode = HttpServletResponse.SC_BAD_REQUEST;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    } catch (Exception ex) {
        int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        log.error("Exception occurred in doPost, returning status code {}", statusCode, ex);
        response.sendError(statusCode, ex.getMessage());
        return;
    }

    // Generate JSON and send back the response
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    try (final OutputStream out = response.getOutputStream()) {
        response.setContentLength(outputBytes.length);
        out.write(outputBytes);
    }
}

From source file:com.orange.mmp.mvc.bundle.Controller.java

@SuppressWarnings("unchecked")
@Override//  www  .j ava 2s  .c  o  m
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    int pathInfoStart = request.getRequestURI().indexOf(urlMapping);
    if (pathInfoStart < 0) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
        return null;
    }
    // Get user agent to obtain branchID
    String userAgent = request.getHeader(Constants.HTTP_HEADER_USERAGENT);
    Mobile mobile = new Mobile();
    mobile.setUserAgent(userAgent);
    Mobile[] mobiles = (Mobile[]) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile").find(mobile);
    String branchId = null;//Constants.DEFAULT_BRANCH_ID;
    if (mobiles != null && mobiles.length > 0) {
        branchId = mobiles[0].getBranchId();
    } else {
        Branch branch = new Branch();
        branch.setDefault(true);
        Branch[] branches = (Branch[]) DaoManagerFactory.getInstance().getDaoManager().getDao("branch")
                .find(branch);
        if (branches != null && branches.length > 0)
            branchId = branches[0].getId();
    }

    String pathInfo = request.getRequestURI().substring(pathInfoStart + urlMapping.length());
    String requestParts[] = pathInfo.split("/");
    String widgetId = null;
    String resourceName = null;
    InputStream input = null;

    if (requestParts.length > 2) {
        widgetId = requestParts[1];
        resourceName = pathInfo.substring(widgetId.length() + 2);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentLength(0);
        return null;
    }

    input = WidgetManager.getInstance().getWidgetResource(resourceName, widgetId, branchId);

    if (input == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        ByteArrayOutputStream resourceBuffer = new ByteArrayOutputStream();
        OutputStream output = response.getOutputStream();
        try {
            IOUtils.copy(input, resourceBuffer);
            response.setContentLength(resourceBuffer.size());
            resourceBuffer.writeTo(output);
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);
        } finally {
            if (input != null)
                input.close();
            if (output != null)
                output.close();
            if (resourceBuffer != null)
                resourceBuffer.close();
        }
    }
    return null;
}

From source file:de.yaio.services.metaextract.server.controller.MetaExtractController.java

@ExceptionHandler(IOExceptionWithCause.class)
public void handleCustomException(final HttpServletRequest request, final IOExceptionWithCause e,
        final HttpServletResponse response) throws IOException {
    LOGGER.info("IOExceptionWithCause while running request:" + createRequestLogMessage(request), e);
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.getWriter().append("url-get failed while extracting metadata for requested resource:");
    response.getWriter().append(e.getCause().getMessage());
}

From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilterTest.java

/**
 * ?method?/*from   w  w w  . ja  v a  2s .  c om*/
 */
@Test
@Ignore
public void testMethodIsNull() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setCharacterEncoding("UTF-8");

    try {
        request.setMethod("POST");
        request.addParameter("version", "1.0.0");
        filter.doFilter(request, response, null);

        Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_BAD_REQUEST);
        Assert.assertEquals(MainErrorType.MISSING_METHOD.value(), ErrorMsgParser.getErrorCode(response));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:com.atolcd.web.scripts.ZipContents.java

public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {

    String nodes = req.getParameter("nodes");
    if (nodes == null || nodes.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "nodes");
    }/*from  w w w .  ja va2s .  co m*/

    List<String> nodeIds = new ArrayList<String>();
    StringTokenizer tokenizer = new StringTokenizer(nodes, ",");
    if (tokenizer.hasMoreTokens()) {
        while (tokenizer.hasMoreTokens()) {
            nodeIds.add(tokenizer.nextToken());
        }
    }

    String filename = req.getParameter("filename");
    if (filename == null || filename.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "filename");
    }

    String noaccentStr = req.getParameter("noaccent");
    if (noaccentStr == null || noaccentStr.length() == 0) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "noaccent");
    }

    try {
        res.setContentType(MIMETYPE_ZIP);
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + unAccent(filename) + ZIP_EXTENSION + "\"");

        res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "public");
        res.setHeader("Expires", "0");

        createZipFile(nodeIds, res.getOutputStream(), new Boolean(noaccentStr));
    } catch (RuntimeException e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                "Erreur lors de la gnration de l'archive.");
    }
}

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

private void setLike(long id, String user, HttpServletResponse res, boolean isLike) {
    Video v = videos.findOne(id);/*  w  w  w .j ava 2s. c om*/
    int code = HttpServletResponse.SC_OK;
    if (v == null) {
        code = HttpServletResponse.SC_NOT_FOUND;
    } else {
        if (isLike ? v.addLikedUser(user) : v.removeLikedUser(user)) {
            videos.save(v);
        } else {
            code = HttpServletResponse.SC_BAD_REQUEST;
        }
    }
    res.setStatus(code);
}

From source file:contestWebsite.EditRegistration.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets");
    ve.init();//from w  w  w  .  j a v a  2s. c  o m
    VelocityContext context = new VelocityContext();
    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    if (loggedIn && userCookie.isAdmin()) {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Key key = KeyFactory.createKey("registration", Long.parseLong(req.getParameter("key")));
        try {
            Entity registration = datastore.get(key);
            Map<String, Object> props = registration.getProperties();

            String[] propNames = { "schoolName", "name", "email", "paid", "classification", "studentData",
                    "schoolLevel" };
            for (String propName : propNames) {
                context.put(propName, props.get(propName));
            }

            context.put("account", "yes".equals(props.get("account")));
            context.put("studentData", ((Text) props.get("studentData")).getValue());
            context.put("coach".equals(props.get("registrationType")) ? "coach" : "student", true);

            Entity contestInfo = infoAndCookie.x;
            context.put("price", contestInfo.getProperty("price"));
            context.put("key", key);
            context.put("levels", contestInfo.getProperty("levels"));
            context.put("Level", Level.class);

            close(context, ve.getTemplate("editRegistration.html"), resp);
        } catch (EntityNotFoundException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Invalid registration entity key " + key.toString());
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * Get a resource based of the requested URI.
 * If the parameter file is set, it will be used to retrieve the content of the file.
 * /*w w  w. j a  v a  2s. c  o m*/
 * @param req
 * @param resp
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    // Get the uri of the resource
    String uri = restUtils.extractRepositoryUri(req.getPathInfo());
    if (!validParameters(req.getParameterMap().keySet())) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "request contains unsupported parameters");
    }

    // by default get the root...
    if (uri == null || uri.length() == 0)
        uri = "/";

    // get the resources....
    // Add all the options...
    Map<String, Object> options = new HashMap<String, Object>();

    // This options allow to get the informations about an input control
    // including the data to fill the input control....
    if (req.getParameter(Argument.IC_GET_QUERY_DATA) != null) {
        options.put(Argument.IC_GET_QUERY_DATA, req.getParameter(Argument.IC_GET_QUERY_DATA));

        // Extract parameters
        Map<String, Object> parameters = restUtils.extractParameters(req);

        // Add the parsed parameters to the options map (only if it makes sense)
        if (parameters.size() > 0) {
            options.put(Argument.PARAMS_ARG, parameters);
        }
    }

    options.put(restUtils.SWITCH_PARAM_GET_LOCAL_RESOURCE,
            restUtils.isLocalResource(uri) && req.getParameterMap().containsKey(restUtils.FILE_DATA));
    if (log.isDebugEnabled()) {
        log.debug("adding the local resource with data flag");
    }

    ResourceDescriptor rd = null;
    try {
        rd = resourcesManagementRemoteService.getResource(uri, options);
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex.getMessage());
    }

    // This check should not be useful, since an execption should have been thrown by service.getReporse
    if (rd == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find resource: " + uri);
        }
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "Could not find resource: " + uri);
    }

    // If the client specified a specific file, return the file
    if (Boolean.parseBoolean(req.getParameter(restUtils.FILE_DATA))) {
        if (runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()),
                    resp);
        else if (runReportService.getReportAttachments(rd.getUriString())
                .get(FileResourceHandler.MAIN_ATTACHMENT_ID) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString())
                    .get(FileResourceHandler.MAIN_ATTACHMENT_ID), resp);
        return;

    } else // else return the resource descriptor
    {

        Marshaller m = new Marshaller();
        String xml = m.writeResourceDescriptor(rd);

        resp.setContentType("text/xml");
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, xml);
    }
    return;
}