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.linagora.linshare.webservice.userv2.impl.ThreadEntryRestServiceImpl.java

@Path("/")
@POST/*from   w  w  w. j a  va  2s .  c  o m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Create a thread entry which will contain the uploaded file.", response = ThreadEntryDto.class)
@ApiResponses({
        @ApiResponse(code = 403, message = "Current logged in account does not have the delegation role."),
        @ApiResponse(code = 404, message = "Owner not found."),
        @ApiResponse(code = 400, message = "Bad request : missing required fields."),
        @ApiResponse(code = 500, message = "Internal server error."), })
@Override
public ThreadEntryDto create(
        @ApiParam(value = "The thread uuid.", required = true) @PathParam("threadUuid") String threadUuid,
        @ApiParam(value = "File stream.", required = true) InputStream theFile,
        @ApiParam(value = "An optional description of a thread entry.") @Multipart(value = "description", required = false) String description,
        @ApiParam(value = "The given file name of the uploaded file.", required = true) @Multipart(value = "filename", required = false) String givenFileName,
        MultipartBody body) throws BusinessException {
    String fileName;

    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;
    }
    return threadEntryFacade.create(threadUuid, theFile, fileName);
}

From source file:org.linagora.linshare.webservice.userv2.impl.WorkGroupEntryRestServiceImpl.java

@Path("/")
@POST//w  w  w  .  j a  v  a2s  .  c  o m
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Create a workgroup 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 = "Workgroup 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 workgroup uuid.", required = true) @PathParam("workGroupUuid") String workGroupUuid,
        @ApiParam(value = "The workgroup folder uuid.", required = false) @QueryParam("workGroupUuid") String workGroupFolderUuid,
        @ApiParam(value = "File stream.", required = true) @Multipart(value = "file", required = true) InputStream file,
        @ApiParam(value = "An optional description of a workgroup entry.") @Multipart(value = "description", required = false) String description,
        @ApiParam(value = "The given file name of the uploaded file.", required = true) @Multipart(value = "filename", required = false) 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 {
    checkMaintenanceMode();
    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-userv2-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 = workGroupEntryFacade.getAuthenticatedAccountDto();
        AsyncTaskDto asyncTask = null;
        try {
            asyncTask = asyncTaskFacade.create(currSize, transfertDuration, fileName, null,
                    AsyncTaskType.THREAD_ENTRY_UPLOAD);
            ThreadEntryTaskContext threadEntryTaskContext = new ThreadEntryTaskContext(actorDto,
                    actorDto.getUuid(), workGroupUuid, tempFile, fileName, workGroupFolderUuid);
            ThreadEntryUploadAsyncTask task = new ThreadEntryUploadAsyncTask(threadEntryAsyncFacade,
                    threadEntryTaskContext, asyncTask);
            taskExecutor.execute(task);
            return new WorkGroupEntryDto(asyncTask, threadEntryTaskContext);
        } catch (Exception e) {
            logAsyncFailure(asyncTask, e);
            throw e;
        } finally {
            deleteTempFile(tempFile);
        }
    } else {
        // TODO : manage transfertDuration
        // Synchronous mode
        try {
            logger.debug("Async mode is not used");
            return workGroupEntryFacade.create(null, workGroupUuid, workGroupFolderUuid, tempFile, fileName);
        } finally {
            deleteTempFile(tempFile);
        }
    }
}

From source file:org.mule.transport.http.functional.HttpMethodTestCase.java

@Test
public void testFoo() throws Exception {
    CustomHttpMethod method = new CustomHttpMethod("FOO", getHttpEndpointAddress());
    int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_BAD_REQUEST, statusCode);
}

From source file:org.nuxeo.ecm.tokenauth.servlet.TokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Don't provide token for anonymous user unless 'allowAnonymous' parameter is explicitly set to true in
    // the authentication plugin configuration
    Principal principal = req.getUserPrincipal();
    if (principal instanceof NuxeoPrincipal && ((NuxeoPrincipal) principal).isAnonymous()) {
        PluggableAuthenticationService authenticationService = (PluggableAuthenticationService) Framework
                .getRuntime().getComponent(PluggableAuthenticationService.NAME);
        AuthenticationPluginDescriptor tokenAuthPluginDesc = authenticationService
                .getDescriptor(TOKEN_AUTH_PLUGIN_NAME);
        if (tokenAuthPluginDesc == null || !(Boolean
                .valueOf(tokenAuthPluginDesc.getParameters().get(TokenAuthenticator.ALLOW_ANONYMOUS_KEY)))) {
            log.debug("Anonymous user is not allowed to acquire an authentication token.");
            resp.sendError(HttpStatus.SC_UNAUTHORIZED);
            return;
        }//from  ww w. j  a v a2s.  co  m

    }

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();

    // Write response
    String response = null;
    int statusCode;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
            statusCode = 201;
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
                statusCode = 400;
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
                statusCode = 202;
            }
        }
        sendTextResponse(resp, response, statusCode);
    } catch (TokenAuthenticationException e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetBlacklists() throws ParseException, IOException {
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().get(rt.host("/blacklists.json"));
    given().queryParam("type", "test").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .get(rt.host("/blacklists.json"));

    // Test type//from w w w .  j  a  va2 s.  c o m
    String responseString = given().queryParam("type", "person").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().get(rt.host("/blacklists.json")).asString();

    JSONArray responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(2, responseJson.size());
    JSONObject blacklist = (JSONObject) responseJson.get(1);
    long id = Long.parseLong(blacklist.get("id").toString());
    Assert.assertEquals(1L, id);
    Assert.assertEquals("2014-05-11T13:24:31Z", blacklist.get("start"));
    Assert.assertEquals("2014-05-11T13:30:00Z", blacklist.get("end"));

    // Test filter by name
    responseString = given().queryParam("type", "person").queryParam("name", "Peter").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().get(rt.host("/blacklists.json")).asString();
    responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(0, responseJson.size());

    responseString = given().queryParam("type", "person").queryParam("name", "Hans").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().get(rt.host("/blacklists.json")).asString();
    responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(2, responseJson.size());

    // Test limit offset
    responseString = given().queryParam("type", "person").queryParam("name", "Hans").queryParam("limit", 1)
            .queryParam("offset", 1).log().all().expect().statusCode(HttpStatus.SC_OK).when()
            .get(rt.host("/blacklists.json")).asString();
    responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(1, responseJson.size());
    blacklist = (JSONObject) responseJson.get(0);
    id = Long.parseLong(blacklist.get("id").toString());
    Assert.assertEquals(1L, id);

    // Test order
    responseString = given().queryParam("type", "person").queryParam("name", "Hans").queryParam("limit", 1)
            .queryParam("offset", 1).queryParam("sort", "PERIOD_DESC").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().get(rt.host("/blacklists.json")).asString();
    responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(1, responseJson.size());
    blacklist = (JSONObject) responseJson.get(0);
    id = Long.parseLong(blacklist.get("id").toString());
    Assert.assertEquals(2L, id);

    responseString = given().queryParam("type", "person").queryParam("name", "Hans").queryParam("limit", 0)
            .queryParam("offset", 0).queryParam("sort", "PERIOD_DESC").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().get(rt.host("/blacklists.json")).asString();
    responseJson = (JSONArray) parser.parse(responseString);
    Assert.assertEquals(2, responseJson.size());
    blacklist = (JSONObject) responseJson.get(0);
    id = Long.parseLong(blacklist.get("id").toString());
    Assert.assertEquals(1L, id);
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountInputNoParamsExpectsBadRequest() {
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().get(rt.host("/blacklistCount"));
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountInputInvalidTypeExpectsBadRequest() {
    given().log().all().queryParam("blacklistedId", validRoomBlackListedId).queryParam("type", "Invalid Type")
            .queryParam("start", DateTimeSupport.toUTC(TestBlacklistEndpoint.START_DATE.getTime()))
            .queryParam("end", DateTimeSupport.toUTC(TestBlacklistEndpoint.END_DATE.getTime())).expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().get(rt.host("/blacklistCount"));
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountInputInvalidStartDateExpectsBadRequest() {
    given().log().all().queryParam("blacklistedId", validRoomBlackListedId).queryParam("type", Room.TYPE)
            .queryParam("start", "Invalid start date")
            .queryParam("end", DateTimeSupport.toUTC(TestBlacklistEndpoint.END_DATE.getTime())).expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().get(rt.host("/blacklistCount"));
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountInputInvalidEndDateExpectsBadRequest() {
    given().log().all().queryParam("blacklistedId", validRoomBlackListedId).queryParam("type", Room.TYPE)
            .queryParam("start", DateTimeSupport.toUTC(TestBlacklistEndpoint.START_DATE.getTime()))
            .queryParam("end", "Not a valid end date").expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .get(rt.host("/blacklistCount"));
}

From source file:org.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountsInputNoParamsExpectsBadRequest() {
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().get(rt.host("/blacklistCounts"));
}