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.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET,
        RequestMethod.POST })//from   w  ww  . j ava 2s . c o m
public void doExport(@RequestParam("bbox") final String bbox,
        @RequestParam(value = "size", required = false) final String size,
        @RequestParam(value = "layerDefs", required = false) final String layerDefs,
        @RequestParam(value = "transparent", required = false) final String transparent,
        final HttpServletResponse response) throws IOException {
    double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0;
    if (bbox != null && bbox.length() > 0) {
        final String[] tokens = m_patternComma.split(bbox);
        if (tokens.length == 4) {
            xmin = Double.parseDouble(tokens[0]);
            ymin = Double.parseDouble(tokens[1]);
            xmax = Double.parseDouble(tokens[2]);
            ymax = Double.parseDouble(tokens[3]);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "bbox is not in the form xmin,ymin,xmax,ymax");
            return;
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty");
        return;
    }

    final double xdel = xmax - xmin;
    final double ydel = ymax - ymin;

    int imageWidth = 400;
    int imageHeight = 400;
    if (size != null && size.length() > 0) {
        final String[] tokens = m_patternComma.split(size);
        if (tokens.length == 2) {
            imageWidth = Integer.parseInt(tokens[0], 10);
            imageHeight = Integer.parseInt(tokens[1], 10);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height");
            return;
        }
    }
    String where = null;
    double lo = Double.NaN;
    double hi = Double.NaN;
    int[] ramp = null;
    if (layerDefs != null) {
        final String[] tokens = m_patternSemiColon.split(layerDefs);
        for (final String token : tokens) {
            final String[] keyval = m_patternEqual.split(token.substring(2));
            if (keyval.length == 2) {
                final String key = keyval[0];
                final String val = keyval[1];
                if ("lo".equalsIgnoreCase(key)) {
                    lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("hi".equalsIgnoreCase(key)) {
                    hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("ramp".equalsIgnoreCase(key)) {
                    ramp = parseRamp(val);
                } else if ("where".equalsIgnoreCase(key)) {
                    where = val;
                }
            }
        }
    }
    if (ramp == null) {
        ramp = new int[] { 0xFFFFFF, 0x000000 };
    }

    final Range range = new Range();
    final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range);
    if (!Double.isNaN(lo)) {
        range.lo = lo;
    }
    if (!Double.isNaN(hi)) {
        range.hi = hi;
    }
    range.dd = range.hi - range.lo;

    final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB
            : BufferedImage.TYPE_INT_RGB;
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb);
    final Graphics2D graphics = bufferedImage.createGraphics();
    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        graphics.setBackground(new Color(0, 0, 0, 0));

        drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet());
    } finally {
        graphics.dispose();
    }

    // bufferedImage = m_op.filter(bufferedImage, null);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024);
    ImageIO.write(bufferedImage, "PNG", baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("image/png");
    response.setContentLength(baos.size());
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();
}

From source file:uk.ac.ebi.eva.server.ws.RegionWSServer.java

@RequestMapping(value = "/{regionId}/variants", method = RequestMethod.GET)
@ResponseBody/*from   ww  w.  ja  va  2 s  .c  o  m*/
//    @ApiOperation(httpMethod = "GET", value = "Retrieves all the variants from region", response = QueryResponse.class)
public QueryResponse getVariantsByRegion(@PathVariable("regionId") String regionId,
        @RequestParam(name = "species") String species,
        @RequestParam(name = "studies", required = false) String studies,
        @RequestParam(name = "annot-ct", required = false) List<String> consequenceType,
        @RequestParam(name = "maf", defaultValue = "") String maf,
        @RequestParam(name = "polyphen", defaultValue = "") String polyphenScore,
        @RequestParam(name = "sift", defaultValue = "") String siftScore,
        @RequestParam(name = "ref", defaultValue = "") String reference,
        @RequestParam(name = "alt", defaultValue = "") String alternate,
        @RequestParam(name = "miss_alleles", defaultValue = "") String missingAlleles,
        @RequestParam(name = "miss_gts", defaultValue = "") String missingGenotypes,
        @RequestParam(name = "histogram", defaultValue = "false") boolean histogram,
        @RequestParam(name = "histogram_interval", defaultValue = "-1") int interval,
        @RequestParam(name = "merge", defaultValue = "false") boolean merge, HttpServletResponse response)
        throws IllegalOpenCGACredentialsException, IOException {
    initializeQueryOptions();

    VariantDBAdaptor variantMongoDbAdaptor = DBAdaptorConnector.getVariantDBAdaptor(species);

    if (studies != null && !studies.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.STUDIES, studies);
    }

    if (consequenceType != null && !consequenceType.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.ANNOT_CONSEQUENCE_TYPE, consequenceType);
    }

    if (!maf.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.MAF, maf);
    }
    if (!polyphenScore.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.POLYPHEN, polyphenScore);
    }
    if (!siftScore.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.SIFT, siftScore);
    }

    if (!reference.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.REFERENCE, reference);
    }
    if (!alternate.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.ALTERNATE, alternate);
    }

    if (!missingAlleles.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.MISSING_ALLELES, missingAlleles);
    }
    if (!missingGenotypes.isEmpty()) {
        queryOptions.put(VariantDBAdaptor.MISSING_GENOTYPES, missingGenotypes);
    }

    queryOptions.put("merge", merge);
    queryOptions.put("sort", true);

    // Parse the provided regions. The total size of all regions together
    // can't excede 1 million positions
    int regionsSize = 0;
    List<Region> regions = new ArrayList<>();
    for (String s : regionId.split(",")) {
        Region r = Region.parseRegion(s);
        regions.add(r);
        regionsSize += r.getEnd() - r.getStart();
    }

    if (histogram) {
        if (regions.size() != 1) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return setQueryResponse("Sorry, histogram functionality only works with a single region");
        } else {
            if (interval > 0) {
                queryOptions.put("interval", interval);
            }
            return setQueryResponse(
                    variantMongoDbAdaptor.getVariantFrequencyByRegion(regions.get(0), queryOptions));

        }
    } else if (regionsSize <= 1000000) {
        if (regions.isEmpty()) {
            if (!queryOptions.containsKey("id") && !queryOptions.containsKey("gene")) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return setQueryResponse("Some positional filer is needed, like region, gene or id.");
            } else {
                return setQueryResponse(variantMongoDbAdaptor.getAllVariants(queryOptions));
            }
        } else {
            return setQueryResponse(variantMongoDbAdaptor.getAllVariantsByRegionList(regions, queryOptions));
        }
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return setQueryResponse("The total size of all regions provided can't exceed 1 million positions. "
                + "If you want to browse a larger number of positions, please provide the parameter 'histogram=true'");
    }
}

From source file:edu.lternet.pasta.datapackagemanager.dataserver.DataServerServlet.java

/**
 * Process a data download request using information that was generated
 * by the Data Package Manager service.//from ww w  .  j a  v a 2 s  . c o m
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String dataToken = request.getParameter("dataToken");
    String size = request.getParameter("size");
    String objectName = request.getParameter("objectName");

    if (dataToken == null || dataToken.isEmpty() || size == null || size.isEmpty() || objectName == null
            || objectName.isEmpty()) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        /*
         * Find out which directory the temporary data files are being
         * placed in by the Data Package Manager
         */
        PropertiesConfiguration options = ConfigurationListener.getOptions();
        String tmpDir = options.getString("datapackagemanager.tmpDir");

        if (tmpDir == null || tmpDir.equals("")) {
            throw new ServletException("datapackagemanager.tmpDir property value was not specified.");
        }

        logger.info(String.format("Downloading: dataToken: %s; size: %s; objectName: %s", dataToken, size,
                objectName));

        try {
            // reads input file from an absolute path
            String filePath = String.format("%s/%s", tmpDir, dataToken);
            File downloadFile = new File(filePath);
            FileInputStream inStream = new FileInputStream(downloadFile);
            ServletContext context = getServletContext();

            // gets MIME type of the file
            String mimeType = context.getMimeType(filePath);
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            logger.debug("MIME type: " + mimeType);

            // modifies response
            response.setContentType(mimeType);

            long length = Long.parseLong(size);
            if (length <= Integer.MAX_VALUE) {
                response.setContentLength((int) length);
            } else {
                response.addHeader("Content-Length", Long.toString(length));
            }

            // forces download
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"", objectName);
            response.setHeader(headerKey, headerValue);

            // obtains response's output stream
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }

            inStream.close();
            outStream.close();

            /*
             * Delete the temporary data file after it was downloaded
             */
            try {
                downloadFile.delete();
            } catch (Exception e) {
                logger.warn(String.format("Error deleting temporary data file: %s", e.getMessage()));
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }
}

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

@RequestMapping(value = Routes.ROOT_APPLICATION_INFORMATION_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/* www .java 2  s .  c  o  m*/
public void update(HttpServletResponse response, @PathVariable Long applicationInformationId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException, FeedException {
    ApplicationInformation applicationInformation = resourceService.findById(applicationInformationId,
            ApplicationInformation.class);

    if (applicationInformation != null) {
        try {

            ApplicationInformation newApplicationInformation = applicationInformationService
                    .importResource(stream);
            applicationInformation.merge(newApplicationInformation);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

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

@RequestMapping(value = Routes.ROOT_METER_READING_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody// w w  w.  j a v a  2  s. c  o  m
public void create(HttpServletRequest request, HttpServletResponse response,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        MeterReading meterReading = this.meterReadingService.importResource(stream);
        exportService.exportMeterReading_Root(subscriptionId, meterReading.getId(), response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping(value = Routes.ROOT_AUTHORIZATION_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody//  w  w  w  .  jav a  2s .c  o  m
public void create(HttpServletResponse response, @RequestParam Map<String, String> params, InputStream stream)
        throws IOException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        Authorization authorization = this.authorizationService.importResource(stream);
        exportService.exportAuthorization(authorization.getId(), response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:com.pureinfo.tgirls.sns.servlet.SNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("tgirls sns entry.");

    String taobaoUserId = null;/*  w  w w . j av  a2  s  .c  o  m*/
    String taobaoUserName = null;

    String topSession = request.getParameter(APPConstants.REQ_PARAMETER_SESSION);
    String topParameters = request.getParameter(APPConstants.REQ_PARAMETER_PARAMETERS);
    String topSign = request.getParameter(APPConstants.REQ_PARAMETER_SIGN);

    TipBean tb = null;
    try {
        tb = TipUtil.beforeFetch(topSession, topParameters, topSign, APPConstants.SECRET);
        if (!tb.isOk()) {
            logger.error("top api failed." + tb.getErrMsg());

            throw new Exception("TOP API failed:" + tb.getErrMsg());
        }
        taobaoUserId = tb.getUserId() + "";
        taobaoUserName = tb.getUserNick();

        logger.debug("id:" + taobaoUserId);
        logger.debug("name:" + taobaoUserName);
        logger.debug("session:" + topSession);

        if ("0".equals(taobaoUserId) || StringUtils.isEmpty(taobaoUserId)
                || StringUtils.isEmpty(taobaoUserName)) {
            throw new Exception("parameter empty.");
        }
    } catch (Exception e) {
        logger.error("error when call top API.", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "top system error." + e.getMessage());
        return;
    }

    HttpSession session = request.getSession(true);
    session.removeAttribute(ArkHelper.ATTR_LOGIN_USER);
    User loginUser = null;//(User) session.getAttribute(ArkHelper.ATTR_LOGIN_USER);
    //loginUser = CookieUtils.getLoginUser(request, response);

    if (loginUser != null && loginUser.getTaobaoID().equals(taobaoUserId)) {

        logger.debug("user " + taobaoUserId + " already logined.");

    } else {
        try {
            userMgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
            if (!userMgr.isUserExists(taobaoUserId)) {
                loginUser = createUser(taobaoUserId, topSession);
                //ScriptWriteUtils.reBuildUserInfoScript(loginUser);
                try {
                    //ScriptWriteUtils.reBuildUserBuyPhotosScript(loginUser);
                    //ScriptWriteUtils.reBuildUserUploadPhotosScript(loginUser);
                } catch (Exception e) {
                    logger.error("error when rebuild buy and upload scripts.", e);
                }
            } else {
                loginUser = userMgr.getUserByTaobaoId(taobaoUserId);
            }
        } catch (PureException e) {
            logger.error("tgirls system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "tgirls system error." + e.getMessage());
            return;
        } catch (NumberFormatException e) {
            logger.error("number format error.", e);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        } catch (TaobaoApiException e) {
            logger.error("top system error.", e);
            response.sendError(HttpServletResponse.SC_BAD_GATEWAY, "top system error." + e.getMessage());
            return;
        }
    }

    if (loginUser == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "can not find current user.");
        return;
    }

    if (loginUser.getFunds() <= UserConstants.DISUSE_FUNDS
            || loginUser.getAssets() <= UserConstants.DISUSE_ASSETS) {
        response.sendRedirect(request.getContextPath() + "/disable.html");
        return;
    }

    updateUserHeadImg(loginUser, topSession);

    session.setAttribute(ArkHelper.ATTR_LOGIN_USER, loginUser);
    session.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);
    LocalContextHelper.setAttribute(SessionConstants.TAOBAO_SESSION_ID, topSession);

    addCookie(loginUser, request, response);

    //        System.out.println("========================");
    //        
    //        
    //       Cookie[] cs = request.getCookies();
    //        for (int i = 0; i < cs.length; i++) {
    //            Cookie c = cs[i];
    //            System.out.println("cookie[" + c.getName() + "]:" + c.getValue());
    //        }
    //        
    RequestDispatcher rd = request.getRequestDispatcher("/index.html");
    rd.forward(request, response);
    //response.sendRedirect(request.getContextPath());

    return;
}

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

protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {// w w  w.  j a  va2 s  .  c  om
        String userName = restUtils.extractResourceName(req.getPathInfo());

        WSUser user = restUtils.populateServiceObject(restUtils.unmarshal(WSUser.class, req.getInputStream()));
        if (log.isDebugEnabled()) {
            log.debug("un Marshaling OK");
        }

        if (validateUserForPutOrUpdate(user)) {
            if (!isAlreadyAUser(user)) {
                userAndRoleManagementService.putUser(user);
                restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
            } else {
                throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                        "user " + user.getUsername() + "already exists");
            }
        } else
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");

    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }

}

From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java

public void handleClassicRequest(final String jk, final String crypted, final HttpServletResponse resp)
        throws IOException {
    LOG.debug("Configuration: " + drClient.toString());

    try {//from  ww w  .j  av  a 2  s  .  c  o m
        final String key = extractKey(jk);
        final List<URI> targets = Decrypter.decryptDownloadUri(crypted, key);
        final List<URI> fixedTargets = fixURIs(targets);

        LOG.debug("Sending download URLs to Synology NAS. Number of URIs: " + targets.size());
        for (URI target : fixedTargets) {
            drClient.addDownloadUrl(target);
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        analyticsTracker.trackEvent(ANALYTICS_EVENT_CATEGORY, "Classic Request", "added targets",
                targets.size());

    } catch (ScriptException ex) {
        LOG.error(ex.getMessage(), ex);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to evaluate script:\n" + ex.getMessage());

    } catch (SynoException ex) {
        LOG.error(ex.getMessage(), ex);
        if (ex instanceof LoginException) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
        } else {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        }

    } catch (URISyntaxException ex) {
        LOG.error("Decrypted URL seems to be corrupt.", ex);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

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

@RequestMapping(value = "/cuentabancaria/{idCuentaBancaria}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public void update(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @RequestBody String jsonEntrada, @PathVariable("idCuentaBancaria") int idCuentaBancaria) {
    try {/*from  w  w  w.ja va2s  .  co  m*/
        CuentaBancaria cuentaBancaria = (CuentaBancaria) jsonTransformer.fromJsonToObject(jsonEntrada,
                CuentaBancaria.class);
        cuentaBancariaService.update(cuentaBancaria);
        String jsonSalida = jsonTransformer.ObjectToJson(cuentaBancaria);

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

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

        httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        httpServletResponse.setContentType("application/json; charset=UTF-8");
        try {
            httpServletResponse.getWriter().println(jsonSalida);
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaService.class.getName()).log(Level.SEVERE, null, ex1);
        }

    } catch (Exception ex) {
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        httpServletResponse.setContentType("text/plain; charset=UTF-8");
        try {
            ex.printStackTrace(httpServletResponse.getWriter());
        } catch (IOException ex1) {
            Logger.getLogger(CuentaBancariaController.class.getName()).log(Level.SEVERE, null, ex1);
        }
    }
}