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:gov.nist.appvet.servlet.AppVetServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    String sessionId = request.getParameter("sessionid");
    String commandStr = request.getParameter("command");
    String appId = request.getParameter("appid");
    String report = request.getParameter("report");
    String appName = request.getParameter("appname");
    String clientIpAddress = request.getRemoteAddr();

    try {/*from   w w w  . j a va 2 s.  c o m*/
        //-------------------------- Authenticate --------------------------
        if (isAuthenticated(sessionId, userName, password, clientIpAddress, commandStr)) {
            if (sessionId != null) {
                userName = Database.getSessionUser(sessionId);
            }
        } else {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.AUTHENTICATION_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //------------------------- Handle command -------------------------
        final AppVetServletCommand command = AppVetServletCommand.getCommand(commandStr);
        switch (command) {

        // Used solely by third-party clients that are not app stores nor
        // analysis (tool service) providers.
        case AUTHENTICATE:
            sessionId = Database.setSession(userName, clientIpAddress);
            sendHttpResponse(userName, appId, command.name(), clientIpAddress, "SESSIONID=" + sessionId,
                    response, HttpServletResponse.SC_OK, false);
            return;
        case GET_STATUS:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            final AppStatus currentStatus = AppStatusManager.getAppStatus(appId);
            sendHttpResponse(userName, appId, command.name(), clientIpAddress,
                    "CURRENT_STATUS=" + currentStatus.name(), response, HttpServletResponse.SC_OK, false);
            break;

        // Used by all clients.
        case GET_TOOL_REPORT:
            log.debug(userName + " invoked " + command.name() + " of " + report + " on app " + appId);
            returnReport(response, appId, report, clientIpAddress);
            break;
        case GET_APP_LOG:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            returnAppLog(response, appId, clientIpAddress);
            break;
        case GET_APPVET_LOG:
            log.debug(userName + " invoked " + command.name());
            returnAppVetLog(response, clientIpAddress);
            break;
        case DOWNLOAD_APP:
            log.debug(userName + " invoked " + command.name() + " on app " + appId);
            downloadApp(response, appId, appName, clientIpAddress);
            break;
        case DOWNLOAD_REPORTS:
            log.debug(userName + " invoked " + command.name() + " on " + "app " + appId);
            final AppStatus appStatus = AppStatusManager.getAppStatus(appId);
            if (appStatus != null) {
                if (appStatus == AppStatus.ERROR || appStatus == AppStatus.FAIL
                        || appStatus == AppStatus.WARNING || appStatus == AppStatus.PASS) {
                    downloadReports(response, appId, sessionId, clientIpAddress);
                } else {
                    sendHttpResponse(userName, appId, command.name(), clientIpAddress,
                            "App " + appId + " has not finished processing", response,
                            HttpServletResponse.SC_BAD_REQUEST, true);
                }
            } else {
                log.warn("Null appstatus in doGet()");
            }
            break;
        default:
            log.warn("Received unknown command: " + commandStr + " from IP: " + clientIpAddress);
        }
    } finally {
        userName = null;
        password = null;
        sessionId = null;
        commandStr = null;
        appId = null;
        report = null;
        appName = null;
        clientIpAddress = null;
        System.gc();
    }
}

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

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

    //get all necessary fields to create 
    //REQUIRING NAME & DESCRIPTION & CONTACT 
    boolean isValid = false;

    String name = params.get("name") != null ? params.get("name") : "";

    String description = params.get("description") != null ? params.get("description") : "";

    String contact = params.get("contact") != null ? params.get("contact") : "";

    String phone = params.get("phone") != null ? params.get("phone") : "";
    String url = params.get("url") != null ? params.get("url") : "";

    if (!name.isEmpty() && !description.isEmpty() && !contact.isEmpty()) {
        isValid = true;//from  w w w  . j  a  va  2  s  . c  om

    } else {

    }
    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);

        Vendor vendor = new Vendor();
        vendor.setName(name);
        vendor.setDescription(description);
        vendor.setContact(contact);

        if (!phone.isEmpty()) {
            vendor.setPhone(phone);
        }
        if (!url.isEmpty()) {
            vendor.setUrl(url);
        }

        //everything is set for that product
        ClothoAdapter.createVendor(vendor, clothoObject);
        JSONObject vendorJSON = new JSONObject();
        vendorJSON.put("id", vendor.getId());
        conn.closeConnection();
        response.setStatus(HttpServletResponse.SC_CREATED);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(vendorJSON);
        out.flush();
        out.close();

        clothoObject.logout();

    } else {
        JSONObject msg = new JSONObject();
        msg.put("message", "Need to send name, description, and contact");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }

}

From source file:org.opendatakit.api.forms.FormService.java

@POST
@ApiOperation(value = "Upload a zipped form definition as multipart/form-data.", response = FormUploadResult.class)
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8,
        ApiConstants.MEDIA_APPLICATION_XML_UTF8 })
@Path("{appId}/{odkClientVersion}")
public Response doPost(@Context HttpServletRequest req, @Context HttpServletResponse resp,
        @PathParam("odkClientVersion") String odkClientVersion, @PathParam("appId") String appId,
        @Context UriInfo info) throws IOException {
    logger.debug("Uploading...");
    ServiceUtils.examineRequest(req.getServletContext(), req);

    req.getContentLength();/*from   ww  w.j av a  2 s  . c  o m*/
    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new WebApplicationException(ErrorConsts.NO_MULTI_PART_CONTENT,
                HttpServletResponse.SC_BAD_REQUEST);
    }

    try {
        TablesUserPermissions userPermissions = ContextUtils.getTablesUserPermissions(callingContext);
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
        Map<String, byte[]> files = null;
        String tableId = null;
        List<String> regionalOffices = new ArrayList<>();

        // unzipping files

        for (FileItem item : items) {

            // Retrieve all Regional Office IDs to which a form definition
            // is going to be assigned to
            if (item.getFieldName().equals(WebConsts.OFFICE_ID)) {
                regionalOffices.add(item.getString());
            }

            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());

            if (fieldName.equals(WebConsts.ZIP_FILE)) {
                if (fileName == null || !(fileName.endsWith(".zip"))) {
                    throw new WebApplicationException(ErrorConsts.NO_ZIP_FILE,
                            HttpServletResponse.SC_BAD_REQUEST);
                }

                InputStream fileStream = item.getInputStream();
                ZipInputStream zipStream = new ZipInputStream(fileStream);
                files = processZipInputStream(zipStream);
            }
        }

        tableId = getTableIdFromFiles(files);

        FormUploadResult formUploadResult = uploadFiles(odkClientVersion, appId, tableId, userPermissions,
                files, regionalOffices);

        FileManifestManager manifestManager = new FileManifestManager(appId, odkClientVersion, callingContext);
        OdkTablesFileManifest manifest = manifestManager.getManifestForTable(tableId);
        FileManifestService.fixDownloadUrls(info, appId, odkClientVersion, manifest);

        formUploadResult.setManifest(manifest);
        String eTag = Integer.toHexString(manifest.hashCode()); // Is this
                                                                // right?

        return Response.status(Status.CREATED).entity(formUploadResult).header(HttpHeaders.ETAG, eTag)
                .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION)
                .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true")
                .build();

    } catch (FileUploadException | ODKDatastoreException | ODKTaskLockException | PermissionDeniedException
            | TableAlreadyExistsException e) {
        logger.error("Error uploading zip", e);
        throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(),
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    }
}

From source file:org.openxdata.server.servlet.DataImportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    try {//from w  ww.j  av a 2s.  c o  m
        // authenticate user
        User user = getUser(request.getHeader("Authorization"));
        if (user != null) {
            log.info("authenticated user:");
            // check msisdn
            String msisdn = request.getParameter("msisdn");
            if (msisdn != null && !msisdn.equals("")) {
                // if an msisdn is sent, then we retrieve the user with that phone number
                authenticateUserBasedOnMsisd(msisdn);
            }

            // can be empty or null, then the default is used. this parameter is a key in the settings table indicating the classname of the serializer to use
            String serializer = request.getParameter("serializer");

            // input stream
            // first byte contains number of forms (x)
            // followed by x number of UTF strings (use writeUTF method in DataOutput)
            formDownloadService.submitForms(request.getInputStream(), out, serializer);

        } else {
            response.setHeader("WWW-Authenticate", "BASIC realm=\"openxdata\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (UserNotFoundException userNotFound) {
        out.println("Invalid msisdn");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (Exception e) {
        log.error("Could not import data", e);
        out.println(e.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        out.close();
    }
}

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

@RequestMapping(value = Routes.ROOT_INTERVAL_BLOCK_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody/* w ww.  j  a v a 2  s.  co m*/
public void show(HttpServletRequest request, HttpServletResponse response, @PathVariable Long intervalBlockId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

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

From source file:com.sun.faban.harness.webclient.ResultAction.java

String editArchive(HttpServletRequest request, HttpServletResponse response)
        throws IOException, FileNotFoundException, ParseException {
    String[] runIds = request.getParameterValues("select");

    if (runIds == null || runIds.length < 1) {
        String msg;//from w ww.  j av  a2  s . c  o m
        msg = "Select at least one runs to archive.";
        response.getOutputStream().println(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return null;
    }

    EditArchiveModel model = new EditArchiveModel();
    model.runIds = runIds;
    model.duplicates = checkArchivedRuns(runIds);

    if (Config.repositoryURLs != null && Config.repositoryURLs.length > 1)
        model.head = "Repositories";
    else
        model.head = "Repository";

    model.results = new RunResult[runIds.length];
    for (int i = 0; i < runIds.length; i++) {
        model.results[i] = RunResult.getInstance(new RunId(runIds[i]));
    }
    // We use request attributes as not to reflect session state.
    request.setAttribute("editarchive.model", model);
    return "/edit_archive.jsp";
}

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

@RequestMapping(value = Routes.ROOT_ELECTRIC_POWER_QUALITY_SUMMARY_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//from  w  ww  . j a  v  a2 s . c om
public void show(HttpServletRequest request, HttpServletResponse response,
        @PathVariable Long electricPowerQualitySummaryId, @RequestParam Map<String, String> params)
        throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);

    try {
        exportService.exportElectricPowerQualitySummary_Root(subscriptionId, electricPowerQualitySummaryId,
                response.getOutputStream(), new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping("/accessToken")
public HttpEntity<String> token(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {

    try {/*from   ww w  . j a  va2 s  . c  o m*/
        // OAuth
        OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);

        // ??id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            return buildInvalidClientIdResponse();

        }

        // KEY?
        if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
            return buildInvalidClientSecretResponse();
        }

        String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
        // ??AUTHORIZATION_CODEPASSWORDREFRESH_TOKEN
        if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildBadAuthCodeResponse();
            }
            // TODO ??
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.PASSWORD.toString())) {
            if (!checkUserPassword(oauthRequest.getUsername(), oauthRequest.getPassword())) {
                return buildInvalidUserPassResponse();
            }
        } else if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.REFRESH_TOKEN.toString())) {
            // https://github.com/zhouyongtao/homeinns-web
            if (!oAuthService.checkAuthCode(authCode)) {
                return buildInvalidRefreshTokenResponse();
            }
        }

        // ?Access Token
        OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        final String accessToken = oauthIssuerImpl.accessToken();
        oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
        final String refreshToken = oauthIssuerImpl.refreshToken();
        oAuthService.addAccessToken(refreshToken, oAuthService.getUsernameByAuthCode(authCode));

        // ?OAuth?
        OAuthResponse response = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)
                .setAccessToken(accessToken).setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
                .setTokenType(TokenType.BEARER.toString()).setRefreshToken(refreshToken).buildJSONMessage();

        // ?OAuthResponse?ResponseEntity
        return new ResponseEntity<String>(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));

    } catch (OAuthProblemException e) {
        // ?
        OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
                .buildJSONMessage();
        return new ResponseEntity<String>(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
    }
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * {@inheritDoc}//from  w w  w  . j  ava2 s.com
 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // only handle requests to /
    if (!target.equals("/webhook")) {
        return;
    }

    // verify whether the call comes directly from GitHub using the X-GitHub-Event,
    // X-Hub-Signature and X-GitHub-Delivery headers
    String eventType = request.getHeader("X-GitHub-Event");
    String signature = request.getHeader("X-Hub-Signature");
    String deliveryId = request.getHeader("X-GitHub-Delivery");

    if (eventType == null || eventType.isEmpty()
            || (this.secret != null && (signature == null || signature.isEmpty())) || deliveryId == null
            || deliveryId.isEmpty()) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    if (signature != null) {
        // strip sha1=
        // TODO: Decide upon signature method based on this parameter
        signature = signature.substring(5);
    }

    logger.info("Processing GitHub request " + deliveryId + ".");

    // decode the data passed in the request body
    String data;
    try (InputStream inputStream = request.getInputStream()) {
        data = new String(ByteStreams.toByteArray(inputStream),
                Charset.forName(request.getCharacterEncoding()));
    }

    // verify the signature supplied to us (as long as a secret key was configured)
    try {
        if (!verifySignature(data, signature)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            baseRequest.setHandled(true);
            return;
        }
    } catch (IllegalStateException ex) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        baseRequest.setHandled(true);
        return;
    }

    // find correct event message
    eventType = eventType.replace('_', '.');

    // de-serialize and handle event data
    Map<String, Object> context = new HashMap<>();
    context.put("color", COLOR_MAP);
    context.put("event", reader.readValue(data));

    String message = this.getMessage(eventType, context);

    if (message != null) {
        this.bridge.sendMessage(message);
    }

    // answer with 204 at all times
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

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

@RequestMapping(value = Routes.ROOT_USAGE_POINT_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody/*from  w  w w. j  av  a  2  s  .c o m*/
public void show(HttpServletRequest request, HttpServletResponse response, @PathVariable Long usagePointId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    Long subscriptionId = getSubscriptionId(request);

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    try {
        System.out.println(
                "Exporting root usage point: " + usagePointId + " for subscription: " + subscriptionId);
        exportService.exportUsagePoint_Root(subscriptionId, usagePointId, response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}