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:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>DELETE</code> method.
 *
 * @param request servlet request/*from   ww  w.  jav a2 s .  c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        String ruleName = request.getPathInfo();
        ruleName = ruleName == null ? "" : ruleName.substring(1);
        logger.debug("rule asked for " + ruleName);
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.printf("{\"error\":\"%s not found\"}\n", ruleName);
            } else {
                st.destroy();
                out.println(Utils.Statement2JSONObject(st));
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            out.println("{\"error\":\"not rule specified for deleting\"}");
        }

    } catch (EPException epe) {
        logger.error("deleting statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private void fromHome(HttpServletRequest request, HttpServletResponse response) {
    String target = request.getParameter("TARGET");
    AuthenticationResponse eduGAINresponse = null;
    try {/*from  w w  w  .ja  v  a 2  s.co  m*/
        eduGAINresponse = getSAMLResponse(request.getParameter("SAMLResponse").getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse eduGAIN response");
            return;
        } catch (IOException e1) {
            this.log.error("Invalid eduGAIN response; unable to forward user to error page");
        }
    }

    if ((eduGAINresponse != null)
            && eduGAINresponse.getResult().equals(AuthenticationResponse.EDUGAIN_NAMESPACE_RESULT_ACCEPTED)) {
        try {
            Cookie lcook = getCookie(request, response, "statecook");
            HashMap attrs = validateCookie(lcook, "statecook");
            if ((attrs != null) && (attrs.containsKey("KEY"))) {
                String key = (String) attrs.get("KEY");
                HashMap<String, String> oldRequest = (HashMap<String, String>) this.loadRequest(key);
                String oldURL = reconstructRequest(oldRequest, response);

                attrs = parseAttrs(eduGAINresponse);

                request.getSession().setAttribute("SAMLResponse", eduGAINresponse.toSAML());
                attachCookies("lcook", attrs, response, false);
                attachCookies("statecook", null, response, true);
                //addAttributes(attrs,request.getSession());
                if (!(oldURL.equals("")) && (oldRequest != null) && !(response.isCommitted()))
                    response.sendRedirect(oldURL);
                else
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unable to load old request");

            } else
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Connection timed out");
        } catch (IOException ioe) {
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "State cookie not found");
            } catch (IOException e) {
                this.log.error("State cookie not found");
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            try {
                e.printStackTrace();
                response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, "Process timed out");
            } catch (IOException e1) {
                this.log.error("Process timed out");
                e1.printStackTrace();
            }
        }

    } else
        try {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication at home domain");
        } catch (IOException e) {
            this.log.error("Invalid authentication at home domain");
            e.printStackTrace();
        } catch (IllegalStateException ex) {
            this.log.error("Unable to forward user to error page");
            ex.printStackTrace();
        }

}

From source file:fi.hoski.web.forms.EventServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    // 1. event type
    EventType eventType;//from   www .  j a v a2s.co  m
    try {
        eventType = EventType.valueOf(request.getParameter("eventType"));
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: eventType");
        return;
    }

    // 2. earliest date
    Date startDate;
    try {
        String evd = request.getParameter("startDate");
        startDate = evd != null ? new Date(Long.parseLong(evd)) : null;
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: eventDate");
        return;
    }

    // 3. max count    
    Integer maxCount;
    try {
        String maxc = request.getParameter("maxCount");
        maxCount = maxc != null ? new Integer(maxc) : null;
    } catch (Exception e) {
        sendError(response, HttpServletResponse.SC_BAD_REQUEST, "Bad parameter: maxCount");
        return;
    }

    // 4. get events of said type
    List<Event> events = eventManager.getEvents(eventType, new Day(startDate), maxCount);

    // 5. write json
    response.setContentType("application/json");

    try {
        JSONArray jsonEvents = new JSONArray();
        for (Event event : events) {
            JSONObject e = new JSONObject(event.getAll());
            e.put("reservations", event.getChildCount());
            e.put("isFull", event.isFull());
            e.put("key", event.createKeyString());
            Day d = (Day) event.get(Event.EventDate);
            e.put("eventDate", d.getDate().getTime());
            e.put("eventName", d);
            jsonEvents.put(e);
        }

        JSONObject json = new JSONObject();

        json.put("events", jsonEvents);
        json.write(response.getWriter());
    } catch (JSONException e) {
        throw new ServletException(e);
    }
}

From source file:ai.h2o.servicebuilder.CompilePojoServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File tmp = null;/*from w w w  .  j  a  va2  s.  c  o  m*/
    try {
        //create temp directory
        tmp = createTempDirectory("compilePojo");
        logger.info("tmp dir {}", tmp);

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        List<String> pojofiles = new ArrayList<String>();
        String jarfile = null;
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) {
                    pojofiles.add(filename);
                }
                if (field.equals("jar")) {
                    jarfile = filename;
                }
                FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename));
            }
        }
        if (pojofiles.isEmpty() || jarfile == null)
            throw new Exception("need pojofile(s) and jarfile");

        //  create output directory
        File out = new File(tmp.getPath(), "out");
        boolean mkDirResult = out.mkdir();
        if (!mkDirResult)
            throw new Exception("Can't create output directory (out)");

        if (servletPath == null)
            throw new Exception("servletPath is null");

        copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java");
        FileUtils.copyDirectoryToDirectory(
                new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp);
        copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt",
                "MANIFEST.txt");

        // Compile the pojo(s)
        for (String pojofile : pojofiles) {
            runCmd(tmp,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out",
                            pojofile, "H2OPredictor.java"),
                    "Compilation of pojo failed: " + pojofile);
        }

        // create jar result file
        runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile),
                "jar extraction of h2o-genmodel failed");

        runCmd(out,
                Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"),
                "jar extraction of gson failed");

        runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar",
                "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed");

        byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar"));
        if (resjar == null)
            throw new Exception("Can't create jar of compiler output");

        logger.info("jar created, size {}", resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = pojofiles.get(0).replace(".java", "");
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.error("post failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        try {
            if (tmp != null && tmp.exists())
                FileUtils.deleteDirectory(tmp);
        } catch (IOException e) {
            logger.error("Can't delete tmp directory");
        }
    }
}

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

@RequestMapping(value = Routes.ROOT_ELECTRIC_POWER_QUALITY_SUMMARY_MEMBER, method = RequestMethod.PUT, consumes = "application/atom+xml", produces = "application/atom+xml")
@ResponseBody/*w  w w.j a  v a2s . c  om*/
public void update(HttpServletResponse response, @PathVariable Long electricPowerQualitySummaryId,
        @RequestParam Map<String, String> params, InputStream stream) throws IOException, FeedException {
    ElectricPowerQualitySummary electricPowerQualitySummary = electricPowerQualitySummaryService
            .findById(electricPowerQualitySummaryId);

    if (electricPowerQualitySummary != null) {
        try {

            ElectricPowerQualitySummary newElectricPowerQualitySummary = electricPowerQualitySummaryService
                    .importResource(stream);
            electricPowerQualitySummary.merge(newElectricPowerQualitySummary);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    }
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//from w  w w. j a v  a 2  s  .c o m
        long jobId = getJobId(restUtils.extractRepositoryUri(req.getPathInfo()));

        Job job = restUtils.unmarshal(Job.class, req.getInputStream());

        if (job.getId() != jobId) {
            if (log.isDebugEnabled()) {
                log.debug("job descriptor id " + job.getId() + " and request id " + jobId
                        + "do not match. assigning the request id to as the job id");
            }
            job.setId(jobId);
        }

        if (job.getVersion() == DISREGARD_VERSION && reportSchedulerService.getJob(jobId) != null) {
            Job oldJob = reportSchedulerService.getJob(jobId);
            job.setVersion(oldJob.getVersion());

        }
        reportSchedulerService.updateJob(job);
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, axisFault.getMessage());
    } catch (IOException e) {
        throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    }

}

From source file:com.groupon.odo.controllers.ClientController.java

@ExceptionHandler(Exception.class)
public @ResponseBody HashMap<String, Object> handleException(Exception ex, WebRequest request,
        HttpServletResponse response) {//from  www  .j a v  a  2 s.  c o  m
    response.setHeader("Content-Type", "application/json");
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

    HashMap<String, Object> returnVal = new HashMap<String, Object>();
    returnVal.put("message", ex.getMessage());
    returnVal.put("httpCode", HttpServletResponse.SC_BAD_REQUEST);

    HashMap<String, Object> errorVal = new HashMap<String, Object>();
    errorVal.put("error", returnVal);
    return errorVal;
}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

protected void retrieveProperties(HttpServletRequest request, HttpServletResponse response,
        File applicationFolder) throws IOException {
    String applicationToken = applicationFolder.getName();

    int pageSize = getIntParameter(request, "pageSize", 20);
    if (pageSize < 1 || pageSize > 100) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page size");
        return;/*from   ww  w  .j a va 2 s .  co  m*/
    }

    int page = getIntParameter(request, "page", 20);
    if (page < 1) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid page");
        return;
    }

    boolean empty = true;

    StringBuilder builder = new StringBuilder();
    builder.append('[');

    File[] files = applicationFolder.listFiles();
    if (files != null) {
        int first = (page - 1) * pageSize + 1;
        System.out.println("##### " + first);
        int i = 0;

        for (File file : files) {
            String name = file.getName();
            if (name.endsWith(ETAG_EXTENSION)) {
                if (++i >= first) {
                    String key = name.substring(0, name.length() - ETAG_EXTENSION.length());
                    System.out.println("##### " + key);
                    String etag = IOUtil.readUTF(file);

                    if (empty) {
                        empty = false;
                    } else {
                        builder.append(",");
                    }

                    builder.append("{\"application_token\":\"");
                    builder.append(applicationToken);
                    builder.append("\",\"key\":\"");
                    builder.append(key);
                    builder.append("\",\"etag\":\"");
                    builder.append(etag);
                    builder.append("\"}");

                    if (--pageSize == 0) {
                        break;
                    }
                }
            }
        }
    }

    builder.append(']');
    System.out.println(builder);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");

    InputStream body = IOUtil.streamUTF(builder.toString());

    try {
        ServletOutputStream out = response.getOutputStream();
        IOUtil.copy(body, out);
        out.flush();
    } finally {
        IOUtil.closeSilent(body);
    }
}

From source file:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {/*from  ww w  .  ja v  a 2 s . c  o m*/
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

                FileItem item = (FileItem) i.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

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

@RequestMapping(value = "/addProductsToOrder", method = RequestMethod.POST)
protected void addProductsToOrder(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {
    /*Add products to an order...
     *ASSUMPTION 1: I receive a JSONArray with key value pairs <String, int> product id, and quantity
     *ASSUMPTION 2: Along with each object I get a "discount" : double key...
     * I take care of everything here //  w  w w  .  j ava2s .  co m
     *ASSUMPTION 3: I GET THE LOGGED IN PERSONS'S ID (if I need it) from the cookie
     *ASSUMPTION 4: I GET THE ORDER ID PASSED IN.
     */

    Object pCartItems = params.get("CartItems");
    String cartItems = pCartItems != null ? (String) pCartItems : "";

    Object pUser = params.get("loggedInUserId");
    String user = pUser != null ? (String) pUser : "";

    Object pOrderId = params.get("orderId");
    String orderId = pOrderId != null ? (String) pOrderId : "";

    boolean isValid = false;

    if (!cartItems.equals("") && !user.equals("") && !orderId.equals("")) {
        isValid = true;
    }

    //should now have something like this parsed.
    /*
     [{"productId": "<ID>" , "quantity": "5", "discount": "100" }, {"productId": "<ID> ,.. etc"}];  
            
            
     */
    if (isValid) {
        //NEED TO LOG INTO CLOTHO... better way TBA

        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);
        clothoObject.login(loginMap);
        //

        //STEP 1, get the order we want to modify...
        //assuming valid order ID.
        Order editableOrder = ClothoAdapter.getOrder(orderId, clothoObject);
        //now we have the order object.
        JSONArray cartItemsJSONArray = new JSONArray(cartItems);
        //we have our JSONArray of products to add with discounts
        List<String> items = editableOrder.getProducts(); //initialize, we want to add not replace
        Date date = new Date();
        for (int i = 0; i < cartItemsJSONArray.length(); i++) {
            //process the information that we have

            JSONObject obj = (JSONObject) cartItemsJSONArray.get(i);
            Product product = ClothoAdapter.getProduct(obj.getString("productId"), clothoObject);
            product.decreaseInventory(obj.getInt("quantity"));

            CartItem item = new CartItem();
            item.setDateCreated(date);
            item.setProductId(obj.getString("productId"));
            item.setDiscount(obj.getDouble("discount"));
            item.setQuantity(obj.getInt("quantity"));

            ClothoAdapter.createCartItem(item, clothoObject);
            ClothoAdapter.setProduct(product, clothoObject);

            items.add(item.getId());

        }
        //now have a CART ITEM OBJECT all with ID's 

        editableOrder.setProducts(items);

        ClothoAdapter.setOrder(editableOrder, clothoObject);

        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        JSONObject responseJSON = new JSONObject();
        responseJSON.put("message", "successfully modified order object");
        PrintWriter out = response.getWriter();
        out.print(responseJSON);
        out.flush();

        conn.closeConnection();
    } else {
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JSONObject responseJSON = new JSONObject();
        responseJSON.put("message", "missing parameters for servlet call");
        PrintWriter out = response.getWriter();
        out.print(responseJSON);
        out.flush();
    }
}