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.energyos.espi.datacustodian.web.api.ElectricPowerUsageSummaryRESTController.java

@RequestMapping(value = Routes.ROOT_ELECTRIC_POWER_USAGE_SUMMARY_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody//from   w w  w  .  j  ava 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 {
        ElectricPowerUsageSummary electricPowerUsageSummary = this.electricPowerUsageSummaryService
                .importResource(stream);
        exportService.exportElectricPowerUsageSummary_Root(subscriptionId, electricPowerUsageSummary.getId(),
                response.getOutputStream(), new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:eu.smartfp7.EdgeNode.SocialNetworkFeed.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */// w  ww  .  j  av  a 2  s .c  o  m
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String accept = request.getHeader("Accept");
    if (accept != null && accept.contains("application/json"))
        response.setContentType("application/json; charset=utf-8");
    else
        response.setContentType("text/plain; charset=utf-8");

    PrintWriter out = response.getWriter();

    String action = request.getParameter("action");
    String socialname = null;
    if (action == null) {
        try {
            response.sendRedirect("socialFeed.html");
        } catch (IOException e1) {
            System.err.println("doGet IOException: Can not redirect");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"action parameter not specified\"}");
        }
        return;
    }

    int res = -1;
    if (action.equals("start")) {
        // Read the keyword for the start action
        String keyword = request.getParameter("keyword");
        if (keyword == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"Start action requires the parameter 'keyword'\"}");
            return;
        }
        res = startSocial(keyword, out, request);
    } else if (action.equals("stop") || action.equals("delete")) {
        // Read the social network name for the other actions that need it
        socialname = request.getParameter("name");
        if (socialname == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("{\"error\":\"Stop and delete actions require the parameter 'name'\"}");
            return;
        }
        if (action.equals("stop"))
            res = stopSocial(socialname, out);
        else if (action.equals("delete"))
            res = deleteSocial(socialname, out);
    } else if (action.equals("list"))
        res = listRunningSocials(out);
    else if (action.equals("delete_all"))
        res = deleteAllSocials(out, request);
    else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.println(
                "{\"error\":\"Unknown action, should be one of: 'list', 'start', 'stop', 'delete', 'delete_all'\"}");
        return;
    }
    // error messages will be printed by the function
    if (res < 0) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else if (res > 0) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:org.magnum.mobilecloud.video.VideoSvc.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/unlike", method = RequestMethod.POST)
public @ResponseBody void unlikeVideo(@PathVariable("id") long id, HttpServletRequest request,
        HttpServletResponse response) {/* w  ww .ja  v  a2s  . c  om*/
    Video video = videos.findOne(id);
    if (video != null) {
        Set<String> users = video.getLikesUserNames();
        String user = request.getRemoteUser();
        if (users.contains(user)) {
            users.remove(user);
            video.setLikesUserNames(users);
            video.setLikes(users.size());
            videos.save(video);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:org.bjason.oauth2.TokenResource.java

private Response buildInvalidClientIdResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
            .setError(OAuthError.TokenResponse.INVALID_CLIENT).setErrorDescription(INVALID_CLIENT_DESCRIPTION)
            .buildJSONMessage();/* ww w .  jav a 2  s.  c o m*/
    return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}

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

@RequestMapping(value = Routes.ROOT_TIME_CONFIGURATION_MEMBER, method = RequestMethod.DELETE)
public void delete(HttpServletResponse response, @PathVariable Long timeConfigurationId,
        @RequestParam Map<String, String> params, InputStream stream) {
    try {/*from   w w  w .  j  a v a  2  s .  com*/
        resourceService.deleteById(timeConfigurationId, TimeConfiguration.class);
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping(value = Routes.ROOT_INTERVAL_BLOCK_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody//  w w w  .ja va  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 {
        IntervalBlock intervalBlock = this.intervalBlockService.importResource(stream);
        exportService.exportIntervalBlock_Root(subscriptionId, intervalBlock.getId(),
                response.getOutputStream(), new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping(value = "/contacts/{id}/delete", method = RequestMethod.GET)
public ModelAndView getDeleteContact(@PathVariable String id) {

    ModelAndView modelAndView = new ModelAndView();
    try {//from w  ww.  j a  va2 s  .  c  om
        deleteContactController.deleteContact(id);
        modelAndView.setViewName("redirect:/contacts");
    } catch (DalException ex) {
        logger.error("A database error occured.", ex);
        modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        modelAndView.addObject("errorMessage", "An internal database error occured. Please try again.");
        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 (caused by id = "
                + id + "). Please use only numeric values.");
        modelAndView.setViewName("/errorPage.jsp");
    }
    return modelAndView;
}

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

@RequestMapping(value = Routes.ROOT_USAGE_POINT_COLLECTION, method = RequestMethod.POST, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody//from   ww  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 {
        UsagePoint usagePoint = this.usagePointService.importResource(stream);
        exportService.exportUsagePoint_Root(subscriptionId, usagePoint.getId(), response.getOutputStream(),
                new ExportFilter(params));
    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:contestTabulation.Setup.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    Entity contestInfo = Retrieve.contestInfo();

    GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(jsonFactory)
            .setTransport(httpTransport)
            .setClientSecrets((String) contestInfo.getProperty("OAuth2ClientId"),
                    (String) contestInfo.getProperty("OAuth2ClientSecret"))
            .build().setFromTokenResponse(new JacksonFactory().fromString(
                    ((Text) contestInfo.getProperty("OAuth2Token")).getValue(), GoogleTokenResponse.class));

    String docName = null, docLevel = null;
    for (Level level : Level.values()) {
        docName = req.getParameter("doc" + level.getName());
        if (docName != null) {
            docLevel = level.toString();
            break;
        }//w ww.ja  va2 s .c  o m
    }

    if (docLevel == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Spreadsheet creation request must have paramater document name parameter set");
        return;
    }

    Query query = new Query("registration")
            .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, docLevel))
            .addSort("schoolName", SortDirection.ASCENDING);
    List<Entity> registrations = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());

    Map<String, List<JSONObject>> studentData = new HashMap<String, List<JSONObject>>();
    for (Entity registration : registrations) {
        String regSchoolName = ((String) registration.getProperty("schoolName")).trim();
        String regStudentDataJSON = unescapeHtml4(((Text) registration.getProperty("studentData")).getValue());

        JSONArray regStudentData = null;
        try {
            regStudentData = new JSONArray(regStudentDataJSON);
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        for (int i = 0; i < regStudentData.length(); i++) {
            if (!studentData.containsKey(regSchoolName)) {
                studentData.put(regSchoolName, new ArrayList<JSONObject>());
            }
            try {
                studentData.get(regSchoolName).add(regStudentData.getJSONObject(i));
            } catch (JSONException e) {
                resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                e.printStackTrace();
                return;
            }
        }
    }

    for (List<JSONObject> students : studentData.values()) {
        Collections.sort(students, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject a, JSONObject b) {
                try {
                    return a.getString("name").compareTo(b.getString("name"));
                } catch (JSONException e) {
                    e.printStackTrace();
                    return 0;
                }
            }
        });
    }

    Workbook workbook = new XSSFWorkbook();

    XSSFCellStyle boldStyle = (XSSFCellStyle) workbook.createCellStyle();
    Font boldFont = workbook.createFont();
    boldFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
    boldStyle.setFont(boldFont);

    Map<Subject, XSSFCellStyle> subjectCellStyles = new HashMap<Subject, XSSFCellStyle>();
    for (Subject subject : Subject.values()) {
        final double ALPHA = .144;
        String colorStr = (String) contestInfo.getProperty("color" + subject.getName());
        byte[] backgroundColor = new byte[] { Integer.valueOf(colorStr.substring(1, 3), 16).byteValue(),
                Integer.valueOf(colorStr.substring(3, 5), 16).byteValue(),
                Integer.valueOf(colorStr.substring(5, 7), 16).byteValue() };
        // http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
        byte[] borderColor = new byte[] { (byte) ((backgroundColor[0] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[1] & 0xff) * (1 - ALPHA)),
                (byte) ((backgroundColor[2] & 0xff) * (1 - ALPHA)) };

        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        style.setFillBackgroundColor(new XSSFColor(backgroundColor));
        style.setFillPattern(CellStyle.ALIGN_FILL);

        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(new XSSFColor(borderColor));
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(new XSSFColor(borderColor));
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(new XSSFColor(borderColor));
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(new XSSFColor(borderColor));
        subjectCellStyles.put(subject, style);
    }

    Entry<String, List<JSONObject>>[] studentDataEntries = studentData.entrySet().toArray(new Entry[] {});
    Arrays.sort(studentDataEntries, Collections.reverseOrder(new Comparator<Entry<String, List<JSONObject>>>() {
        @Override
        public int compare(Entry<String, List<JSONObject>> arg0, Entry<String, List<JSONObject>> arg1) {
            return Integer.compare(arg0.getValue().size(), arg1.getValue().size());
        }
    }));

    for (Entry<String, List<JSONObject>> studentDataEntry : studentDataEntries) {
        Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(studentDataEntry.getKey()));
        Row row = sheet.createRow((short) 0);

        String[] columnNames = { "Name", "Grade", "N", "C", "M", "S" };
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            Cell cell = row.createCell(i);
            cell.setCellValue(columnName);
            cell.setCellStyle(boldStyle);
            CellUtil.setAlignment(cell, workbook, CellStyle.ALIGN_CENTER);
        }

        int longestNameLength = 7;
        int rowNum = 1;
        for (JSONObject student : studentDataEntry.getValue()) {
            try {
                row = sheet.createRow((short) rowNum);
                row.createCell(0).setCellValue(student.getString("name"));
                row.createCell(1).setCellValue(student.getInt("grade"));

                for (Subject subject : Subject.values()) {
                    String value = student.getBoolean(subject.toString()) ? "" : "X";
                    Cell cell = row.createCell(Arrays.asList(columnNames).indexOf(subject.toString()));
                    cell.setCellValue(value);
                    cell.setCellStyle(subjectCellStyles.get(subject));
                }

                if (student.getString("name").length() > longestNameLength) {
                    longestNameLength = student.getString("name").length();
                }

                rowNum++;
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }
        }

        sheet.createFreezePane(0, 1, 0, 1);
        // sheet.autoSizeColumn((short) 0); Not supported by App Engine
        sheet.setColumnWidth((short) 0, (int) (256 * longestNameLength * 1.1));
    }

    Drive drive = new Drive.Builder(httpTransport, jsonFactory, credential)
            .setApplicationName("contestTabulation").build();

    File body = new File();
    body.setTitle(docName);
    body.setMimeType("application/vnd.google-apps.spreadsheet");

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    workbook.write(outStream);
    ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
    InputStreamContent content = new InputStreamContent(
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", inStream);

    drive.files().insert(body, content).execute();
    workbook.close();
}

From source file:com.jaspersoft.jasperserver.rest.RESTLoginAuthenticationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String username = EncryptionRequestUtils.getValue(request,
            AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
    String password = EncryptionRequestUtils.getValue(request,
            AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY);

    if (!StringUtils.isEmpty(username)) {
        // decoding since | is not http safe
        username = URLDecoder.decode(username, CharEncoding.UTF_8);

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                password);/* ww w.  j  av a 2s. c o m*/
        authRequest.setDetails(new WebAuthenticationDetails(httpRequest));

        Authentication authResult;
        try {
            authResult = authenticationManager.authenticate(authRequest);
        } catch (AuthenticationException e) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " failed to authenticate: " + e.toString());
            }

            if (log.isWarnEnabled()) {
                log.warn("User " + username + " failed to authenticate: " + e.toString() + " " + e,
                        e.getRootCause());
            }

            SecurityContextHolder.getContext().setAuthentication(null);

            // Send an error message in the form of OperationResult...
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //OperationResult or = servicesUtils.createOperationResult(1, "Invalid username " + username);
            PrintWriter pw = httpResponse.getWriter();
            pw.print("Unauthorized");
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("User " + username + " authenticated: " + authResult);
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);

        chain.doFilter(request, response);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Failed to authenticate: Bad request. Username and password must be specified.");
        }
        if (log.isWarnEnabled()) {
            log.warn("Failed to authenticate: Bad request. Username and password must be specified.");
        }

        httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        PrintWriter pw = httpResponse.getWriter();
        pw.print("Bad request."
                + (StringUtils.isEmpty(username)
                        ? " Parameter " + AuthenticationProcessingFilter.SPRING_SECURITY_FORM_USERNAME_KEY
                                + " not found."
                        : "")
                + (StringUtils.isEmpty(password)
                        ? " Parameter " + AuthenticationProcessingFilter.SPRING_SECURITY_FORM_PASSWORD_KEY
                                + " not found."
                        : ""));
    }
}