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.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentdata/{userId}")
public @ResponseBody StudentInfoData getStudentInfo(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String userId) throws InvocationException {
    try {/*from w w  w. j ava2  s.  co  m*/
        User user = getUserObject(userId);
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(userId, token);
        StudentInfoData sd = getStudentInfo(idAda);
        if (sd != null) {
            return sd;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

        return null;
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:au.org.ala.biocache.web.BreakdownController.java

@RequestMapping(value = "/breakdown*")
public @ResponseBody TaxaRankCountDTO breakdownByQuery(BreakdownRequestParams breakdownParams,
        HttpServletResponse response) throws Exception {
    logger.debug(breakdownParams);/*  w  w  w  . ja  v  a 2s .co  m*/
    if (StringUtils.isNotEmpty(breakdownParams.getQ())) {
        if (breakdownParams.getMax() != null || StringUtils.isNotEmpty(breakdownParams.getRank())
                || StringUtils.isNotEmpty(breakdownParams.getLevel()))
            return searchDAO.calculateBreakdown(breakdownParams);
        else
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "No context provided for breakdown.  Please supply either max, rank or level as a minimum");
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query provided for breakdown");
    }
    return null;
}

From source file:com.eureka.v1_0.account.information.api.AccountInformationController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE, value = "/resettoken")
public CreateResetPasswordTokenResponse createResetPasswordToken(
        @RequestBody CreateResetPasswordTokenRequest createResetPasswordTokenRequest,
        HttpServletRequest request, HttpServletResponse response) {
    if (createResetPasswordTokenRequest != null) {
        try {//from ww w  .  j a  va 2  s. c  o  m
            witLoggerService.debug(JaxbHandler.toXml(createResetPasswordTokenRequest));
            CreateResetPasswordTokenResponse createResetPasswordTokenResponse = this.accountInformationApiService
                    .createResetPasswordToken(createResetPasswordTokenRequest);
            if (createResetPasswordTokenResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(createResetPasswordTokenResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return createResetPasswordTokenResponse;
            } else {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            }
        } catch (Exception ex) {
            witLoggerService.warn(ex);
            ex.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    return null;
}

From source file:com.vmware.identity.MetadataController.java

/**
 * Handle default tenant request sent with a wrong binding
 *///from   w w w .j  a  va  2  s  .  c  o  m
@RequestMapping(value = "/SAML2/Metadata")
public void metadataDefaultTenantBindingError(Locale locale, HttpServletResponse response) throws IOException {
    logger.info("Metadata binding error! The client locale is {}, DEFAULT tenant", locale.toString());

    // use validation result code to return error to client
    ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", "Binding");
    String message = vr.getMessage(messageSource, locale);
    response.sendError(vr.getResponseCode(), message);
    logger.info("Responded with ERROR " + vr.getResponseCode() + ", message " + message);
}

From source file:com.day.cq.wcm.foundation.forms.impl.FormsListServlet.java

/**
 * {@inheritDoc}/*w  ww.  ja va2s .  c  om*/
 */
protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp, Predicate predicate)
        throws ServletException, IOException {
    try {
        JSONWriter w = new JSONWriter(resp.getWriter());
        if (req.getRequestURI().contains("/actions")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeActions(w);
        } else if (req.getRequestURI().contains("/constraints")) {
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");

            writeConstraints(w);
        } else if (req.getRequestURI().contains("/actiondialog")) {
            final String dialogPath = this.formsManager.getDialogPathForAction(req.getParameter("id"));
            if (dialogPath != null) {
                req.getRequestDispatcher(dialogPath + ".infinity.json").forward(req, resp);
            } else {
                // if there is no dialog just return an empty dialog
                resp.setContentType("application/json");
                resp.setCharacterEncoding("utf-8");

                resp.getWriter().write("{jcr:primaryType:\"cq:WidgetCollection\"}");
            }
        } else if (req.getRequestURI().contains("/report")) {
            // we collect the information and then redirect to the bulk editor
            final String path = req.getParameter("path");
            if (path == null || path.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Path parameter is missing.");
                return;
            }
            final Resource formStartResource = req.getResourceResolver().getResource(path);
            if (formStartResource == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource not found.");
                return;
            }
            final ValueMap vm = ResourceUtil.getValueMap(formStartResource);
            final StringBuilder sb = new StringBuilder();
            sb.append(req.getContextPath());
            sb.append("/etc/importers/bulkeditor.html?rootPath=");
            String actionPath = vm.get(FormsConstants.START_PROPERTY_ACTION_PATH, "");
            if (actionPath == null || actionPath.trim().length() == 0) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Missing '" + FormsConstants.START_PROPERTY_ACTION_PATH + "' property on node "
                                + formStartResource.getPath());
            }
            if (actionPath.endsWith("*")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            if (actionPath.endsWith("/")) {
                actionPath = actionPath.substring(0, actionPath.length() - 1);
            }
            sb.append(FormsHelper.encodeValue(actionPath));
            sb.append("&initialSearch=true&contentMode=false&spc=true");
            final Iterator<Resource> elements = FormsHelper.getFormElements(formStartResource);
            while (elements.hasNext()) {
                final Resource element = elements.next();
                FieldHelper.initializeField(req, resp, element);
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(req, element);
                for (final FieldDescription desc : descs) {
                    if (!desc.isPrivate()) {
                        final String name = FormsHelper.encodeValue(desc.getName());
                        sb.append("&cs=");
                        sb.append(name);
                        sb.append("&cv=");
                        sb.append(name);
                    }
                }
            }
            resp.sendRedirect(sb.toString());
        }
    } catch (Exception e) {
        logger.error("Error while generating JSON list", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        return;
    }
}

From source file:bbdn.lti2.LTI2Servlet.java

@SuppressWarnings("unused")
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("getServiceURL=" + getServiceURL(request));

    String ipAddress = request.getRemoteAddr();
    System.out.println("LTI Service request from IP=" + ipAddress);

    String rpi = request.getPathInfo();
    String uri = request.getRequestURI();
    String[] parts = uri.split("/");
    if (parts.length < 5) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        doErrorJSON(request, response, null, "Incorrect url format", null);
        return;/*from w  w  w  .ja v a  2 s . c om*/
    }
    String controller = parts[4];
    if ("register".equals(controller)) {
        doRegister(request, response);
        return;
    } else if ("launch".equals(controller)) {
        doLaunch(request, response);
        return;
    } else if (SVC_tc_profile.equals(controller) && parts.length == 6) {
        String profile_id = parts[5];
        getToolConsumerProfile(request, response, profile_id);
        return;
    } else if (SVC_tc_registration.equals(controller) && parts.length == 6) {
        String profile_id = parts[5];
        registerToolProviderProfile(request, response, profile_id);
        return;
    } else if (SVC_Result.equals(controller) && parts.length == 6) {
        String sourcedid = parts[5];
        handleResultRequest(request, response, sourcedid);
        return;
    } else if (SVC_Settings.equals(controller) && parts.length >= 7) {
        handleSettingsRequest(request, response, parts);
        return;
    }

    IMSJSONRequest jsonRequest = new IMSJSONRequest(request);
    if (jsonRequest.valid) {
        System.out.println(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.moss.bdbadmin.jetty.BdbAdminJettyAdapter.java

public void handle(String target, final HttpServletRequest request, final HttpServletResponse response,
        int arg3) throws IOException, ServletException {

    target = request.getRequestURI(); // the target is automatically URLDecoded, we don't want this

    if (!target.startsWith(contextPath)) {
        return;/*www  . ja v a  2s  . c o  m*/
    }

    final IdProof assertion;
    {
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (target.length() >= contextPath.length()) {
            path = target.substring(contextPath.length()).trim();
        } else {
            path = target;
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            service.clearDb(assertion, db);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            } else {
                                response.setStatus(HttpServletResponse.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } else if ("DELETE".equals(request.getMethod())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatus(HttpServletResponse.SC_OK);
                            } else {
                                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();

    ((Request) request).setHandled(true);
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/*  w  w w .jav  a  2s  . c om*/
        WSRole role = restUtils.unmarshal(WSRole.class, req.getInputStream());
        role = restUtils.populateServiceObject(role);

        if (userAndRoleManagementService.findRoles(wsRoleToWSRoleSearchCriteria(role)).length == 0) {
            userAndRoleManagementService.putRole(role);
            restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
        } else {
            throw new IllegalArgumentException(
                    "can not create new role: " + role.getRoleName() + ". it already exists");
        }
    } catch (Exception e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }
}

From source file:com.rmn.qa.servlet.BmpServlet.java

/**
 * Starts a new BrowserMobProxy. Note that either recordHar must be set to true or some credentials are provided or
 * a proxy will not be created./*  w  w  w  . j a  v a2s .c  om*/
 *
 * Content should be a json object in the following form.
 * 
 * <pre>
{
  "uuid": "my-uuid",//required
  "recordHar" : "true",
  "credentials": [{
    "domain" : "",
    "username" : "",
    "password" : "",
  }]
}
 * </pre>
 * 
 * @return Responds with a 201 Created and the url ins the Location header if proxy is created.
 * 
 * @return Responds with a 400 Bad Request if the uuid is not specified or there is no reason to create the proxy
 *         (see above).
 * 
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // if (request.getContentType().equals("application/json"))
    try {
        JsonNode input = getNodeFromRequest(request);
        String uuid = getJsonString(input, "uuid");
        if (StringUtils.isBlank(uuid)) {
            log.error("uuid not  present");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "uuid must be specified in json");
            return;
        }

        JsonNode harRecording = input.get("recordHar");
        boolean recorrdingHar = harRecording != null && harRecording.asBoolean(false);
        BrowserMobProxy proxy = null;
        if (recorrdingHar) {
            proxy = new BrowserMobProxyServer();
            Set<CaptureType> set = new HashSet<CaptureType>(CaptureType.getRequestCaptureTypes());
            set.addAll(CaptureType.getResponseCaptureTypes());
            set.removeAll(CaptureType.getBinaryContentCaptureTypes());
            proxy.setHarCaptureTypes(set);
        }
        JsonNode creds = input.get("credentials");
        if (creds != null) {
            if (proxy == null) {
                proxy = new BrowserMobProxyServer();
            }
            if (creds.isArray()) {
                ArrayNode array = (ArrayNode) creds;
                Iterator<JsonNode> elements = array.elements();
                while (elements.hasNext()) {
                    JsonNode cred = elements.next();
                    addCredentials(proxy, cred);
                }
            } else {
                addCredentials(proxy, creds);
            }
        }
        if (proxy == null) {
            log.error("Nothing for proxy to do");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Har recording or credentials not specified. There is no reason to start a proxy.");
            return;
        } else {
            String localhostname;
            // Try and get the IP address from the system property
            String runTimeHostName = System.getProperty(AutomationConstants.IP_ADDRESS);
            try {
                if (runTimeHostName == null) {
                    log.warn("Host name could not be determined from system property.");
                }
                localhostname = (runTimeHostName != null) ? runTimeHostName
                        : InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                log.error("Error parsing out host name", e);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Host name could not be determined: " + e);
                return;
            }

            // build the response
            BmpProxyRegistry.getInstance().addProxy(uuid, proxy);
            proxy.start();
            response.setStatus(HttpServletResponse.SC_CREATED);
            response.setHeader("Location", localhostname + ":" + proxy.getPort());
        }
    } catch (Exception e) {
        log.error("Error starting proxy: " + e, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error starting proxy: " + e);
    }
}

From source file:com.vmware.identity.WebssoMetadataController.java

/**
 * Handle default tenant request sent with a wrong binding
 *//* ww  w  .j  a v a  2  s .co m*/
@RequestMapping(value = "/websso/SAML2/Metadata")
public void metadataDefaultTenantBindingError(Locale locale, HttpServletResponse response) throws IOException {
    logger.info("Metadata binding error! The client locale is {}, DEFAULT tenant", locale.toString());

    // use validation result code to return error to client
    ValidationResult vr = new ValidationResult(HttpServletResponse.SC_BAD_REQUEST, "BadRequest", "Binding");
    String message = vr.getMessage(messageSource, locale);
    response.sendError(vr.getResponseCode(), message);
    logger.info("Responded with ERROR " + vr.getResponseCode() + ", message " + message);
}