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.obiba.shiro.web.filter.AuthenticationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (ThreadContext.getSubject() != null) {
        log.warn("Previous executing subject was not properly unbound from executing thread. Unbinding now.");
        ThreadContext.unbindSubject();/*from ww w .  j av a2 s .c  o  m*/
    }

    try {
        authenticateAndBind(request);
        filterChain.doFilter(request, response);
    } catch (AuthenticationException e) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        log.error("Exception", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().println(e.getMessage());
    } finally {
        unbind();
    }
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);//from  w w w.ja v  a 2s.  c o  m

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:com.moss.appkeep.server.HttpPublisher.java

public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws java.io.IOException, javax.servlet.ServletException {
    ComponentRequest cr = parse(request);

    if (cr != null) {
        final StoredComponent c = data.components.get(cr.componentId, null, LockMode.DEFAULT);

        if (c == null) {
            completeWithError("No such component:" + cr.componentId, HttpServletResponse.SC_BAD_REQUEST,
                    response);/* w  w w  . j  av a2  s  .c  o  m*/
        }

        if (c.type() != cr.componentType) {
            completeWithError("Invalid type for component: " + cr.componentType,
                    HttpServletResponse.SC_BAD_REQUEST, response);
        }

        if (!c.isPublic()) {
            completeWithError(
                    "ACCESS DENIED: component " + cr.componentId + " is not configured for public access",
                    HttpServletResponse.SC_FORBIDDEN, response);
            return;
        }

        OutputStream out = response.getOutputStream();

        // FIND THE COMPONENT
        InputStream i = tool.getComponent(c, cr.endorsements);

        // WRITE THE DATA TO THE CLIENT
        try {
            byte[] buf = new byte[1024 * 100];
            for (int x = i.read(buf); x != -1; x = i.read(buf)) {
                out.write(buf, 0, x);
            }

            out.close();
        } finally {
            i.close();
        }
    }
}

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

@RequestMapping(value = Routes.ROOT_AUTHORIZATION_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//ww w  . ja v  a 2s  . c o m
public void show(HttpServletResponse response, @PathVariable Long authorizationId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        exportService.exportAuthorization(authorizationId, response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.starit.diamond.server.controller.ConfigController.java

/**
 * ???/*from   w  ww.j a va  2s.c o  m*/
 * 
 * @param request
 * @param dataId
 * @param clientGroup
 *            ?
 * @return
 */
@RequestMapping(method = RequestMethod.POST)
public String getProbeModifyResult(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(Constants.PROBE_MODIFY_REQUEST) String probeModify) {
    String version = request.getHeader(Constants.CLIENT_VERSION_HEADER);
    if (version == null) {
        version = "3.0.0";
    }
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";

    }

    final List<ConfigKey> configKeyList = getConfigKeyList(probeModify);

    StringBuilder resultBuilder = new StringBuilder();
    StringBuilder newResultBuilder = new StringBuilder();
    int index = 0;
    for (ConfigKey key : configKeyList) {
        String md5 = this.configService.getContentMD5(key.getDataId(), key.getGroup());
        if (md5 != null) {
            if (!md5.equals(key.getMd5())) {
                resultBuilder.append(key.getDataId()).append(":").append(key.getGroup()).append(";");
                newResultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                        .append(Constants.LINE_SEPARATOR);
                index++;
            }
        } else {
            if (key.getMd5() != null) {
                resultBuilder.append(key.getDataId()).append(":").append(key.getGroup()).append(";");
                newResultBuilder.append(key.getDataId()).append(Constants.WORD_SEPARATOR).append(key.getGroup())
                        .append(Constants.LINE_SEPARATOR);
                index++;
            }
        }

    }

    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");

    int versionNum = 0;
    if (index > 0) {
        versionNum = Protocol.getVersionNumber(version);
    } else {
        versionNum = -1;
    }
    String returnHeader = newResultBuilder.toString();
    try {
        returnHeader = URLEncoder.encode(newResultBuilder.toString(), "UTF-8");
    } catch (Exception e) {
    }
    if (versionNum >= 204) {
        request.setAttribute("content", returnHeader);
    } else if (versionNum >= 0) {
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE_NEW, returnHeader);
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE, resultBuilder.toString());// ?1.0
    } else {
        request.setAttribute("content", "");
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE_NEW, "");
        response.addHeader(Constants.PROBE_MODIFY_RESPONSE, "");
    }
    return "200";
}

From source file:net.longfalcon.web.WebExceptionHandlerResolver.java

/**
 * Handle the case where an {@linkplain ModelAttribute @ModelAttribute} method
 * argument has binding or validation errors and is not followed by another
 * method argument of type {@link BindingResult}.
 * By default an HTTP 400 error is sent back to the client.
 * @param request current HTTP request/*from  w  w w .j a  v a  2  s.  co m*/
 * @param response current HTTP response
 * @param handler the executed handler
 * @return an empty ModelAndView indicating the exception was handled
 * @throws IOException potentially thrown from response.sendError()
 */
protected ModelAndView handleBindException(BindException ex, HttpServletRequest request,
        HttpServletResponse response, Object handler) throws IOException {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    _log.error(ex, ex);
    return new ModelAndView();
}

From source file:com.wso2telco.premiuminfo.PremiumInfoEndpoint.java

/**
 * Build the error message response properly
 *
 * @param e/*from   ww w .  j  a  va  2 s.  co m*/
 * @return
 * @throws OAuthSystemException
 */
private Response handleError(UserInfoEndpointException e) throws OAuthSystemException {
    log.debug(e);
    OAuthResponse res = null;
    try {
        res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).setError(e.getErrorCode())
                .setErrorDescription(e.getErrorMessage()).buildJSONMessage();
    } catch (OAuthSystemException e1) {
        log.error("OAuthSystemException Exception occurred : ", e1);
        res = OAuthASResponse.errorResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
                .setError(OAuth2ErrorCodes.SERVER_ERROR).setErrorDescription(e1.getMessage())
                .buildJSONMessage();
    }
    return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
}

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

@RequestMapping(value = Routes.ROOT_READING_TYPE_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody//from   ww  w. j a  v  a  2 s. co m
public void update(HttpServletResponse response, @PathVariable Long readingTypeId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException {
    ReadingType existingReadingType = readingTypeService.findById(readingTypeId);

    if (existingReadingType != null) {
        try {

            readingTypeService.importResource(stream);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

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

@RequestMapping(value = {
        "/usuario" }, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public void insert(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada) {
    try {/* w ww  . jav a 2  s .  co  m*/
        Usuario usuario = (Usuario) jsonTransformer.fromJsonToObject(jsonEntrada, Usuario.class);
        if (usuario == null) {
            throw new BusinessException("Campo", "Debe rellenar los datos");
        }

        if (!passwordManager.checkComplexity(usuario.getPassword()) || usuario.getPassword().isEmpty()) {
            throw new BusinessException("Password",
                    "La contrasea debe contener Minusculas, Maysculas, Dgitos y de 6-20 caractres");
        }

        usuario.setPassword(passwordManager.encrypt(usuario.getPassword()));

        usuarioService.insert(usuario);

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

    } 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:eionet.transfer.controller.FileOpsController.java

/**
 * AJAX Upload file for transfer./*from  ww  w  . j av  a  2 s .  c o m*/
 */
@RequestMapping(value = "/fileupload", method = RequestMethod.POST, params = "ajaxupload=1")
public void importFileWithAJAX(@RequestParam("file") MultipartFile myFile, @RequestParam("fileTTL") int fileTTL,
        HttpServletRequest request, HttpServletResponse response) throws IOException {

    if (myFile == null || myFile.getOriginalFilename() == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Select a file to upload");
        return;
    }
    if (fileTTL > 90) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid expiration date");
        return;
    }
    String uuidName = storeFile(myFile, fileTTL);
    response.setContentType("text/xml");
    PrintWriter printer = response.getWriter();
    StringBuffer requestUrl = request.getRequestURL();
    String url = requestUrl.substring(0, requestUrl.length() - "/fileupload".length());
    printer.println("<?xml version='1.0'?>");
    printer.println("<package>");
    printer.println("<downloadLink>" + url + "/download/" + uuidName + "</downloadLink>");
    printer.println("<deleteLink>" + url + "/delete/" + uuidName + "</deleteLink>");
    printer.println("</package>");
    printer.flush();
    response.flushBuffer();
}