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:edu.harvard.i2b2.fhirserver.ws.OAuth2TokenEndpoint.java

@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public Response authorize(@Context HttpServletRequest request) throws OAuthSystemException, IOException {

    try {/*  w w w  . ja va  2 s  .c o  m*/
        logger.info("got url:" + request.getRequestURL());

        Enumeration<String> kl = request.getParameterNames();
        while (kl.hasMoreElements()) {
            String k = kl.nextElement();
            logger.debug(k + "->" + request.getParameter(k));
        }

        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

        // find if AuthToken was issued, from db
        String authCode = oauthRequest.getCode();
        AuthToken authToken = authTokenBean.find(authCode);
        if (authToken == null) {
            logger.debug("authToken is not found");

            return buildBadAuthCodeResponse();
        }
        logger.debug("authToken is " + authToken.toString());

        // check if clientid is valid
        if (!checkClientId(oauthRequest.getClientId())) {
            return buildInvalidClientIdResponse();
        }

        // check if client_secret is valid
        if (!checkClientSecret(oauthRequest.getClientSecret())) {
            return buildInvalidClientSecretResponse();
        }

        // do checking for different grant types
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!checkAuthCode(authToken, oauthRequest.getParam(OAuth.OAUTH_CODE))) {
                return buildBadAuthCodeResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPass(oauthRequest.getUsername(), oauthRequest.getPassword(), authToken)) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            // refresh token is not supported in this implementation
            // buildInvalidUserPassResponse();
            //buildAccessTokenNotSupportedResponse();
        }

        final String accessTokenString = oauthIssuerImpl.accessToken();
        // database.addToken(accessToken);
        String resourceUserId = authToken.getResourceUserId();
        String i2b2Token = authToken.getI2b2Token();
        String i2b2Project = authToken.getI2b2Project();
        String clientId = authToken.getClientId();
        String scope = authToken.getScope();

        accessTokenBean.createAccessTokenAndDeleteAuthToken(authCode, accessTokenString, resourceUserId,
                i2b2Token, i2b2Project, clientId, scope);

        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessTokenString).setExpiresIn("3600").buildJSONMessage();
        logger.info("returning res:" + response.getBody());

        return Response.status(response.getResponseStatus()).entity(response.getBody()).build();

    } catch (OAuthProblemException e) {
        logger.error(e.getMessage(), e);
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return Response.status(res.getResponseStatus()).entity(res.getBody()).build();
    }
}

From source file:org.mypackage.spring.controllers.EmailsSpringController.java

@RequestMapping(value = "/contacts/{id}/modify/delete_email/{emailId}", method = RequestMethod.GET)
public ModelAndView getDeleteEmail(@PathVariable String id, @PathVariable String emailId) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(id);//from  w w  w  .ja v  a2  s  .  c o  m
    try {
        this.deleteEmailController.deleteEmail(emailId);
        modelAndView.setViewName("/contacts/" + id + "/modify");
    } catch (DalException ex) {
        logger.error("A database error occured while trying to delete contact with ID = " + id, ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "There was a an internal database error.");
        modelAndView.setViewName("/errorPage.jsp");
    } catch (MalformedIdentifierException ex) {
        modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST);
        modelAndView.addObject("errorMessage",
                "An error occured because of a malformed id. Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    }
    return modelAndView;
}

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

@RequestMapping(value = Routes.ROOT_ELECTRIC_POWER_QUALITY_SUMMARY_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/*from w w  w .  j a v  a  2s . 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 {
        ElectricPowerQualitySummary electricPowerQualitySummary = this.electricPowerQualitySummaryService
                .importResource(stream);
        exportService.exportElectricPowerQualitySummary_Root(subscriptionId,
                electricPowerQualitySummary.getId(), response.getOutputStream(), new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter(ACTION_PARAM_NAME);

    if (action.equals(ACTION_LIST_VALUE)) {
        GregorianCalendar cal = new GregorianCalendar();

        File[] files = destinationDir.listFiles();
        Arrays.<File>sort(files, FILE_SORTER);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType(CONTENT_TYPE_PLAIN);

        PrintWriter writer = resp.getWriter();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].getName().endsWith(".jar")) {
                continue;
            }/* www.  j a va  2  s .c o  m*/

            cal.setTimeInMillis(files[i].lastModified());
            writer.println(files[i].getName() + '\t' + (cal.get(GregorianCalendar.MONTH) + 1) + '/'
                    + cal.get(GregorianCalendar.DAY_OF_MONTH) + '/' + cal.get(GregorianCalendar.YEAR) + ' '
                    + cal.get(GregorianCalendar.HOUR_OF_DAY) + ':' + cal.get(GregorianCalendar.MINUTE) + ':'
                    + cal.get(GregorianCalendar.SECOND));
        }
    } else if (action.equals(ACTION_DELETE_VALUE)) {
        String filename = req.getParameter(FILENAME_PARAM_NAME);

        if (filename == null || filename.length() == 0) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            File f = new File(destinationDir, filename);
            if (!f.exists() || f.isDirectory()) {
                resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
            f.delete();
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

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

    String repositoryPath = null;
    final OutputStream out = response.getOutputStream();
    try {/*  ww  w .j  a  va 2  s .c  o  m*/
        repositoryPath = extractRepositoryPath(request);
        IEntity entity = getEntity(repositoryPath, request);
        if (entity == null) {
            doPost(request, response);
        } else {
            if (entity instanceof IResource) {
                ByteArrayOutputStream buff = new ByteArrayOutputStream();
                IOUtils.copy(request.getInputStream(), buff);
                byte[] data = buff.toByteArray();
                IResource resource = (IResource) entity;
                resource.setContent(data);
            } else {
                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:eu.earthobservatory.org.StrabonEndpoint.DescribeBean.java

/**
 * Processes the request made from the HTML visual interface of Strabon Endpoint.
 * //  w ww.  j av a  2 s . c om
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
private void processVIEWRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // get the dispatcher for forwarding the rendering of the response
    RequestDispatcher dispatcher = request.getRequestDispatcher("describe.jsp");

    String query = URLDecoder.decode(request.getParameter("query"), "UTF-8");
    String format = request.getParameter("format");
    String handle = request.getParameter("handle");
    RDFFormat rdfFormat = RDFFormat.valueOf(format);

    if (format == null || query == null || rdfFormat == null) {
        request.setAttribute(ERROR, PARAM_ERROR);
        dispatcher.forward(request, response);

    } else {
        // set the query, format and handle to be selected in the rendered page
        //request.setAttribute("query", URLDecoder.decode(query, "UTF-8"));
        //request.setAttribute("format", URLDecoder.decode(reqFormat, "UTF-8"));
        //request.setAttribute("handle", URLDecoder.decode(handle, "UTF-8"));

        if ("download".equals(handle)) { // download as attachment
            ServletOutputStream out = response.getOutputStream();

            response.setContentType(rdfFormat.getDefaultMIMEType());
            response.setHeader("Content-Disposition", "attachment; filename=results."
                    + rdfFormat.getDefaultFileExtension() + "; " + rdfFormat.getCharset());

            try {
                strabonWrapper.describe(query, format, out);
                response.setStatus(HttpServletResponse.SC_OK);

            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                out.print(ResponseMessages.getXMLHeader());
                out.print(ResponseMessages.getXMLException(e.getMessage()));
                out.print(ResponseMessages.getXMLFooter());
            }

            out.flush();

        } else //plain
        {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                strabonWrapper.describe(query, format, bos);

                request.setAttribute(RESPONSE, StringEscapeUtils.escapeHtml(bos.toString()));

            } catch (Exception e) {
                request.setAttribute(ERROR, e.getMessage());
            }
            dispatcher.forward(request, response);
        }
    }
}

From source file:com.zimbra.cs.service.admin.StatsImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;//from  w  w w  . java2 s .  c o m

    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;

    String serverAddr = "";

    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {

        //check if this is the logger host, otherwise proxy the request to the logger host 
        String serviceHostname = Provisioning.getInstance().getLocalServer()
                .getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);

            // create an HTTP client with the same cookies
            HttpState state = new HttpState();
            try {
                state.addCookie(new org.apache.commons.httpclient.Cookie(logHost,
                        ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false));
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            client.setState(state);
            GetMethod get = new GetMethod(url.toString());
            try {
                int statusCode = HttpClientUtil.executeMethod(client, get);
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null);

                resp.setContentType("image/gif");
                ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } catch (IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } finally {
                get.releaseConnection();
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {

        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");

        String reqParts[] = reqPath.split("/");

        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {//unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);

            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();

        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}

From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java

@RequestMapping(value = "/autoCompleteProjects", method = RequestMethod.GET)
protected void autoCompleteProjects(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {

    //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need!
    //they could check over there if the schema matches what they are querying for and so i can do this generically!
    //user should be logged in so I will log in as that user.
    String name = params.get("name") != null ? params.get("name") : "";
    boolean isValid = false;
    System.out.println("Name is: " + name);
    if (!name.equals("")) {
        isValid = true;//from w  ww .  j  a  v  a2s  . c  om
    }

    if (isValid) {
        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        //TODO: we need to have an authentication token at some point

        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;

        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);

        clothoObject.login(loginMap);
        Map query = new HashMap();

        query.put("query", name); // the value for which we are querying.
        query.put("key", "name"); // the key of the object we are querying

        List<Project> projects = ClothoAdapter.queryProject(query, clothoObject,
                ClothoAdapter.QueryMode.STARTSWITH);
        org.json.JSONArray responseArray = new org.json.JSONArray();
        for (Project proj : projects) {
            JSONObject obj = new JSONObject();
            obj.put("id", proj.getId());
            obj.put("name", proj.getName());
            responseArray.put(obj);
        }

        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(responseArray);
        out.flush();
        out.close();

        clothoObject.logout();
        conn.closeConnection();

    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.setContentType("application/json");
    JSONObject reply = new JSONObject();
    reply.put("message", "Auto Complete requires a query parameter");
    PrintWriter out = response.getWriter();
    out.print(reply);
    out.flush();
    out.close();
}

From source file:fr.smile.alfresco.module.panier.scripts.SmilePanierExportZipWebScript.java

@Override
public void execute(WebScriptRequest request, WebScriptResponse res) throws IOException {

    String userName = AuthenticationUtil.getFullyAuthenticatedUser();

    PersonService personService = services.getPersonService();

    NodeRef userNodeRef = personService.getPerson(userName);

    MimetypeService mimetypeService = services.getMimetypeService();
    FileFolderService fileFolderService = services.getFileFolderService();

    Charset archiveEncoding = Charset.forName("ISO-8859-1");

    String encoding = request.getParameter("encoding");

    if (StringUtils.isNotEmpty(encoding)) {
        archiveEncoding = Charset.forName(encoding);
    }//ww w.ja  v a 2s .c  o m

    ZipOutputStream fileZip = new ZipOutputStream(res.getOutputStream(), archiveEncoding);
    String folderName = "mon_panier";
    try {

        String zipFileExtension = "." + mimetypeService.getExtension(MimetypeMap.MIMETYPE_ZIP);

        res.setContentType(MimetypeMap.MIMETYPE_ZIP);

        res.setHeader("Content-Transfer-Encoding", "binary");
        res.addHeader("Content-Disposition",
                "attachment;filename=\"" + normalizeZipFileName(folderName) + zipFileExtension + "\"");

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

        fileZip.setMethod(ZipOutputStream.DEFLATED);
        fileZip.setLevel(Deflater.BEST_COMPRESSION);

        String archiveRootPath = folderName + "/";

        List<NodeRef> list = smilePanierService.getSelection(userNodeRef);
        List<FileInfo> filesInfos = new ArrayList<FileInfo>();
        for (int i = 0; i < list.size(); i++) {
            FileInfo fileInfo = fileFolderService.getFileInfo(list.get(i));
            filesInfos.add(fileInfo);
        }

        for (FileInfo file : filesInfos) {
            addEntry(file, fileZip, archiveRootPath);
        }
        fileZip.closeEntry();

    } catch (Exception e) {
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Erreur exportation Zip", e);
    } finally {
        fileZip.close();
    }

}

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

@RequestMapping(value = "/entidadbancaria/{identidadbancaria}", method = RequestMethod.DELETE, produces = "application/json")
public void delete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @PathVariable("identidadbancaria") int identidadbancaria) {
    try {// w ww  . j  av  a 2 s  .c om
        boolean deleteSeguro;
        deleteSeguro = entidadBancariaService.delete(identidadbancaria);

        if (deleteSeguro == true) {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        } else {
            httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}