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:com.imaginary.home.cloud.api.call.CommandCall.java

@Override
public void get(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {//w  w w  .  ja va  2 s . co  m
        ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Boolean hasCommands = null;

        if (userId == null) {
            String apiKey = (String) headers.get(RestApi.API_KEY);
            ControllerRelay relay = ControllerRelay.getRelay(apiKey);

            if (relay == null) {
                throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        RestException.INTERNAL_ERROR, "Relay was lost");
            }
            for (PendingCommand cmd : PendingCommand.getCommandsToSend(relay, true)) {
                list.add(toJSON(cmd));
            }
            hasCommands = PendingCommand.hasCommands(relay);
        } else {
            User user = User.getUserByUserId(userId);

            if (user == null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.NO_SUCH_USER,
                        "Invalid user access to location");
            }
            String locationId = req.getParameter("locationId");
            Collection<ControllerRelay> relays;

            if (locationId == null) {
                relays = new ArrayList<ControllerRelay>();
                for (Location location : user.getLocations()) {
                    relays.addAll(ControllerRelay.findRelaysInLocation(location));
                }
            } else {
                boolean mine = false;

                for (String lid : user.getLocationIds()) {
                    if (lid.equals(locationId)) {
                        mine = true;
                        break;
                    }
                }
                Location location = Location.getLocation(locationId);

                if (location == null || (!mine && !userId.equals(location.getOwnerId()))) {
                    throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PARAMETER,
                            "No such location: " + locationId);
                }
                relays = ControllerRelay.findRelaysInLocation(location);
            }
            for (ControllerRelay relay : relays) {
                for (PendingCommand cmd : PendingCommand.getCommands(relay)) {
                    list.add(toJSON(cmd));
                }
            }
        }
        if (hasCommands != null) {
            resp.setHeader("x-imaginary-has-commands", String.valueOf(hasCommands));
        }
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().println((new JSONArray(list)).toString());
        resp.getWriter().flush();
    } catch (PersistenceException e) {
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                e.getMessage());
    }
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//  ww  w  .  ja  v a2s  . co  m
        JAXBList<ObjectPermission> perm = (JAXBList<ObjectPermission>) restUtils.unmarshal(req.getInputStream(),
                JAXBList.class, ObjectPermissionImpl.class, UserImpl.class, RoleImpl.class);
        for (int i = 0; i < perm.size(); i++) {
            if (isValidObjectPermission(perm.get(i)) && canUpdateObjectPermissions(perm.get(i)))
                try {
                    permissionsService.putPermission(perm.get(i));
                } catch (IllegalArgumentException e) {
                    throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
                } catch (RemoteException e) {
                    throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            e.getClass().getName() + (e.getMessage() != null ? ": " + e.getMessage() : ""));
                }
            else {
                if (perm.get(i).getPermissionRecipient() instanceof User) {
                    throw new AccessDeniedException("could not set permissions for: "
                            + ((User) perm.get(i).getPermissionRecipient()).getUsername());
                } else if (perm.get(i).getPermissionRecipient() instanceof Role) {
                    throw new AccessDeniedException("could not set permissions for: "
                            + ((Role) perm.get(i).getPermissionRecipient()).getRoleName());
                } else {
                    throw new AccessDeniedException(
                            "could not set permissions for: " + (perm.get(i).getPermissionRecipient() != null
                                    ? perm.get(i).getPermissionRecipient().toString()
                                    : "null"));
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("finished PUT permissions " + perm.size() + " permissions were added");
        }
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "please check the request job descriptor");
    }
}

From source file:com.portfolio.security.LTIv2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ServletContext application, String toolProxyPath, StringBuffer outTrace)
        throws ServletException, IOException {

    outTraceFormattedMessage(outTrace, "getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    outTraceFormattedMessage(outTrace, "LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 4) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;/*from  w ww  . j  a  va2  s . com*/
    }

    Map<String, Object> payload = LTIServletUtils.processRequest(request, outTrace);
    String url = getServiceURL(request);

    String controller = parts[3];
    if ("register".equals(controller)) {
        payload.put("base_url", url);
        payload.put("launch_url", url + "register");
        doRegister(response, payload, application, toolProxyPath, outTrace);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response, session, payload, application, outTrace);
        return;
    }

    // Check if json request if valid
    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        outTraceFormattedMessage(outTrace, jsonRequest.getPostBody());
    }

    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    M_log.warn("Unknown request=" + uri);
    doErrorJSON(request, response, null, "Unknown request=" + uri, null);
}

From source file:com.iflytek.edu.cloud.frame.web.filter.CheckOpenServiceFilterTest.java

/**
 * ?version?//w  w w  .  j a  v  a  2  s.c  o m
 */
@Test
@Ignore
public void testVersionIsNull() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    response.setCharacterEncoding("UTF-8");

    try {
        request.setMethod("POST");
        request.addParameter("method", "user.get");
        filter.doFilter(request, response, null);

        Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_BAD_REQUEST);
        Assert.assertEquals(MainErrorType.MISSING_VERSION.value(), ErrorMsgParser.getErrorCode(response));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:com.asual.summer.core.ErrorResolver.java

public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception e) {/*from  w  w w  .j  av  a 2s .  c om*/

    if (e instanceof BindException) {

        BindException be = (BindException) e;
        Map<String, Map<String, Object>> errors = new HashMap<String, Map<String, Object>>();

        for (FieldError fe : (List<FieldError>) be.getFieldErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = fe.getArguments();
            String key = fe.isBindingFailure() ? fe.getCodes()[2].replaceFirst("typeMismatch", "conversion")
                    : "validation." + fe.getCodes()[2];
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (!fe.isBindingFailure()) {
                    if (key.split("\\.").length > 3) {
                        message = ResourceUtils
                                .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1))
                                        + key.substring(key.lastIndexOf(".")), args);
                    }
                    if (message == null && key.split("\\.").length > 2) {
                        message = ResourceUtils
                                .getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)), args);
                    }
                } else if (fe.isBindingFailure() && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(
                            key.substring(0, key.indexOf(".")) + key.substring(key.lastIndexOf(".")), args);
                } else {
                    message = fe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", fe.getRejectedValue());
            errors.put(fe.getField(), error);
        }

        for (ObjectError oe : (List<ObjectError>) be.getGlobalErrors()) {
            Map<String, Object> error = new HashMap<String, Object>();
            Object[] args = oe.getArguments();
            String key = "global" + (oe.getCodes() != null ? "." + oe.getCodes()[2] : "");
            String message = ResourceUtils.getMessage(key, args);
            if (message == null) {
                if (key.split("\\.").length > 3) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1))
                            + key.substring(key.lastIndexOf(".")), args);
                }
                if (message == null && key.split("\\.").length > 2) {
                    message = ResourceUtils.getMessage(key.substring(0, key.indexOf(".", key.indexOf(".") + 1)),
                            args);
                }
                if (message == null) {
                    message = oe.getDefaultMessage();
                }
            }
            error.put("message", message != null ? message : "Error (" + key + ")");
            error.put("value", oe.getObjectName());
            errors.put(oe.getObjectName(), error);
        }

        String form = (String) RequestUtils.getParameter("_form");
        if (form != null) {
            if (request.getAttribute(ERRORS) == null) {
                request.setAttribute(ERRORS, errors);
                request.setAttribute(be.getObjectName(), be.getTarget());
                return new ModelAndView(new InternalResourceView(
                        form.concat(form.contains("?") ? "&" : "?").concat("_error=true")));
            }
        } else {
            List<String> pairs = new ArrayList<String>();
            for (String key : errors.keySet()) {
                pairs.add(key + "=" + errors.get(key).get("message"));
            }
            try {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, StringUtils.join(pairs, ";"));
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
            }
        }
    }

    return null;
}

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

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

From source file:org.jetbrains.webdemo.handlers.ServerHandler.java

private void forwardRunRequest(HttpServletRequest request, HttpServletResponse response) {
    try {/*  w w  w .  j  a v a2s . c o m*/
        Project project = objectMapper.readValue(request.getParameter("project"), Project.class);
        ExamplesUtils.addHiddenFilesToProject(project);
        ExamplesUtils.addUnmodifiableFilesToProject(project);
        Map<String, String> postParameters = new HashMap<>();
        postParameters.put("project", objectMapper.writeValueAsString(project));
        postParameters.put("filename", request.getParameter("filename"));
        postParameters.put("searchForMain", request.getParameter("searchForMain"));
        forwardRequestToBackend(request, response, postParameters);
    } catch (IOException e) {
        writeResponse(request, response, "Can't parse project", HttpServletResponse.SC_BAD_REQUEST);
    } catch (NullPointerException e) {
        writeResponse(request, response, "Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    }
}

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

@RequestMapping(value = "/sucursalbancaria/{idsucursalbancaria}", method = RequestMethod.DELETE, produces = "application/json")
public void delete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        @PathVariable("idsucursalbancaria") int idsucursalbancaria) {
    try {// ww w  . ja  v  a2 s  . com
        boolean deleteSucursal;
        deleteSucursal = sucursalBancariaService.delete(idsucursalbancaria);

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

From source file:net.contextfw.web.application.internal.service.InitHandler.java

public final void handleRequest(final UriMapping mapping, final List<Class<? extends Component>> chain,
        final HttpServlet servlet, final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    if (watcher != null && watcher.hasChanged()) {
        logger.debug("Reloading resources");
        cleaner.clean();//from   ww  w.  ja v a 2  s.  co m
        internalDevelopmentTools.reloadResources();
    }

    response.addHeader("Expires", "Sun, 19 Nov 1978 05:00:00 GMT");
    response.addHeader("Last-Modified", new Date().toString());
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.addHeader("Pragma", "no-cache");

    if (chain == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        WebApplicationPage page = pageScope.createPage(servlet, request, response);
        final MutableBoolean expired = new MutableBoolean(false);
        storage.initialize(page, request, System.currentTimeMillis() + HOUR,
                new ScopedWebApplicationExecution() {
                    @Override
                    public void execute(net.contextfw.web.application.WebApplication application) {
                        try {
                            WebApplicationPage page = (WebApplicationPage) application;
                            WebApplication app = webApplicationProvider.get();
                            app.setInitializerChain(chain);
                            page.setWebApplication(app);
                            listeners.beforeInitialize();
                            page.getWebApplication().initState(mapping);
                            listeners.afterInitialize();
                            listeners.beforeRender();
                            expired.setValue(page.getWebApplication().sendResponse());
                            listeners.afterRender();
                        } catch (Exception e) {
                            // TODO Fix this construct with test
                            if (e instanceof MetaComponentException) {
                                ErrorResolution resolution = ((MetaComponentException) e).getResolution();
                                try {
                                    if (resolution == ErrorResolution.SEND_NOT_FOUND_ERROR) {
                                        response.sendError(HttpServletResponse.SC_NOT_FOUND);
                                    } else if (resolution == ErrorResolution.SEND_BAD_REQUEST_ERROR) {
                                        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                                    }
                                } catch (IOException e1) {
                                    throw new WebApplicationException(e1);
                                }
                            }
                            listeners.onException(e);
                        } finally {
                            pageScope.deactivateCurrentPage();
                        }

                    }
                });
        // Setting expiration here so that long page
        // processing is
        // not
        // penalizing client
        if (expired.booleanValue()) {
            storage.remove(page.getHandle(), request);
        } else {
            storage.refresh(page.getHandle(), request, System.currentTimeMillis() + initialMaxInactivity);
        }
    }
}

From source file:com.haulmont.cuba.core.controllers.FileDownloadController.java

public File getFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String filePath = URLEncodeUtils.decodeUtf8(request.getParameter("p"));
    if (filePath != null) {
        if (isPermittedDirectory(filePath)) {
            return new File(filePath);
        } else {//ww  w  . j av a2  s .  co m
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
    return null;
}