Example usage for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST

List of usage examples for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST.

Prototype

int SC_BAD_REQUEST

To view the source code for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST.

Click Source Link

Document

<tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)// ww  w. j av  a2  s  .c  o  m
public void testQueryFailure$badValue(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    HttpGet get = HELPER.newRequest(
            MyApplication.ROOT_QUERYABLE_RESOURCE_PATH + "?" + QueryableResourceHandler.FAILURE + "=unknown",
            HttpGet.class);
    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(getResponse.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    assertThat(getResponse.body, notNullValue());
    assertThat(getResponse.contentType, startsWith("text/plain"));
    assertThat(getResponse.language, equalTo(Locale.ENGLISH));
}

From source file:org.linagora.linshare.webservice.admin.impl.UserRestServiceImpl.java

@Path("/mail_migration")
@POST/*from w  w w  .j  a va 2 s.c o  m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Update users email address.")
@ApiResponses({ @ApiResponse(code = 403, message = "User isn't admin"),
        @ApiResponse(code = 400, message = "Bad request : missing required fields."),
        @ApiResponse(code = 500, message = "Internal server error.") })
@Override
public UpdateUsersEmailStateDto updateUsersEmail(
        @ApiParam(value = "File stream.", required = true) @Multipart(value = "file", required = true) InputStream file,
        @ApiParam(value = "The given file name of the uploaded file.", required = false) @Multipart(value = "filename", required = false) String givenFileName,
        @ApiParam(value = "The given field delimiter of the csv file.", required = false) @Multipart(value = "csvFieldDelimiter", required = false) String csvFieldDelimiter,
        MultipartBody body) throws BusinessException {
    if (file == null) {
        logger.error("Missing file (check parameter file)");
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing file (check parameter file)");
    }
    String fileName = getFileName(givenFileName, body);
    String extension = null;
    String csvExtension = ".csv";
    int splitIdx = fileName.lastIndexOf('.');
    if (splitIdx > -1) {
        extension = fileName.substring(splitIdx, fileName.length());
    }
    if (!extension.equals(csvExtension)) {
        logger.error("Bad file extension");
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "bad file extension");
    }
    File tempFile = getTempFile(file, "emails-migration", fileName);
    BufferedReader reader = null;
    String csvLine = "";
    String[] emails = null;
    String currentEmail = "";
    String newEmail = "";

    long total = 0;
    long updated = 0;
    long notUpdated = 0;
    long skipped = 0;

    if (csvFieldDelimiter == null) {
        csvFieldDelimiter = ";";
    }
    UpdateUsersEmailStateDto state = new UpdateUsersEmailStateDto();
    try {
        reader = new BufferedReader(new FileReader(tempFile));
        while ((csvLine = reader.readLine()) != null) {
            emails = csvLine.split(csvFieldDelimiter);
            currentEmail = emails[0];
            newEmail = emails[1];

            if (currentEmail.equals(newEmail)) {
                logger.debug("The former email : " + currentEmail + " is the same to new one : " + newEmail);
                skipped++;
                total++;
                continue;
            }

            boolean user = userFacade.updateEmail(currentEmail, newEmail);
            if (user) {
                updated++;
            }
            total++;
        }

        notUpdated = total - (updated + skipped);
        state.setTotal(total);
        state.setUpdated(updated);
        state.setNotUpdated(notUpdated);
        state.setSkipped(skipped);
        reader.close();
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new BusinessException(BusinessErrorCode.FILE_UNREACHABLE, e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new BusinessException(BusinessErrorCode.FILE_INVALID_INPUT_TEMP_FILE, e.getMessage());
    } finally {
        deleteTempFile(tempFile);
    }
    return state;
}

From source file:org.linagora.linshare.webservice.delegation.impl.DocumentRestServiceImpl.java

@Path("/")
@POST/*from w w  w  . j a  v a2 s  . c  om*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Create a document which will contain the uploaded file.", response = DocumentDto.class)
@ApiResponses({
        @ApiResponse(code = 403, message = "Current logged in account does not have the delegation role."),
        @ApiResponse(code = 404, message = "Document not found."),
        @ApiResponse(code = 400, message = "Bad request : missing required fields."),
        @ApiResponse(code = 500, message = "Internal server error."), })
@Override
public DocumentDto create(
        @ApiParam(value = "The owner (user) uuid.", required = true) @PathParam("ownerUuid") String ownerUuid,
        @ApiParam(value = "File stream.", required = true) @Multipart(value = "file", required = true) InputStream file,
        @ApiParam(value = "An optional description of a document.") @Multipart(value = "description", required = false) String description,
        @ApiParam(value = "The given file name of the uploaded file.", required = false) @Multipart(value = "filename", required = false) String givenFileName,
        @ApiParam(value = "Signature file stream.", required = false) @Multipart(value = "signaturefile", required = false) InputStream theSignatureFile,
        @ApiParam(value = "The given file name of the signature uploaded file.", required = false) @Multipart(value = "signatureFileName", required = false) String signatureFileName,
        @ApiParam(value = "X509 Certificate entity.", required = false) @Multipart(value = "x509cert", required = false) InputStream x509certificate,
        @ApiParam(value = "The given metadata of the uploaded file.", required = false) @Multipart(value = "metadata", required = false) String metaData,
        @ApiParam(value = "True to enable asynchronous upload processing.", required = false) @QueryParam("async") Boolean async,
        @HeaderParam("Content-Length") Long contentLength,
        @ApiParam(value = "file size (size validation purpose).", required = false) @Multipart(value = "filesize", required = false) Long fileSize,
        MultipartBody body) throws BusinessException {
    Long transfertDuration = getTransfertDuration();
    if (file == null) {
        logger.error("Missing file (check parameter file)");
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing file (check parameter file)");
    }
    String fileName = getFileName(givenFileName, body);
    // Default mode. No user input.
    if (async == null) {
        async = false;
    }
    File tempFile = getTempFile(file, "rest-delegation-document-entries", fileName);
    long currSize = tempFile.length();
    if (sizeValidation) {
        checkSizeValidation(contentLength, fileSize, currSize);
    }
    if (async) {
        logger.debug("Async mode is used");
        // Asynchronous mode
        AccountDto actorDto = documentFacade.getAuthenticatedAccountDto();
        AsyncTaskDto asyncTask = null;
        try {
            DocumentTaskContext documentTaskContext = new DocumentTaskContext(actorDto, ownerUuid, tempFile,
                    fileName, metaData, description);
            asyncTask = asyncTaskFacade.create(ownerUuid, currSize, transfertDuration, fileName, null,
                    AsyncTaskType.DOCUMENT_UPLOAD);
            DocumentUploadAsyncTask task = new DocumentUploadAsyncTask(documentAsyncFacade, documentTaskContext,
                    asyncTask);
            taskExecutor.execute(task);
            return new DocumentDto(asyncTask, documentTaskContext);
        } catch (Exception e) {
            logAsyncFailure(ownerUuid, asyncTask, e);
            throw e;
        }
    } else {
        // TODO : manage transfertDuration
        // Synchronous mode
        try {
            logger.debug("Async mode is not used");
            if (theSignatureFile != null) {
                // TODO : Manage signature and meta data
                return documentFacade.create(ownerUuid, tempFile, description, fileName);
            }
            return documentFacade.create(ownerUuid, tempFile, description, fileName);
        } finally {
            deleteTempFile(tempFile);
        }
    }
}

From source file:org.linagora.linshare.webservice.delegation.impl.ThreadEntryRestServiceImpl.java

@Path("/")
@POST// www.java2 s.  co  m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Create a thread entry which will contain the uploaded file.", response = WorkGroupEntryDto.class)
@ApiResponses({
        @ApiResponse(code = 403, message = "Current logged in account does not have the delegation role."),
        @ApiResponse(code = 404, message = "Thread entry not found."),
        @ApiResponse(code = 400, message = "Bad request : missing required fields."),
        @ApiResponse(code = 500, message = "Internal server error."), })
@Override
public WorkGroupEntryDto create(
        @ApiParam(value = "The owner (user) uuid.", required = true) @PathParam("ownerUuid") String ownerUuid,
        @ApiParam(value = "The thread uuid.", required = true) @PathParam("threadUuid") String threadUuid,
        @ApiParam(value = "File stream.", required = true) InputStream file,
        @ApiParam(value = "An optional description of a thread entry.") String description,
        @ApiParam(value = "The given file name of the uploaded file.", required = true) String givenFileName,
        @ApiParam(value = "True to enable asynchronous upload processing.", required = false) @QueryParam("async") Boolean async,
        @HeaderParam("Content-Length") Long contentLength,
        @ApiParam(value = "file size (size validation purpose).", required = false) @Multipart(value = "filesize", required = false) Long fileSize,
        MultipartBody body) throws BusinessException {
    Long transfertDuration = getTransfertDuration();
    if (file == null) {
        logger.error("Missing file (check parameter file)");
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing file (check parameter file)");
    }
    String fileName = getFileName(givenFileName, body);
    // Default mode. No user input.
    if (async == null) {
        async = false;
    }
    File tempFile = getTempFile(file, "rest-delegation-thread-entries", fileName);
    long currSize = tempFile.length();
    if (sizeValidation) {
        checkSizeValidation(contentLength, fileSize, currSize);
    }
    if (async) {
        logger.debug("Async mode is used");
        // Asynchronous mode
        AccountDto actorDto = threadEntryFacade.getAuthenticatedAccountDto();
        AsyncTaskDto asyncTask = null;
        try {
            asyncTask = asyncTaskFacade.create(ownerUuid, currSize, transfertDuration, fileName, null,
                    AsyncTaskType.THREAD_ENTRY_UPLOAD);
            ThreadEntryTaskContext threadEntryTaskContext = new ThreadEntryTaskContext(actorDto, ownerUuid,
                    threadUuid, tempFile, fileName, null);
            ThreadEntryUploadAsyncTask task = new ThreadEntryUploadAsyncTask(threadEntryAsyncFacade,
                    threadEntryTaskContext, asyncTask);
            taskExecutor.execute(task);
            return new WorkGroupEntryDto(asyncTask, threadEntryTaskContext);
        } catch (Exception e) {
            logAsyncFailure(ownerUuid, asyncTask, e);
            throw e;
        } finally {
            deleteTempFile(tempFile);
        }
    } else {
        // TODO : manage transfertDuration
        // Synchronous mode
        try {
            logger.debug("Async mode is not used");
            return threadEntryFacade.create(ownerUuid, threadUuid, tempFile, fileName);
        } finally {
            deleteTempFile(tempFile);
        }
    }
}

From source file:org.linagora.linshare.webservice.delegationv2.impl.DocumentRestServiceImpl.java

@Path("/")
@POST/* w w w  .  j  a va 2s .c om*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Create a document which will contain the uploaded file.", response = DocumentDto.class)
@ApiResponses({
        @ApiResponse(code = 403, message = "Current logged in account does not have the delegation role."),
        @ApiResponse(code = 404, message = "Document not found."),
        @ApiResponse(code = 400, message = "Bad request : missing required fields."),
        @ApiResponse(code = 500, message = "Internal server error."), })
@Override
public DocumentDto create(
        @ApiParam(value = "The owner (user) uuid.", required = true) @PathParam("ownerUuid") String ownerUuid,
        @ApiParam(value = "File stream.", required = true) @Multipart(value = "file", required = true) InputStream file,
        @ApiParam(value = "An optional description of a document.") @Multipart(value = "description", required = false) String description,
        @ApiParam(value = "The given file name of the uploaded file.", required = false) @Multipart(value = "filename", required = false) String givenFileName,
        @ApiParam(value = "Signature file stream.", required = false) @Multipart(value = "signaturefile", required = false) InputStream theSignatureFile,
        @ApiParam(value = "The given file name of the signature uploaded file.", required = false) @Multipart(value = "signatureFileName", required = false) String signatureFileName,
        @ApiParam(value = "X509 Certificate entity.", required = false) @Multipart(value = "x509cert", required = false) InputStream x509certificate,
        @ApiParam(value = "The given metadata of the uploaded file.", required = false) @Multipart(value = "metadata", required = false) String metaData,
        @ApiParam(value = "True to enable asynchronous upload processing.", required = false) @QueryParam("async") Boolean async,
        @ApiParam(value = "file size (size validation purpose).", required = true) @Multipart(value = "filesize", required = true) Long fileSize,
        MultipartBody body) throws BusinessException {
    Long transfertDuration = getTransfertDuration();
    if (file == null) {
        logger.error("Missing file (check parameter file)");
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing file (check parameter file)");
    }
    String fileName = getFileName(givenFileName, body);
    // Default mode. No user input.
    if (async == null) {
        async = false;
    }
    File tempFile = getTempFile(file, "rest-delegation-document-entries", fileName);
    long currSize = tempFile.length();
    if (sizeValidation) {
        checkSizeValidation(fileSize, currSize);
    }
    if (async) {
        logger.debug("Async mode is used");
        // Asynchronous mode
        AccountDto actorDto = documentFacade.getAuthenticatedAccountDto();
        AsyncTaskDto asyncTask = null;
        try {
            DocumentTaskContext documentTaskContext = new DocumentTaskContext(actorDto, ownerUuid, tempFile,
                    fileName, metaData, description);
            asyncTask = asyncTaskFacade.create(ownerUuid, currSize, transfertDuration, fileName, null,
                    AsyncTaskType.DOCUMENT_UPLOAD);
            DocumentUploadAsyncTask task = new DocumentUploadAsyncTask(documentAsyncFacade, documentTaskContext,
                    asyncTask);
            taskExecutor.execute(task);
            return new DocumentDto(asyncTask, documentTaskContext);
        } catch (Exception e) {
            logAsyncFailure(ownerUuid, asyncTask, e);
            throw e;
        }
    } else {
        // TODO : manage transfertDuration
        // Synchronous mode
        try {
            logger.debug("Async mode is not used");
            if (theSignatureFile != null) {
                // TODO : Manage signature and meta data
                return documentFacade.create(ownerUuid, tempFile, description, fileName);
            }
            return documentFacade.create(ownerUuid, tempFile, description, fileName);
        } finally {
            deleteTempFile(tempFile);
        }
    }
}

From source file:org.linagora.linshare.webservice.impl.PluginCompatibilityRestServiceImpl.java

@POST
@Path("/share/multiplesharedocuments")
@Override//ww  w. j ava  2s  .c o  m
public void multiplesharedocuments(@FormParam("targetMail") String targetMail,
        @FormParam("file") List<String> uuid, @FormParam("securedShare") @DefaultValue("0") int securedShare,
        @FormParam("message") @DefaultValue("") String message,
        @FormParam("inReplyTo") @DefaultValue("") String inReplyTo,
        @FormParam("references") @DefaultValue("") String references) throws BusinessException {
    User actor;

    actor = webServiceShareFacade.checkAuthentication();
    if ((actor instanceof Guest && !actor.getCanUpload()))
        throw giveRestException(HttpStatus.SC_FORBIDDEN, "You are not authorized to use this service");
    CollectionUtils.filter(uuid, StringPredicates.isNotBlank());
    if (uuid.isEmpty())
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing parameter file");
    webServiceShareFacade.multiplesharedocuments(targetMail, uuid, securedShare, message, inReplyTo,
            references);
}

From source file:org.linagora.linshare.webservice.impl.PluginCompatibilityRestServiceImpl.java

/**
 * upload a file in user's space. send file inside a form
 *///  w  w w.  j a  v  a 2 s. c o  m
@POST
@Path("/document/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Override
public DocumentDto uploadfile(@Multipart(value = "file") InputStream theFile,
        @Multipart(value = "description", required = false) String description,
        @Multipart(value = "filename", required = false) String givenFileName, MultipartBody body)
        throws BusinessException {
    User actor = webServiceDocumentFacade.checkAuthentication();
    String fileName;
    String comment = (description == null) ? "" : description;

    if ((actor instanceof Guest && !actor.getCanUpload())) {
        throw giveRestException(HttpStatus.SC_FORBIDDEN, "You are not authorized to use this service");
    }
    if (theFile == null) {
        throw giveRestException(HttpStatus.SC_BAD_REQUEST, "Missing file (check parameter file)");
    }
    if (givenFileName == null || givenFileName.isEmpty()) {
        // parameter givenFileName is optional
        // so need to search this information in the header of the
        // attachement (with id file)
        fileName = body.getAttachment("file").getContentDisposition().getParameter("filename");
    } else {
        fileName = givenFileName;
    }

    try {
        byte[] bytes = fileName.getBytes("ISO-8859-1");
        fileName = new String(bytes, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        logger.error("Can not encode file name " + e1.getMessage());
    }

    // comment can not be null ?
    return webServiceDocumentFacade.uploadfile(theFile, fileName, comment);
}

From source file:org.linagora.linshare.webservice.interceptor.IllegalArgumentExceptionMapper.java

@Override
public Response toResponse(IllegalArgumentException exception) {
    logger.error("A IllegalArgumentException was caught : " + exception.getLocalizedMessage());
    logger.debug("Stacktrace: ", exception);

    ErrorDto errorDto = new ErrorDto(BusinessErrorCode.WEBSERVICE_FAULT.getCode(),
            " : " + exception.getMessage());
    ResponseBuilder response = Response.status(HttpStatus.SC_BAD_REQUEST);
    response.entity(errorDto);/* w w w .  j a v a2s . c  om*/
    return response.build();
}

From source file:org.linagora.linshare.webservice.interceptor.JsonParseExceptionMapper.java

@Override
public Response toResponse(JsonParseException exception) {
    logger.error("A non validate json format exception was caught : " + exception.getLocalizedMessage() + ". ",
            exception);/*from w  w w.  j  a  v  a 2 s .co  m*/
    ErrorDto errorDto = new ErrorDto(BusinessErrorCode.WEBSERVICE_BAD_REQUEST.getCode(),
            "You have an error in your json : " + exception.getClass().toString() + " : "
                    + exception.getMessage());
    ResponseBuilder response = Response.status(HttpStatus.SC_BAD_REQUEST);
    response.entity(errorDto);
    return response.build();
}

From source file:org.linagora.linshare.webservice.interceptor.UnrecognizedPropertyExceptionMapper.java

@Override
public Response toResponse(UnrecognizedPropertyException exception) {
    logger.error("An unrecognized field excpetion was caught : " + exception.getLocalizedMessage() + ". ",
            exception);// w  w  w.jav  a 2  s . c  o  m
    ErrorDto errorDto = new ErrorDto(BusinessErrorCode.WEBSERVICE_BAD_REQUEST.getCode(),
            "You have an unrecognized field in your json : " + exception.getClass().toString() + " : "
                    + exception.getMessage());
    ResponseBuilder response = Response.status(HttpStatus.SC_BAD_REQUEST);
    response.entity(errorDto);
    return response.build();
}