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:com.cerema.cloud2.lib.common.operations.RemoteOperationResult.java

public RemoteOperationResult(boolean success, String bodyResponse, int httpCode) {
    mSuccess = success;/*from www. j  av  a2 s.com*/
    mHttpCode = httpCode;

    if (success) {
        mCode = ResultCode.OK;

    } else if (httpCode > 0) {
        switch (httpCode) {
        case HttpStatus.SC_BAD_REQUEST:

            InputStream is = new ByteArrayInputStream(bodyResponse.getBytes());
            InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser();
            try {
                if (xmlParser.parseXMLResponse(is))
                    mCode = ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER;

            } catch (Exception e) {
                mCode = ResultCode.UNHANDLED_HTTP_CODE;
                Log_OC.e(TAG, "Exception reading exception from server", e);
            }
            break;
        default:
            mCode = ResultCode.UNHANDLED_HTTP_CODE;
            Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
        }
    }

}

From source file:net.bryansaunders.jee6divelog.service.rest.UserAccountApiIT.java

/**
 * Test get by username with Invalid Username.
 *//*from   ww  w . j  a  v  a 2 s  . co  m*/
@Test
public void ifCriteriaDoesntMatchThenBadRequest() {
    // given
    final String requestUrl = RestApiTest.URL_ROOT + "/user/find/";
    final UserAccount loggedInUser = this.doLogin(UserAccountApiIT.VALID_EMAIL,
            UserAccountApiIT.VALID_PASSWORD);
    final String privateApiKey = loggedInUser.getPrivateApiKey();
    final String publicApiKey = loggedInUser.getPublicApiKey();

    final Map<String, String> headers = this.generateLoginHeaders(HttpMethod.POST, requestUrl, null,
            privateApiKey, publicApiKey);

    final UserAccount userAccount = new UserAccount();
    userAccount.setEmail("sdf@sdf.com");

    // when
    given().headers(headers).contentType(ContentType.JSON).body(userAccount).expect()
            .statusCode(HttpStatus.SC_BAD_REQUEST).when().post(requestUrl);
}

From source file:com.owncloud.android.lib.test_project.test.GetShareesTest.java

/**
 *  Test get sharees/*from www .  j ava 2 s  .  co  m*/
 * 
 *  Requires OC server 8.2 or later
 */
public void testGetRemoteShareesOperation() {
    Log.v(LOG_TAG, "testGetRemoteSharees in");

    /// successful cases

    // search for sharees including "a"
    GetRemoteShareesOperation getShareesOperation = new GetRemoteShareesOperation("a", 1, 50);
    RemoteOperationResult result = getShareesOperation.execute(mClient);
    JSONObject resultItem;
    JSONObject value;
    int type;
    int userCount = 0, groupCount = 0;
    assertTrue(result.isSuccess() && result.getData().size() > 0);
    try {
        for (int i = 0; i < result.getData().size(); i++) {
            resultItem = (JSONObject) result.getData().get(i);
            value = resultItem.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
            type = value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
            if (type == ShareType.GROUP.getValue()) {
                groupCount++;
            } else {
                userCount++;
            }
        }
        assertTrue(userCount > 0);
        assertTrue(groupCount > 0);
    } catch (JSONException e) {
        AssertionFailedError afe = new AssertionFailedError(e.getLocalizedMessage());
        afe.setStackTrace(e.getStackTrace());
        throw afe;
    }

    // search for sharees including "ad" - expecting user "admin" & group "admin"
    getShareesOperation = new GetRemoteShareesOperation("ad", 1, 50);
    result = getShareesOperation.execute(mClient);
    assertTrue(result.isSuccess() && result.getData().size() == 2);
    userCount = 0;
    groupCount = 0;
    try {
        for (int i = 0; i < 2; i++) {
            resultItem = (JSONObject) result.getData().get(i);
            value = resultItem.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
            type = value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
            if (type == ShareType.GROUP.getValue()) {
                groupCount++;
            } else {
                userCount++;
            }
        }
        assertEquals(userCount, 1);
        assertEquals(groupCount, 1);
    } catch (JSONException e) {
        AssertionFailedError afe = new AssertionFailedError(e.getLocalizedMessage());
        afe.setStackTrace(e.getStackTrace());
        throw afe;
    }

    // search for sharees including "bd" - expecting 0 results
    getShareesOperation = new GetRemoteShareesOperation("bd", 1, 50);
    result = getShareesOperation.execute(mClient);
    assertTrue(result.isSuccess() && result.getData().size() == 0);

    /// failed cases

    // search for sharees including wrong page values
    getShareesOperation = new GetRemoteShareesOperation("a", 0, 50);
    result = getShareesOperation.execute(mClient);
    assertTrue(!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_BAD_REQUEST);

    getShareesOperation = new GetRemoteShareesOperation("a", 1, 0);
    result = getShareesOperation.execute(mClient);
    assertTrue(!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_BAD_REQUEST);
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private void submitHttpRequest(String address, MessageObject mo) throws Exception {
    HttpMethod httpMethod = null;/* www.  j a  v  a  2 s  .c o m*/

    try {
        httpMethod = buildHttpRequest(replacer.replaceValues(address, mo), mo);

        // authentication

        if (connector.isDispatcherUseAuthentication()) {
            List<String> authenticationPreferences = new ArrayList<String>();

            if ("Digest".equalsIgnoreCase(connector.getDispatcherAuthenticationType())) {
                authenticationPreferences.add(AuthPolicy.DIGEST);
                logger.debug("using Digest authentication");
            } else {
                authenticationPreferences.add(AuthPolicy.BASIC);
                logger.debug("using Basic authentication");
            }

            client.getParams().setAuthenticationPreemptive(true);
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authenticationPreferences);
            Credentials credentials = new UsernamePasswordCredentials(
                    replacer.replaceValues(connector.getDispatcherUsername(), mo),
                    replacer.replaceValues(connector.getDispatcherPassword(), mo));
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
            logger.debug("using authentication with credentials: " + credentials);
        }

        client.getParams().setSoTimeout(
                NumberUtils.toInt(replacer.replaceValues(connector.getDispatcherSocketTimeout()), 30000));

        // execute the method
        logger.debug(
                "executing method: type=" + httpMethod.getName() + ", uri=" + httpMethod.getURI().toString());
        int statusCode = client.executeMethod(httpMethod);
        logger.debug("received status code: " + statusCode);

        String response = null;

        if (connector.isDispatcherIncludeHeadersInResponse()) {
            HttpMessageConverter converter = new HttpMessageConverter();
            response = converter.httpResponseToXml(httpMethod.getStatusLine().toString(),
                    httpMethod.getResponseHeaders(), httpMethod.getResponseBodyAsString());
        } else {
            response = httpMethod.getResponseBodyAsString();
        }

        if (statusCode < HttpStatus.SC_BAD_REQUEST) {
            messageObjectController.setSuccess(mo, response, null);

            // send to reply channel
            if ((connector.getDispatcherReplyChannelId() != null)
                    && !connector.getDispatcherReplyChannelId().equals("sink")) {
                new VMRouter().routeMessageByChannelId(connector.getDispatcherReplyChannelId(), response, true);
            }
        } else {
            alertController.sendAlerts(connector.getChannelId(), Constants.ERROR_404,
                    "Received error response from HTTP server.", null);
            messageObjectController.setError(mo, Constants.ERROR_404, response, null, null);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.thoughtworks.go.server.materials.MaterialUpdateServiceTest.java

@Test
public void shouldReturn400WhenTypeIsMissing_WhenInvokingPostCommitHookMaterialUpdate() {
    when(goConfigService.isUserAdmin(username)).thenReturn(true);
    service.notifyMaterialsForUpdate(username, new HashMap(), result);
    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_BAD_REQUEST));
    assertThat(result.hasMessage(), is(true));
    verify(goConfigService).isUserAdmin(username);
}

From source file:com.kodokux.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*from   w w  w . j a v a  2 s. co  m*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        String message = getErrorMessage(method);
        if (message.contains("API rate limit exceeded")) {
            throw new GithubRateLimitExceededException(message);
        }
        throw new GithubAuthenticationException("Request response: " + message);
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:com.thoughtworks.go.server.service.materials.PackageRepositoryServiceTest.java

@Test
public void shouldFailAndReturnReturnFailureResponse() throws Exception {
    service = spy(service);/*  ww  w  . j a  va  2  s . c o  m*/
    Username username = new Username(new CaseInsensitiveString("user"));

    final PackageRepository packageRepository = new PackageRepository();
    packageRepository.errors().add("name", "Name is invalid");

    final CruiseConfig cruiseConfig = GoConfigMother.configWithPipelines("sample");
    cruiseConfig.errors().add("global", "error");

    final UpdateConfigFromUI updateConfigFromUI = mock(UpdateConfigFromUI.class);
    final ConfigAwareUpdate configAwareUpdate = mock(ConfigAwareUpdate.class);

    doNothing().when(service).performPluginValidationsFor(packageRepository);
    doReturn(updateConfigFromUI).when(service).getPackageRepositoryUpdateCommand(packageRepository, username);

    when(configAwareUpdate.configAfter()).thenReturn(cruiseConfig);
    when(goConfigService.updateConfigFromUI(eq(updateConfigFromUI), eq("md5"), eq(username),
            any(LocalizedOperationResult.class))).then(new Answer<ConfigUpdateResponse>() {
                @Override
                public ConfigUpdateResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
                    LocalizedOperationResult result = (LocalizedOperationResult) invocationOnMock
                            .getArguments()[3];
                    result.badRequest(LocalizedMessage.string("BAD_REQUEST"));

                    return new ConfigUpdateResponse(cruiseConfig, cruiseConfig, packageRepository,
                            configAwareUpdate, ConfigSaveState.UPDATED);
                }
            });
    when(localizer.localize("BAD_REQUEST", new Object[] {})).thenReturn("Save Failed");

    ConfigUpdateAjaxResponse response = service.savePackageRepositoryToConfig(packageRepository, "md5",
            username);

    assertThat(response.isSuccessful(), is(false));
    assertThat(response.getMessage(), is("Save Failed"));

    assertThat(response.getFieldErrors().size(), is(1));
    assertThat(response.getFieldErrors().get("package_repository[name]"), is(asList("Name is invalid")));

    assertThat(response.getGlobalErrors().size(), is(1));
    assertThat(response.getGlobalErrors().contains("error"), is(true));

    assertThat(response.getStatusCode(), is(HttpStatus.SC_BAD_REQUEST));

    verify(service).performPluginValidationsFor(packageRepository);
    verify(service).getPackageRepositoryUpdateCommand(packageRepository, username);
}

From source file:au.gov.aims.atlasmapperserver.URLCache.java

public static ResponseStatus getResponseStatus(String urlStr) {
    ResponseStatus responseStatus = new ResponseStatus();

    URI uri = null;//from   w ww  . j  a v a2s . c  om
    try {
        uri = Utils.toURL(urlStr).toURI();
    } catch (Exception ex) {
        responseStatus.setStatusCode(HttpStatus.SC_BAD_REQUEST);
        responseStatus.setErrorMessage("Can not parse the URL: " + urlStr);
        return responseStatus;
    }
    HttpGet httpGet = new HttpGet(uri);

    try {
        HttpResponse response = httpClient.execute(httpGet);

        StatusLine httpStatus = response.getStatusLine();
        if (httpStatus != null) {
            responseStatus.setStatusCode(httpStatus.getStatusCode());
        }
    } catch (IOException ex) {
        responseStatus.setErrorMessage(getErrorMessage(ex));
    } finally {
        if (httpGet != null) {
            // Cancel the connection, if it's still alive
            httpGet.abort();
            // Close connections
            httpGet.reset();
        }
    }

    return responseStatus;
}

From source file:com.thoughtworks.go.server.materials.MaterialUpdateServiceTest.java

@Test
public void shouldReturn400WhenTypeIsInvalid_WhenInvokingPostCommitHookMaterialUpdate() {
    when(goConfigService.isUserAdmin(username)).thenReturn(true);
    when(postCommitHookMaterialType.toType("some_invalid_type")).thenReturn(invalidMaterialType);
    final HashMap params = new HashMap();
    params.put(MaterialUpdateService.TYPE, "some_invalid_type");
    service.notifyMaterialsForUpdate(username, params, result);
    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_BAD_REQUEST));
    assertThat(result.hasMessage(), is(true));
    verify(goConfigService).isUserAdmin(username);
}

From source file:com.owncloud.android.lib.test_project.test.GetShareesTest.java

/**
 *  Test get federated sharees/*from   w  ww.j  av  a  2s .co m*/
 * 
 *  Requires OC server 8.2 or later
 */
public void testGetFederatedShareesOperation() {
    Log.v(LOG_TAG, "testGetFederatedSharees in");

    /// successful cases

    // search for sharees including "@"
    GetRemoteShareesOperation getShareesOperation = new GetRemoteShareesOperation("@", 1, 50);
    RemoteOperationResult result = getShareesOperation.execute(mClient);
    JSONObject resultItem;
    JSONObject value;
    int type;
    int fedCount = 0;
    assertTrue(result.isSuccess() && result.getData().size() > 0);
    try {
        for (int i = 0; i < result.getData().size(); i++) {
            resultItem = (JSONObject) result.getData().get(i);
            value = resultItem.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
            type = value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE);
            if (type == ShareType.FEDERATED.getValue()) {
                fedCount++;
            }
        }
        assertTrue(fedCount > 0);
    } catch (JSONException e) {
        AssertionFailedError afe = new AssertionFailedError(e.getLocalizedMessage());
        afe.setStackTrace(e.getStackTrace());
        throw afe;
    }

    // search for 'admin' sharee from external server - expecting at least 1 result
    String remoteSharee = "admin@" + mServerUri2.split("//")[1];
    getShareesOperation = new GetRemoteShareesOperation(remoteSharee, 1, 50);
    result = getShareesOperation.execute(mClient);
    assertTrue(result.isSuccess() && result.getData().size() > 0);

    /// failed cases

    // search for sharees including wrong page values
    getShareesOperation = new GetRemoteShareesOperation("@", 0, 50);
    result = getShareesOperation.execute(mClient);
    assertTrue(!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_BAD_REQUEST);

    getShareesOperation = new GetRemoteShareesOperation("@", 1, 0);
    result = getShareesOperation.execute(mClient);
    assertTrue(!result.isSuccess() && result.getHttpCode() == HttpStatus.SC_BAD_REQUEST);
}