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.attribyte.api.pubsub.impl.server.APIServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    List<String> path = splitPath(request);
    if (path.size() == 0) {
        sendServletResponse(NO_OPERATION_RESPONSE, response);
        return;//w  w w . j ava  2 s  .  com
    }

    Iterator<String> pathIter = path.iterator();
    String op = pathIter.next();
    switch (op) {
    case "topics":
        doTopicsGet(request, response);
        break;
    default:
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "The operation, '" + op + "' is not supported");
        break;
    }
}

From source file:edu.umd.cs.submitServer.servlets.UploadProjectStarterFiles.java

/**
 * The doPost method of the servlet. <br>
 * //  www .  j a va 2 s  .c  om
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Project project = (Project) request.getAttribute(PROJECT);

    Connection conn = null;
    FileItem fileItem = null;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();

        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] bytesForUpload = bytes.toByteArray();

        // set the byte array as the archive
        project.setArchiveForUpload(bytesForUpload);
        FormatDescription desc = FormatIdentification.identify(bytesForUpload);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit starter files that are either zipped or jarred");
            return;
        }

        Integer archivePK = project.getArchivePK();
        if (archivePK == null || archivePK.equals(0)) {
            // If there is no archive, then upload and create a new one
            project.uploadCachedArchive(conn);
            project.update(conn);
        } else {
            // Otherwise, update the archive we already have
            project.updateCachedArchive(bytesForUpload, conn);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        releaseConnection(conn);
    }
}

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

@PreAuthorize("hasRole(USER)")
@RequestMapping(method = RequestMethod.POST, value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like")
public @ResponseBody void likeVideo(@PathVariable("id") long id, Principal principal,
        HttpServletResponse response) {/*from  ww  w . j  a  v a  2 s .c  o  m*/
    Video v = videoRepo.findOne(id);
    if (v != null) {
        HashSet<String> likers = v.getLikers();
        if (likers.contains(principal.getName()))
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        else {
            likers.add(principal.getName());
            videoRepo.save(v);
            response.setStatus(HttpServletResponse.SC_OK);
        }
    } else
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}

From source file:nl.surfnet.coin.teams.service.impl.GroupServiceBasicAuthentication10aTest.java

@Test
public void testGetGroupFaultyHttpResponse() {
    super.setResponseResource(new ByteArrayResource("not-even-valid-json".getBytes()));
    super.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    Group20 group20 = groupService.getGroup20(provider, "personId", "whatever");
    assertNull(group20);//from   ww  w  .j  a  v  a 2  s . co m
}

From source file:com.oneops.cms.ws.rest.CmDjMergeController.java

@ExceptionHandler(DJException.class)
public void handleDJExceptions(DJException e, HttpServletResponse response) throws IOException {
    sendError(response, HttpServletResponse.SC_BAD_REQUEST, e);
}

From source file:edu.umd.cs.submitServer.servlets.UploadTestSetup.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO sanity checks on the format of the test setup
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Connection conn = null;//from w w  w .  j  a va  2s.  c  om
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();
        if (fileItem == null)
            throw new ServletException("fileItem is null; this is not good");

        Project project = (Project) request.getAttribute(PROJECT);
        // could be null
        String comment = multipartRequest.getOptionalCheckedParameter("comment");

        // get size in bytes
        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] byteArray = bytes.toByteArray();

        FormatDescription desc = FormatIdentification.identify(byteArray);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit test-setups that are either zipped or jarred");
            return;
        }
        Submission canonicalSubmission = Submission
                .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn);
        // start transaction here
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        TestSetup.submit(byteArray, project, comment, conn);
        conn.commit();
        transactionSuccess = true;
        if (canonicalSubmission != null
                && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) {
            WaitingBuildServer.offerSubmission(project, canonicalSubmission);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
        releaseConnection(conn);
        if (fileItem != null)
            fileItem.delete();
    }
}

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

@RequestMapping(value = "/addColleagueRequest", method = RequestMethod.POST)
public void addColleagueRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Object pUserId = request.getParameter("loggedInClothoId");
    String userId = pUserId != null ? (String) pUserId : "";

    Object pRequestId = request.getParameter("colleagueClothoId");
    String requestId = pRequestId != null ? (String) pRequestId : "";

    boolean isValid = false; //used only to make sure the person exists in Clotho
    if (!userId.equals("")) {
        isValid = true;//from  w  ww.  j a  v  a2 s.  c o  m
    }

    if (isValid) {
        //ESTABLISH CONNECTION
        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);
        //
        //userID = person logged into phagebook
        //requestId = person not logged in... receives request
        Person receivesRequest = ClothoAdapter.getPerson(requestId, clothoObject);
        if (!requestId.equals(userId)) {
            if (!receivesRequest.getId().equals("") && !userId.equals("")) {
                if (!receivesRequest.getColleagues().contains(userId)
                        && !receivesRequest.getColleagueRequests().contains(userId)) {

                    receivesRequest.addColleagueRequest(userId);
                }

            }

            clothoObject.logout();
            ClothoAdapter.setPerson(receivesRequest, clothoObject);
        }

        conn.closeConnection();

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

    }
}

From source file:uk.ac.ebi.eva.server.ws.StudyWSServer.java

@RequestMapping(value = "/{study}/files", method = RequestMethod.GET)
//    @ApiOperation(httpMethod = "GET", value = "Retrieves all the files from a study", response = QueryResponse.class)
public QueryResponse getFilesByStudy(@PathVariable("study") String study,
        @RequestParam("species") String species, HttpServletResponse response)
        throws UnknownHostException, IllegalOpenCGACredentialsException, IOException {
    initializeQueryOptions();/*from  w  ww  .  j a  v a 2 s  .  c  o m*/

    StudyDBAdaptor studyMongoDbAdaptor = DBAdaptorConnector.getStudyDBAdaptor(species);
    VariantSourceDBAdaptor variantSourceDbAdaptor = DBAdaptorConnector.getVariantSourceDBAdaptor(species);

    QueryResult idQueryResult = studyMongoDbAdaptor.findStudyNameOrStudyId(study, queryOptions);
    if (idQueryResult.getNumResults() == 0) {
        QueryResult queryResult = new QueryResult();
        queryResult.setErrorMsg("Study identifier not found");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return setQueryResponse(queryResult);
    }

    BasicDBObject id = (BasicDBObject) idQueryResult.getResult().get(0);
    QueryResult finalResult = variantSourceDbAdaptor
            .getAllSourcesByStudyId(id.getString(DBObjectToVariantSourceConverter.STUDYID_FIELD), queryOptions);
    finalResult.setDbTime(finalResult.getDbTime() + idQueryResult.getDbTime());

    return setQueryResponse(finalResult);
}

From source file:eu.trentorise.smartcampus.feedback.controller.FeedbackController.java

/**
 * Upload feedback data. Take as input {@link Feedback} instance as JSON String passed 
 * in 'body' param and the {@link MultipartFile} file param for the (optional) screenshot data.
 * @param request/*w w w.  jav a 2 s. c om*/
 * @param response
 * @param body
 * @param file
 * @return
 */
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
public @ResponseBody String feedback(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("body") String body, @RequestParam(required = false, value = "file") MultipartFile file) {
    User user = null;
    try {
        user = retrieveUser(request, response);
    } catch (AcServiceException e) {
        logger.error("Error reading the user: " + e.getMessage());
    }
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }

    try {
        Feedback feedback = mapper.readValue(body, Feedback.class);
        if (feedback == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
        feedback.setCreatorId("" + user.getId());
        feedback.setUser(feedback.getCreatorId());

        if (file != null) {
            String fileId = feedbackFileManager.storeFile(file.getBytes());
            feedback.setFileId(fileId);
        }
        feedback = feedbackManager.storeFeedback(feedback);
        return feedback.getId();
    } catch (Exception e) {
        logger.error("Error storing feedback: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        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)
public CreateAccountResponse createAccount(@RequestBody CreateAccountRequest createAccountRequest,
        HttpServletRequest request, HttpServletResponse response) {
    if (createAccountRequest != null) {
        try {/*from   w ww .j a  va 2s .co  m*/
            CreateAccountResponse createAccountResponse = this.accountInformationApiService
                    .createAccount(createAccountRequest);
            witLoggerService.debug(JaxbHandler.toXml(createAccountRequest));
            if (createAccountResponse != null) {
                witLoggerService.debug(JaxbHandler.toXml(createAccountResponse));
                response.setStatus(HttpServletResponse.SC_OK);
                return createAccountResponse;
            } 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;
}