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.opencastproject.adminui.endpoint.BlacklistsEndpointTest.java

@Test
public void testGetEventsCountsInputInvalidTypeExpectsBadRequest() {
    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("/blacklistCounts"));
}

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

@Test
public void testGetEventsCountsInputInvalidStartDateExpectsBadRequest() {
    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("/blacklistCounts"));
}

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

@Test
public void testGetEventsCountsInputInvalidEndDateExpectsBadRequest() {
    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("/blacklistCounts"));
}

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

@Test
public void testPostBlacklist() throws ParseException, IOException {
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host("/"));
    given().formParam("start", "123").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host("/"));
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "test").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host("/"));
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 0).log().all().expect()
            .statusCode(HttpStatus.SC_NOT_FOUND).when().post(rt.host("/"));
    // Start time after end time should be a bad request.
    given().formParam("start", "2016-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 5).log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host("/")).asString();
    String responseString = given().formParam("start", "2014-05-11T13:35:20Z")
            .formParam("end", "2014-05-11T13:40:00Z").formParam("type", "person").formParam("blacklistedId", 5)
            .log().all().expect().statusCode(HttpStatus.SC_CREATED).when().post(rt.host("/")).asString();

    JSONObject responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);/*from   ww  w.  ja v a 2s  .  c  o m*/
    long id = Long.parseLong(responseJson.get("id").toString());
    Assert.assertEquals(27L, id);
    Assert.assertEquals("2014-05-11T13:35:20Z", responseJson.get("start"));
    Assert.assertEquals("2014-05-11T13:40:00Z", responseJson.get("end"));

    responseString = given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedId", 7).log().all().expect()
            .statusCode(HttpStatus.SC_CREATED).when().post(rt.host("/")).asString();

    responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);
    id = Long.parseLong(responseJson.get("id").toString());
    Assert.assertEquals(27L, id);
    Assert.assertEquals("2014-05-11T13:35:20Z", responseJson.get("start"));
    Assert.assertEquals("2014-05-11T13:40:00Z", responseJson.get("end"));
}

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

@Test
public void testPostBlacklists() throws ParseException, IOException {
    String path = "/blacklists";
    // Empty parameters
    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host(path));
    // Bad start//from w  ww. j ava  2  s  .c  o  m
    given().formParam("start", "123").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host(path));
    // Bad end
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "123").log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host(path));
    // Bad type
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "test").log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(rt.host(path));
    // Just a number, not a JSON array
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedIds", 0).log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host(path));
    // A JSON Object instead of a JSON Array
    given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedIds", "{'1' : '1'}").log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host(path));
    // Start time after end time results in bad request
    given().formParam("start", "2016-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedIds", "[0, 5]").log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host(path)).asString();

    String responseString = given().formParam("start", "2014-05-11T13:35:20Z")
            .formParam("end", "2014-05-11T13:40:00Z").formParam("type", "person")
            .formParam("blacklistedIds", "[0, 5]").log().all().expect().statusCode(HttpStatus.SC_OK).when()
            .post(rt.host(path)).asString();

    System.out.println(responseString);

    JSONObject responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);
    JSONArray ok = (JSONArray) responseJson.get("ok");
    Assert.assertEquals(1, ok.size());
    Assert.assertEquals("5", ok.get(0));

    JSONArray notFound = (JSONArray) responseJson.get("notFound");
    Assert.assertEquals(1, notFound.size());
    Assert.assertEquals("0", notFound.get(0));

    responseString = given().formParam("start", "2014-05-11T13:35:20Z").formParam("end", "2014-05-11T13:40:00Z")
            .formParam("type", "person").formParam("blacklistedIds", "[0,7]").log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().post(rt.host(path)).asString();

    responseJson = (JSONObject) parser.parse(responseString);
    Assert.assertNotNull(responseJson);

    ok = (JSONArray) responseJson.get("ok");
    Assert.assertEquals(1, ok.size());
    Assert.assertEquals("7", ok.get(0));

    notFound = (JSONArray) responseJson.get("notFound");
    Assert.assertEquals(1, notFound.size());
    Assert.assertEquals("0", notFound.get(0));
}

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

@Test
public void testPutPeriod() throws ParseException {
    given().pathParam("periodId", 0).log().all().expect().statusCode(HttpStatus.SC_NOT_FOUND).when()
            .put(rt.host("/{periodId}"));

    String start = "2000-05-11T13:35:20Z";
    String end = "2014-05-11T13:35:20Z";
    String purpose = "Under construction";
    String comment = "A comment about the current period.";

    // Make sure that you cannot update a period with a later start time than the end time.
    given().pathParam("periodId", 1).formParam("start", end).formParam("end", start)
            .formParam("purpose", purpose).formParam("comment", comment).log().all().expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().put(rt.host("/{periodId}")).asString();

    String periodResponse = given().pathParam("periodId", 1).formParam("start", start).formParam("end", end)
            .formParam("purpose", purpose).formParam("comment", comment).log().all().expect()
            .statusCode(HttpStatus.SC_OK).when().put(rt.host("/{periodId}")).asString();
    JSONObject period = (JSONObject) parser.parse(periodResponse);
    long id = (Long) period.get("id");
    Assert.assertEquals(1L, id);//  www  .  j ava  2  s  .co  m
    Assert.assertEquals(start, period.get("start"));
    Assert.assertEquals(end, period.get("end"));
    Assert.assertEquals(purpose, period.get("purpose"));
    Assert.assertEquals(comment, period.get("comment"));
}

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

@Test
public void testDeleteTemplates() {
    BulkOperationResult emptyResult = new BulkOperationResult();

    BulkOperationResult normalResult = new BulkOperationResult();
    normalResult.addOk(Long.toString(1L));
    normalResult.addOk(Long.toString(2L));
    normalResult.addOk(Long.toString(3L));
    normalResult.addNotFound(Long.toString(4L));

    BulkOperationResult allNotFound = new BulkOperationResult();
    allNotFound.addNotFound(Long.toString(1L));
    allNotFound.addNotFound(Long.toString(2L));
    allNotFound.addNotFound(Long.toString(3L));
    allNotFound.addNotFound(Long.toString(4L));

    given().log().all().expect().statusCode(HttpStatus.SC_BAD_REQUEST).when().post(rt.host("/deleteTemplates"));

    String result = given().body("[]").log().all().expect().statusCode(HttpStatus.SC_OK).when()
            .post(rt.host("/deleteTemplates")).asString();
    assertEquals(emptyResult.toJson(), result);

    result = given().body("[\"1\",\"2\",\"3\",\"4\"]").log().all().expect().statusCode(HttpStatus.SC_OK).when()
            .post(rt.host("/deleteTemplates")).asString();
    assertEquals(normalResult.toJson(), result);
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Send a command to the Particle REST API (convenience function).
 *
 * @param device//from  w w w  . j a  v  a  2 s. c  o m
 *            the device context, or <code>null</code> if not needed for this command.
 * @param funcName
 *            the function name to call, or variable/field to retrieve if <code>command</code> is
 *            <code>null</code>.
 * @param user
 *            the user name to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param pass
 *            the password to use in Basic Authentication if the funcName would require Basic Authentication.
 * @param command
 *            the command to send to the API.
 * @param proc
 *            a callback object that receives the status code and response body, or <code>null</code> if not
 *            needed.
 */
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command,
        HttpResponseHandler proc) {
    String url = null;
    String httpMethod = null;
    String content = null;
    String contentType = null;
    Properties headers = new Properties();
    logger.trace("sendCommand: funcName={}", funcName);

    switch (funcName) {
    case "createToken":
        httpMethod = HTTP_POST;
        url = TOKEN_URL;
        content = command;
        contentType = APPLICATION_FORM_URLENCODED;
        break;
    case "deleteToken":
        httpMethod = HTTP_DELETE;
        url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
        break;
    case "getDevices":
        httpMethod = HTTP_GET;
        url = String.format(GET_DEVICES_URL, tokens.accessToken);
        break;
    default:
        url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
        if (command == null) {
            // retrieve a variable
            httpMethod = HTTP_GET;
        } else {
            // call a function
            httpMethod = HTTP_POST;
            content = command;
            contentType = APPLICATION_JSON;
        }
        break;
    }

    HttpClient client = new HttpClient();

    // Only perform basic authentication when we aren't using OAuth

    if (!url.contains("access_token=")) {
        Credentials credentials = new UsernamePasswordCredentials(user, pass);
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    HttpMethod method = createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (String httpHeaderKey : headers.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
        logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
    }

    try {
        // add content if a valid method is given ...
        if (method instanceof EntityEnclosingMethod && content != null) {
            EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
            eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
            logger.trace("content='{}', contentType='{}'", content, contentType);
        }

        if (logger.isDebugEnabled()) {
            try {
                logger.debug("About to execute '{}'", method.getURI());
            } catch (URIException e) {
                logger.debug(e.getMessage());
            }
        }

        int statusCode = client.executeMethod(method);
        if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
            logger.debug("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug("Body of response: {}", responseBody);
        }

        if (proc != null) {
            proc.handleResponse(statusCode, responseBody);
        }
    } catch (HttpException he) {
        logger.warn("{}", he);
    } catch (IOException ioe) {
        logger.debug("{}", ioe);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.openo.gso.roa.impl.DrivermgrRoaModuleImplTest.java

/**
 * test create gso network service<br>
 * fail3: response status is 400, bad request
 * @since  GSO 0.5//from   w w  w  .j a va2 s  .  c  o  m
 */
@Test
public void testCreateGSONsFail3() {
    // get request
    mockGetRequestBody(FILE_PATH + "createGsoNsReq.json");
    // get service template
    ServiceTemplate svcTmpl = new ServiceTemplate();
    svcTmpl.setCsarId("csarId");
    svcTmpl.setServiceTemplateId("svcTmplId");
    new MockUp<CatalogProxyImpl>() {
        @Mock
        public ServiceTemplate getSvcTmplByNodeType(String nodeType, String domainHost) {
            return svcTmpl;
        }
    };
    // get response
    RestfulResponse restRsp = new RestfulResponse();
    restRsp.setStatus(HttpStatus.SC_BAD_REQUEST);
    restRsp.setResponseJson(getJsonString(FILE_PATH + "createGsoNsRsp.json"));
    mockGetRestfulRsp(restRsp);
    // insert data
    new MockUp<ServiceSegmentDaoImpl>() {
        @Mock
        public void insertSegment(ServiceSegmentModel serviceSegment) {
            // do nothing
        }

        @Mock
        public void insertSegmentOper(ServiceSegmentOperation svcSegmentOper) {
            // do nothing
        }

        @Mock
        public void updateSegmentOper(ServiceSegmentOperation svcSegmentOper) {
            // do nothing
        }
    };
    try {
        Response rsp = impl.createGsoNs(servletReq);
    } catch (ApplicationException e) {
        Assert.assertNotNull(e);
    }
}

From source file:org.openo.gso.roa.impl.DrivermgrRoaModuleImplTest.java

/**
 * test delete gso network service<br>
 * fail1: response status is 400, bad request
 * @since  GSO 0.5/*from w w  w.ja v  a2 s . co m*/
 */
@Test
public void testDeleteGSONsFail1() {
    // get request
    mockGetRequestBody(FILE_PATH + "deleteGsoNsReq.json");
    // get response
    RestfulResponse restRsp = new RestfulResponse();
    restRsp.setStatus(HttpStatus.SC_BAD_REQUEST);
    restRsp.setResponseJson(getJsonString(FILE_PATH + "deleteGsoNsRsp.json"));
    mockGetRestfulRsp(restRsp);
    // update data
    new MockUp<ServiceSegmentDaoImpl>() {
        @Mock
        public void updateSegmentOper(ServiceSegmentOperation svcSegmentOper) {
            // do nothing
        }
    };
    try {
        Response rsp = impl.deleteGsoNs(servletReq);
    } catch (ApplicationException e) {
        Assert.assertNotNull(e);
    }

}