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:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;// w w w  .  ja  va2 s  .co m
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}

From source file:com.haulmont.cuba.web.controllers.StaticContentController.java

protected LookupResult lookupNoCache(HttpServletRequest req) {
    final String path = getPath(req);
    if (isForbidden(path))
        return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

    ServletContext context = req.getSession().getServletContext();

    final URL url;
    try {// ww  w. j  ava2s .  c o m
        url = context.getResource(path);
    } catch (MalformedURLException e) {
        return new Error(HttpServletResponse.SC_BAD_REQUEST, "Malformed path");
    }
    if (url == null)
        return new Error(HttpServletResponse.SC_NOT_FOUND, "Not found");

    final String mimeType = getMimeType(path);

    final String realpath = context.getRealPath(path);
    if (realpath != null) {
        // Try as an ordinary file
        File f = new File(realpath);
        if (!f.isFile())
            return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
        else {
            return createLookupResult(req, f.lastModified(), mimeType, (int) f.length(), acceptsDeflate(req),
                    url);
        }
    } else {
        try {
            // Try as a JAR Entry
            final ZipEntry ze = ((JarURLConnection) url.openConnection()).getJarEntry();
            if (ze != null) {
                if (ze.isDirectory())
                    return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
                else
                    return createLookupResult(req, ze.getTime(), mimeType, (int) ze.getSize(),
                            acceptsDeflate(req), url);
            } else
                // Unexpected?
                return new StaticFile(-1, mimeType, -1, acceptsDeflate(req), url);
        } catch (ClassCastException e) {
            // Unknown resource type
            return createLookupResult(req, -1, mimeType, -1, acceptsDeflate(req), url);
        } catch (IOException e) {
            return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}

From source file:com.pymegest.applicationserver.api.PuestoController.java

@RequestMapping(value = { "/Puesto" }, method = RequestMethod.POST)
public void insert(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonInput) {

    try {// ww  w. j  a  va  2s  .  c  o  m

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Puesto puesto = (Puesto) objectMapper.readValue(jsonInput, Puesto.class);

        if (puesto != null) {

            puestoDAO.insert(puesto);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(puesto);
            response.getWriter().println(jsonOutput);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("Imposible insertar un puesto.");

            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

From source file:edu.indiana.d2i.htrc.oauth2.userinfo.OAuth2UserInfoEndpoint.java

private Response handleOAuthProblemException() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuth2ErrorCodes.INVALID_REQUEST).setErrorDescription("Cannot find required parameters.")
            .buildJSONMessage();// w w  w.ja va  2 s .  c  om

    return Response.status(response.getResponseStatus())
            .header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, OAuthUIUtil.getRealmInfo())
            .entity(response.getBody()).build();
}

From source file:com.alfaariss.oa.OAServlet.java

/**
 * Process HTTP requests.//from www.ja va2 s .  c  o  m
 * 
 * Retrieve an enabled requestor profile or helper for the given request 
 * and delegate the request using the following algorithm:
 * 
 * <dl>
 *  <dt>type (helper or profile)</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} from 
 *      {@link HttpServletRequest#getContextPath()} till '/' minus slashes</dd>
 *  <dt>id of helper or profile</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} 
 *      first '/' till second '/' minus slashes</dd>
 * </dl>
 * 
 * @see javax.servlet.http.HttpServlet#service(
 *  javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        String sRequestURI = oRequest.getRequestURI();

        //Check if profiles are available
        if (_profiles.isEmpty() && _helpers.isEmpty())
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);

        //Retrieve profile
        String sContextPath = oRequest.getContextPath();
        String sServletPath = oRequest.getServletPath();

        //type = uri  - context
        String sType = sRequestURI.substring(sContextPath.length());
        if (sType.length() <= 1) {
            //No profile or helper requested
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            //type minus slashes 
            sType = sType.substring(1, sType.length());
            int index = sType.indexOf('/');
            if (index <= 1) {
                _logger.debug("Bad request: no id in path: " + sServletPath);
                //No id requested
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {

                String sId = sType.substring(index + 1, sType.length()); //id minus slashes 
                sType = sType.substring(0, index);
                if (_logger.isDebugEnabled())
                    _logger.debug("Processing: " + sType + " request");

                //sId = sId.substring(1, sId.length());
                index = sId.indexOf('/');
                if (index > 0) {
                    //remove suffix
                    sId = sId.substring(0, index);
                }

                try {
                    ServiceTypes type = ServiceTypes.valueOf(sType);
                    switch (type) {
                    case helpers: {
                        IHelper helper = _helpers.get(sId);
                        if (helper == null || !(helper instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else if (!helper.isEnabled())
                            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);
                        else
                            ((IService) helper).service(oRequest, oResponse);
                        break;
                    }
                    case profiles: {
                        IRequestorProfile profile = _profiles.get(sId);
                        if (profile == null || !(profile instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else
                            ((IService) profile).service(oRequest, oResponse);
                        break;
                    }
                    }
                } catch (IllegalArgumentException e) {
                    _logger.debug("Bad request", e);
                    //Invalid type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                } catch (NullPointerException e) {
                    _logger.debug("Bad request", e);
                    //No type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        }

        //send okay if no response is sent yet
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Could not process request due to internal error", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.harvard.i2b2.fhir.oauth2.ws.OAuth2TokenEndpoint.java

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

    try {/*from   w w w.  j  a  v  a  2s  .  c  om*/
        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(), authToken)) {
            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();
        }

        logger.trace("authToken:" + authToken);
        String state = authToken.getState();
        String patientId = authToken.getPatient();

        AccessToken accessToken = accessTokenBean.createAccessTokenAndDeleteAuthToken(authToken);

        URI fhirBase = HttpHelper.getBasePath(request, serverConfigs);
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken.getTokenString()).setExpiresIn("3600")
                .setScope(accessToken.getScope()).setParam("token_type", "Bearer").setParam("state", state)
                .setParam("patient", patientId)//"1000000005")//authToken.getPatient())
                .setParam("need_patient_banner", "true")
                .setParam("smart_style_url", fhirBase.toString() + "smartstyleuri").buildJSONMessage();
        logger.trace("pat:" + authToken.getPatient());
        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.energyos.espi.datacustodian.web.api.RetailCustomerRESTController.java

@RequestMapping(value = Routes.RETAIL_CUSTOMER_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/* w ww .  j  a v  a  2  s  . c o m*/
public void update(HttpServletResponse response, @PathVariable Long applicationInformationId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException, FeedException {
    RetailCustomer retailCustomer = retailCustomerService.findById(applicationInformationId);

    if (retailCustomer != null) {
        try {

            RetailCustomer newRetailCustomer = retailCustomerService.importResource(stream);
            retailCustomer.merge(newRetailCustomer);
        } catch (Exception e) {
            System.out.printf("***** Error Caused by RetailCustomer.x.IndentifiedObject need: %s",
                    e.toString());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AccessTokenController.java

private HttpEntity<String> buildInvalidUserPassResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuthError.TokenResponse.INVALID_GRANT)
            .setErrorDescription(Constants.INVALID_USER_PASSWORD).buildJSONMessage();
    return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}

From source file:com.pymegest.applicationserver.api.FamiliaController.java

@RequestMapping(value = { "/Familia" }, method = RequestMethod.POST)
public void insert(HttpServletRequest request, HttpServletResponse response, @RequestBody String jsonInput) {

    try {//from  w ww .j a  v  a  2  s . c  o  m

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Familia familia = (Familia) objectMapper.readValue(jsonInput, Familia.class);

        if (familia != null) {

            familiaDAO.insert(familia);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json; chaset=UTF-8");

            String jsonOutput = objectMapper.writeValueAsString(familia);
            response.getWriter().println(jsonOutput);

        } else {

            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType("application/json; chaset=UTF-8");

            BussinesMessage mensaje = new BussinesMessage();
            mensaje.setMensaje("Imposible insertar un puesto de trabajo.");

            String json = objectMapper.writeValueAsString(mensaje);
            response.getWriter().println(json);

        }

    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("text/plain; charset=UTF-8;");
        try {

            ex.printStackTrace(response.getWriter());

        } catch (IOException ex1) {
        }
    }

}

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

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

    String repositoryPath = null;
    final String requestPath = request.getPathInfo();
    boolean deep = false;
    if (requestPath == null) {
        deep = true;/*  w ww  .ja v  a2s . co m*/
    }
    final OutputStream out = response.getOutputStream();
    try {
        repositoryPath = extractRepositoryPath(request);
        final IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity != null) {
            if (entity instanceof IResource) {
                data = buildResourceData(entity, request, response);
            } else if (entity instanceof ICollection) {
                String collectionPath = request.getRequestURI().toString();
                String acceptHeader = request.getHeader(ACCEPT_HEADER);
                if (acceptHeader != null && acceptHeader.contains(JSON)) {
                    if (!collectionPath.endsWith(IRepository.SEPARATOR)) {
                        collectionPath += IRepository.SEPARATOR;
                    }
                    data = buildCollectionData(deep, entity, collectionPath);
                } else {
                    // welcome file support
                    IResource index = ((ICollection) entity).getResource(INDEX_HTML);
                    if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) {
                        data = buildResourceData(index, request, response);
                    } else {
                        // listing of collections is forbidden
                        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                                LISTING_OF_FOLDERS_IS_FORBIDDEN);
                        return;
                    }
                }
            } else {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                        LISTING_OF_FOLDERS_IS_FORBIDDEN);
                return;
            }
        } else {
            exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND,
                    String.format("Resource at [%s] does not exist", requestPath));
            return;
        }

        if (entity instanceof IResource) {
            final IResource resource = (IResource) entity;
            String mimeType = null;
            String extension = ContentTypeHelper.getExtension(resource.getName());
            if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                response.setContentType(mimeType);
            } else {
                response.setContentType(resource.getContentType());
            }
        }
        sendData(out, data);
    } catch (final IllegalArgumentException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (final MissingResourceException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } catch (final RuntimeException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }
}