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.springinpractice.ch11.web.controller.application.ApplicationModuleController.java

/**
 * @param id application ID/*from ww  w .  j  a v a2s . co  m*/
 * @param module
 * @param result
 * @param model
 * @param response
 * @return
 */
@RequestMapping(value = "/{id}/modules", method = RequestMethod.POST)
public String createModule(@PathVariable Long id, @ModelAttribute @Valid Module module, BindingResult result,
        Model model, HttpServletResponse response) {

    log.debug("Creating module: {}", module);

    applicationService.addModule(id, module, result);

    if (result.hasErrors()) {
        log.debug("Invalid module");
        model.addAttribute(new Application(id));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "createApplicationModuleForm";
    }

    return null;
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateTLSClientAuthenticationFilter.java

@Override
public void preAuthenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateTLSClientAuthenticationFilter.preAuthenticate is called");

    Validate.notNull(t);/*from  w  w  w  .  ja  v a2 s  .co m*/
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);

    // then check if required auth header is present
    if (request.getParameter(Shared.REQUEST_AUTH_PARAM) == null) {
        // authentication not possible
        log.debug(Shared.REQUEST_AUTH_PARAM + " is missing, requesting " + Shared.TLSCLIENT_AUTH_PREFIX);
        t.setWwwAuthenticate(Shared.TLSCLIENT_AUTH_PREFIX);
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, WebSSOError.BAD_REQUEST,
                null);
        t.setValidationResult(vr);
        throw new SamlServiceException();
    }

    // check if logout cookie is present
    Cookie[] cookies = request.getCookies();
    String logoutCookieName = Shared.getLogoutCookieName(accessor.getTenant());
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase(logoutCookieName)) {
                ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST,
                        WebSSOError.UNAUTHORIZED, WebSSOError.LOGGED_OUT_TLS_SESSION);
                t.setValidationResult(vr);
                throw new SamlServiceException();
            }
        }
    }
}

From source file:com.haulmont.cuba.core.controllers.FileUploadController.java

private FileDescriptor getFileDescriptor(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    FileDescriptor fd;//from   w  w  w .ja va2 s  .co  m
    try {
        fd = FileDescriptor.fromUrlParam(request.getParameter("f"));
    } catch (Exception e) {
        log.error("Error parsing FileDescriptor from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    return fd;
}

From source file:com.sap.dirigible.runtime.registry.RepositoryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String repositoryPath = null;
    final OutputStream out = response.getOutputStream();
    try {/*from   w  ww.  j  av a 2  s  .c o m*/
        repositoryPath = extractRepositoryPath(request);
        IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity == null) {
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            IOUtils.copy(request.getInputStream(), buff);
            data = buff.toByteArray();
            String contentType = request.getContentType();
            if (contentType == null) {
                contentType = "text/plain"; //$NON-NLS-1$
            }
            boolean isBinary = ContentTypeHelper.isBinary(contentType);
            getRepository(request).createResource(repositoryPath, data, isBinary, contentType);
        } else {
            if (entity instanceof IResource) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_RESOURCE_AT_THE_SAME_LOCATION_USE_PUT_METHOD_FOR_UPDATE);
            } else if (entity instanceof ICollection) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        THERE_IS_AN_EXISTING_COLLECTION_AT_THE_SAME_LOCATION);
            }
        }
    } catch (IllegalArgumentException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (MissingResourceException ex) {
        logger.error(String.format(REQUEST_PROCESSING_FAILED_S, repositoryPath) + ex.getMessage());
        response.sendError(HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }

}

From source file:com.example.cloud.bigtable.helloworld.JsonServlet.java

/**
 * doGet() - for a given row, put all values into a simple JSON request.
 * (basically a simple map<key,v>)
 *
 * Column Family CF1 is well known, so we don't mention it in the JSON output, any additional
 * families will be encoded as family:col, which is valid JSON, but not valid javascript.
 *
 * This is fairly simple code, so if there is a column with invalid syntax for JSON, there will be
 * an error./*  w ww  .j av  a2  s. c  om*/
 * Bigtable (and hbase) fields are basically blobs, so I've chosen to recognize a few "datatypes"
 * bool is defined as 1 byte (either 0x00 / 0x01) for (false / true)
 * counter (long) 64 bits 8 bytes and the first 4 bytes are either 0 or -128
 * doubles we will keep as text in Bigtable / hbase
 **/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();
    String key;
    JSONObject json = new JSONObject();
    if (path.length() < 5) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        log("doGet-bad length-" + path.length());
        return;
    }

    // IMPORTANT - This try() is a java7 try w/ resources which will close() the table at the end.
    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {

        Get g = new Get(Bytes.toBytes(path.substring(1)));
        g.setMaxVersions(1);
        Result r = t.get(g);
        log(r.toString());
        NavigableMap<byte[], NavigableMap<byte[], byte[]>> map = r.getNoVersionMap();

        if (map == null) {
            resp.setContentType("application/json");
            resp.getWriter().print("{}");
            return;
        }
        // For Every Family
        for (Map.Entry<byte[], NavigableMap<byte[], byte[]>> family : map.entrySet()) {
            String cFamily = Bytes.toString(family.getKey());
            // Each column
            for (Map.Entry<byte[], byte[]> entry : family.getValue().entrySet()) {
                String col = Bytes.toString(entry.getKey());
                byte[] val = entry.getValue();
                if (cFamily.equals(cf1)) {
                    key = col;
                } else {
                    key = cFamily + ":" + col;
                }
                // Based on data type, create the json.  8 bytes (leading 0) is an int (counter)
                // 1 byte (0/1) = (false/true) else string
                switch (val.length) {
                case 8:
                    if ((val[0] == 0 && val[1] == 0 && val[2] == 0 && val[3] == 0)
                            || (val[0] == -1 && val[1] == -1 && val[2] == -1 && val[3] == -1)) {
                        json.put(key, Bytes.toLong(val));
                    } else {
                        String temp = Bytes.toString(val);
                        if (isNumeric(temp)) {
                            if (isDigits(temp)) {
                                json.put(key, Long.parseLong(temp));
                            } else {
                                json.put(key, Double.parseDouble(temp));
                            }
                        } else {
                            json.put(key, temp);
                        }
                    }
                    break;
                case 1:
                    switch (val[0]) {
                    case 0:
                        json.put(key, false);
                        continue;
                    case 1:
                        json.put(key, true);
                        continue;
                    default:
                    }
                default:
                    String temp = Bytes.toString(val);
                    if (isNumeric(temp)) {
                        if (isDigits(temp)) {
                            json.put(key, Long.parseLong(temp));
                        } else {
                            json.put(key, Double.parseDouble(temp));
                        }
                    } else {
                        json.put(key, temp);
                    }
                }
            }
        }
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("application/json");
        json.write(resp.getWriter());
    } catch (Exception e) {
        log("doGet", e);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:fr.itldev.koya.webscript.content.ZipContent.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    Map<String, Object> jsonPostMap = KoyaWebscript.getJsonMap(req);

    ArrayList<String> nodeRefs = new ArrayList<>();
    JSONArray jsonArray = (JSONArray) jsonPostMap.get(ARG_NODEREFS);
    if (jsonArray != null) {
        int len = jsonArray.size();
        for (int i = 0; i < len; i++) {
            nodeRefs.add(jsonArray.get(i).toString());
        }/*from   w ww.  j av a  2 s. c om*/
    }

    try {
        res.setContentType(MIMETYPE_ZIP);
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition", "attachment");

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

        File tmpZipFile = koyaContentService.zip(nodeRefs);

        OutputStream outputStream = res.getOutputStream();
        if (nodeRefs.size() > 0) {
            InputStream in = new FileInputStream(tmpZipFile);
            try {
                byte[] buffer = new byte[8192];
                int len;

                while ((len = in.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    } catch (KoyaServiceException ex) {
        throw new WebScriptException("KoyaError : " + ex.getErrorCode().toString());
    } catch (RuntimeException e) {
        /**
         * TODO koya specific exception
         */
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST,
                "Erreur lors de la gnration de l'archive.", e);
    }

}

From source file:org.bedework.webcommon.location.FetchLocationsAction.java

@Override
public int doAction(final BwRequest request, final BwActionFormBase form) throws Throwable {
    if (debug) {/*from w w  w .j av a2s.co m*/
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    }

    final DateFormat df = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");

    mapper.setDateFormat(df);

    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    final Client cl = request.getClient();
    form.setNocache(false);
    final String changeToken = cl.getCurrentChangeToken();

    final String ifNoneMatch = request.getRequest().getHeader("if-none-match");

    if ((changeToken != null) && changeToken.equals(ifNoneMatch)) {
        request.getResponse().setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return forwardNull;
    }

    /* Add an etag */
    request.getResponse().addHeader("etag", changeToken);

    final BwSession sess = request.getSess();

    final Collection<BwLocation> vals;
    final String attrName;

    final String kind = request.getReqPar("kind", "owners");

    switch (kind) {
    case "owners":
        attrName = BwRequest.bwLocationsListName;
        vals = sess.getLocations(request, BwSession.ownersEntity, true);
        break;
    case "editable":
        attrName = BwRequest.bwEditableLocationsListName;

        vals = sess.getLocations(request, BwSession.editableEntity, false);
        //    } else if (kind.equals("preferred")) {
        //      attrName = BwRequest.bwPreferredLocationsListName;
        //
        //      vals = curAuthUserPrefs.getLocationPrefs().getPreferred();
        break;
    default:
        request.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return forwardNull;
    }

    request.getResponse().setContentType("text/json; charset=UTF-8");

    writeJson(request.getResponse(), vals);
    request.getResponse().getOutputStream().close();

    return forwardNull;
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.servlet.ConfigServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    LOGGER.trace("doPost : Setting MMX Configuration");
    response.setContentType(CONTENT_TYPE_JSON);
    PrintWriter out = response.getWriter();

    String postBody = PushServlet.getRequestBody(req);

    if (postBody != null && !postBody.trim().isEmpty()) {
        LOGGER.trace("doPost : Received Configuration : {}", postBody);
        SerializableConfig config = GsonData.getGson().fromJson(postBody, SerializableConfig.class);

        MMXConfiguration configuration = MMXConfiguration.getConfiguration();
        Set<String> keys = config.configs.keySet();
        for (String key : keys) {
            //set the value for this configuration
            // see if this is an XMPP configuration
            if (MMXConfiguration.isXmppProperty(key)) {
                JiveGlobals.setProperty(key, config.configs.get(key));
            } else {
                configuration.setValue(key, config.configs.get(key));
            }/*from   ww  w.  j a  v a2  s . c o  m*/
        }
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:io.github.gsteckman.rpi_rest.SubscriptionManager.java

/**
 * Processes a UPnP SUBSCRIBE request and creates or renews a subscription.
 * //from   w ww .  j  a v  a  2  s  .c o  m
 * @param key
 *            The key identifies the resource to which this subscription applies.
 * @param req
 *            Subscription request
 * @param res
 *            Response to the subscription request
 * @throws IOException
 *             Thrown by HttpServletResponse.sendError if an error occurs writing the response.
 */
public void processSubscribe(String key, HttpServletRequest req, HttpServletResponse res) throws IOException {
    String timeoutHdr = req.getHeader("TIMEOUT");
    String callbackHdr = req.getHeader("CALLBACK");
    String sidHdr = req.getHeader("SID");
    List<URL> callbackUrls = new LinkedList<URL>();

    // Perform error checking:
    // 1. Method must be SUBSCRIBE
    // 2. If no SID header
    // a. CALLBACK header must be present & properly formatted as a correct URL
    // b. NT header must be present with a value of "upnp:event"
    // 3. If there is a SID header, CALLBACK and NT headers not present
    if (!"SUBSCRIBE".equalsIgnoreCase(req.getMethod())) {
        // Return 405 status
        res.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                "Method " + req.getMethod() + " not allowed for this resource.");
        return;
    }

    if (sidHdr != null && (timeoutHdr != null || callbackHdr != null)) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "An SID header field and one of NT or CALLBACK header fields are present.");
        return;
    } else {
        if (callbackHdr == null) {
            // CALLBACK is a required header. Return status 412
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "CALLBACK header is missing.");
            return;
        } else {
            // parse callback header and ensure proper format
            callbackUrls = parseCallbackHeader(callbackHdr);
            if (callbackUrls.size() == 0) {
                res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                        "CALLBACK header doesn't contain a valid HTTP URL.");
                return;
            }
        }

        if (!"upnp:event".equals(req.getHeader("NT"))) {
            // NT is a required header. Return status 412
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                    "NT header field does not equal upnp:event.");
            return;
        }
    }

    // parse timeout header
    long timeout = DEFAULT_TIMEOUT;
    try {
        timeout = Long.parseLong(timeoutHdr.substring(7)) * 1000;
    } catch (NumberFormatException e) {
        // ignore, use default
        LOG.info("Using default timeout", e);
    }

    // check if new subscription or a renewal
    if (sidHdr != null) { // subscription renewal
        Map<UUID, SubscriptionInfo> m = subscriptions.get(key);
        if (m == null) {
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                    "SID doesn't correspond to a known subscription.");
            return;
        }

        // parse SID
        String ss = sidHdr.substring(5).trim();
        UUID sid = new UUID(ss);

        SubscriptionInfo si = m.get(sid);
        if (si == null) {
            res.sendError(HttpServletResponse.SC_PRECONDITION_FAILED,
                    "SID doesn't correspond to a known subscription.");
            return;
        }

        si.renew(timeout);
    } else { // new subscription

        // create subscription identifier
        UUID sid = new UUID();

        addSubscription(key, sid, new SubscriptionInfo(sid, timeout, callbackUrls));

        // Create response
        res.setStatus(HttpServletResponse.SC_OK);
        res.addHeader("SERVER", System.getProperty("os.name") + "/" + System.getProperty("os.version")
                + ", UPnP/1.1, rpi-rest/0.1");
        res.addHeader("SID", "uuid:" + sid.toString());
        res.addHeader("TIMEOUT", "Second-" + (timeout / 1000));
    }
}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {//from   ww w.j a  v a  2s. com
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}