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:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java

public ActionForward deleteFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final GenericApplication application = getDomainObject(request, "applicationExternalId");
    final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
    final GenericApplicationFile file = getDomainObject(request, "fileExternalId");
    if (application != null && confirmationCode != null && application.getConfirmationCode() != null
            && application.getConfirmationCode().equals(confirmationCode) && file != null
            && file.getGenericApplication() == application) {
        file.deleteFromApplication();/*from  w  w  w .j a v  a2 s .co  m*/
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return confirmEmail(mapping, form, request, response);
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

@Test
public void testBadPostToSchedulingOutbox() throws Exception {
    Account dav1 = users[1].create();/* w  w  w.  j a va 2 s. co m*/
    Account dav2 = users[2].create();
    Account dav3 = users[3].create();
    String url = getSchedulingOutboxUrl(dav2, dav2);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    addBasicAuthHeaderForUser(method, dav2);
    method.addRequestHeader("Content-Type", "text/calendar");
    method.addRequestHeader("Originator", "mailto:" + dav2.getName());
    method.addRequestHeader("Recipient", "mailto:" + dav3.getName());

    method.setRequestEntity(new ByteArrayRequestEntity(exampleCancelIcal(dav1, dav2, dav3).getBytes(),
            MimeConstants.CT_TEXT_CALENDAR));

    HttpMethodExecutor.execute(client, method, HttpStatus.SC_BAD_REQUEST);
}

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

private static ResponseStatus loadURLToFile(String urlStr, File file, int maxFileSizeMb) {
    ResponseStatus responseStatus = new ResponseStatus();

    URI uri = null;/*from  w w  w . j a v a  2s.c  o  m*/
    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);
    HttpEntity entity = null;
    InputStream in = null;
    FileOutputStream out = null;

    try {
        // Java DOC:
        //     http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/index.html
        //     http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html
        // Example: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e37
        HttpResponse response = httpClient.execute(httpGet);

        StatusLine httpStatus = response.getStatusLine();
        if (httpStatus != null) {
            responseStatus.setStatusCode(httpStatus.getStatusCode());
        }

        // The entity is streamed
        entity = response.getEntity();
        if (entity != null) {
            long contentSizeMb = entity.getContentLength() / (1024 * 1024); // in megabytes
            // long value can go over 8 millions terabytes

            if (contentSizeMb < maxFileSizeMb) {
                in = entity.getContent();
                out = new FileOutputStream(file);
                // The file size may be unknown on the server. This method stop streaming when the file size reach the limit.
                Utils.binaryCopy(in, out, maxFileSizeMb * (1024 * 1024));
            } else {
                LOGGER.log(Level.WARNING,
                        "File size exceeded for URL {0}\n"
                                + "      File size is {1} Mb, expected less than {2} Mb.",
                        new Object[] { urlStr, entity.getContentLength(), maxFileSizeMb });
                responseStatus.setErrorMessage("File size exceeded. File size is " + entity.getContentLength()
                        + " Mb, expected less than " + maxFileSizeMb + " Mb.");
            }
        }
    } catch (IOException ex) {
        // An error occur while writing the file. It's not reliable. It's better to delete it.
        if (file != null && file.exists()) {
            file.delete();
        }
        responseStatus.setErrorMessage(getErrorMessage(ex));
    } finally {
        if (httpGet != null) {
            // Cancel the connection, if it's still alive
            httpGet.abort();
            // Close connections
            httpGet.reset();
        }
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Error occur while closing the URL: {0}",
                        Utils.getExceptionMessage(e));
                LOGGER.log(Level.FINE, "Stack trace:", e);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Error occur while closing the file: {0}",
                        Utils.getExceptionMessage(e));
                LOGGER.log(Level.FINE, "Stack trace:", e);
            }
        }
    }

    return responseStatus;
}

From source file:davmail.exchange.ews.EWSMethod.java

/**
 * Check method success./*from w w w .  ja v  a 2 s .com*/
 *
 * @throws EWSException on error
 */
public void checkSuccess() throws EWSException {
    if (errorDetail != null) {
        if (!"ErrorAccessDenied".equals(errorDetail) && !"ErrorMailRecipientNotFound".equals(errorDetail)
                && !"ErrorItemNotFound".equals(errorDetail)) {
            try {
                throw new EWSException(errorDetail + " " + ((errorDescription != null) ? errorDescription : "")
                        + "\n request: " + new String(generateSoapEnvelope(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new EWSException(e.getMessage());
            }
        }
    }
    if (getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        throw new EWSException(getStatusText());
    }
}

From source file:edu.psu.iam.cpr.core.util.Utility.java

/**
 * This method is used to convert an CPR status code to an analogous HTTP status code.
 *
 * @param statusCode contains the CPR status code.
 * @return will return the HTTP status code.
 *///www .j  a v a2s.c  o m
public static int convertCprReturnToHttpStatus(final int statusCode) {

    final ReturnType returnType = ReturnType.get(statusCode);
    int httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;

    switch (returnType) {
    case SUCCESS:
        httpStatus = HttpStatus.SC_OK;
        break;
    case ADD_FAILED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case ALREADY_DELETED_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case RECORD_NOT_FOUND_EXCEPTION:
        httpStatus = HttpStatus.SC_NOT_FOUND;
        break;
    case ARCHIVE_FAILED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case NOT_SPECIFIED_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case TYPE_NOT_FOUND_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case INVALID_PARAMETERS_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case YN_PARAMETERS_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case GENERAL_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case PARAMETER_LENGTH_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case MESSAGE_CREATION_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case MESSAGE_INITIALIZATION_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case MESSAGE_SEND_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case NOT_AUTHORIZED_EXCEPTION:
        httpStatus = HttpStatus.SC_UNAUTHORIZED;
        break;
    case PERSON_NOT_ACTIVE_EXCEPTION:
        httpStatus = HttpStatus.SC_BAD_REQUEST;
        break;
    case PERSON_NOT_FOUND_EXCEPTION:
        httpStatus = HttpStatus.SC_NOT_FOUND;
        break;
    case PSUID_NOT_FOUND_EXCEPTION:
        httpStatus = HttpStatus.SC_NOT_FOUND;
        break;
    case SERVICE_AUTHENTICATION_EXCEPTION:
        httpStatus = HttpStatus.SC_UNAUTHORIZED;
        break;
    case SET_PRIMARY_FAILED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case UPDATE_FAILED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case WEB_SERVICE_NOT_FOUND_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case GI_FAILURE:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case DB_CONNECTION_FAILURE:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case GENERAL_DATABASE_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case UNARCHIVE_FAILED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case DATA_CHANGE_EXCEPTION:
        httpStatus = HttpStatus.SC_UNAUTHORIZED;
        break;
    case SECURITY_OPERATION_EXCEPTION:
        httpStatus = HttpStatus.SC_UNAUTHORIZED;
        break;
    case AFFILIATION_USE_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case IAP_USE_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case RECORD_ALREADY_EXISTS:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case EXACT_MATCH_EXCEPTION:
        httpStatus = HttpStatus.SC_MULTIPLE_CHOICES;
        break;
    case NEAR_MATCH_EXCEPTION:
        httpStatus = HttpStatus.SC_MULTIPLE_CHOICES;
        break;
    case MESSAGE_RECEIVE_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case DIRECTORY_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case JSON_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case JMS_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    case NOT_IMPLEMENTED_EXCEPTION:
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        break;
    default:
        break;
    }
    return httpStatus;
}

From source file:com.motorola.studio.android.localization.translators.GoogleTranslator.java

private static void checkStatusCode(int statusCode, String response) throws HttpException {
    switch (statusCode) {
    case HttpStatus.SC_OK:
        //do nothing
        break;/*from ww w . j a v a  2  s.com*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageExecutingRequest,
                getErrorMessage(response)));

    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);

    case HttpStatus.SC_FORBIDDEN:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageNoValidTranslationReturned,
                getErrorMessage(response)));

    default:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_Error_HTTPRequestError,
                new Object[] { statusCode, getErrorMessage(response) }));

    }
}

From source file:davmail.caldav.CaldavConnection.java

/**
 * Send 400 bad response for unsupported request.
 *
 * @param request Caldav request/*from w  w w.  j ava 2 s.  c o  m*/
 * @throws IOException on error
 */
public void sendUnsupported(CaldavRequest request) throws IOException {
    BundleMessage message = new BundleMessage("LOG_UNSUPPORTED_REQUEST", request);
    DavGatewayTray.error(message);
    sendErr(HttpStatus.SC_BAD_REQUEST, message.format());
}

From source file:no.norrs.launchpad.tasks.LaunchpadRepository.java

private Task[] processEndpoint(String url, HttpClient client) throws IOException {
    GetMethod method = new GetMethod(url);
    configureHttpMethod(method);/*www . j a v  a2 s .c o m*/
    client.executeMethod(method);

    int code = method.getStatusCode();
    if (code != HttpStatus.SC_OK) {
        throw new IOException(code == HttpStatus.SC_BAD_REQUEST ? method.getResponseBodyAsString()
                : ("HTTP " + code + " (" + HttpStatus.getStatusText(code) + ") " + method.getStatusText()));
    }

    BugTask bugTask = mapper.readValue(method.getResponseBodyAsStream(), BugTask.class);
    List<Bug> bugs = bugTask.getEntries();
    List<Task> tasks = new ArrayList<Task>();
    for (Bug bug : bugs) {
        tasks.add(new LaunchpadTask(bug));
    }
    LOG.debug(String.format("Tasks size: %s", tasks.size()));

    return tasks.toArray(new Task[] {});
}

From source file:org.alfresco.dropbox.webscripts.Node.java

protected List<NodeRef> parseNodeRefs(final WebScriptRequest req) {
    final List<NodeRef> result = new ArrayList<NodeRef>();
    Content content = req.getContent();/*from w  w  w . ja  v  a2s  . c  o m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODE_REFS)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODE_REFS + " is missing from JSON: " + jsonStr);
        }

        JSONArray nodeRefs = json.getJSONArray(JSON_KEY_NODE_REFS);

        for (int i = 0; i < nodeRefs.length(); i++) {
            NodeRef nodeRef = new NodeRef(nodeRefs.getString(i));
            result.add(nodeRef);
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                "Unable to retrieve nodeRefs from JSON '" + jsonStr + "'.", e);
    }

    return (result);
}

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

private AccessGrant refreshAccessToken()
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    log.debug("Refreshing Access Token for " + AuthenticationUtil.getRunAsUser());
    OAuth2CredentialsInfo credentialInfo = oauth2CredentialsStoreService
            .getPersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM);

    if (credentialInfo.getOAuthRefreshToken() != null) {

        AccessGrant accessGrant = null;//from  w  w w  . j  ava  2 s  . c  o  m
        try {

            accessGrant = connectionFactory.getOAuthOperations()
                    .refreshAccess(credentialInfo.getOAuthRefreshToken(), GoogleDocsConstants.SCOPE, null);
        } catch (HttpClientErrorException hcee) {
            if (hcee.getStatusCode().value() == HttpStatus.SC_BAD_REQUEST) {
                throw new GoogleDocsAuthenticationException(hcee.getMessage());
            } else if (hcee.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) {
                throw new GoogleDocsAuthenticationException("Token Refresh Failed.");
            } else {
                throw new GoogleDocsServiceException(hcee.getMessage(), hcee.getStatusCode().value());
            }

        }

        if (accessGrant != null) {
            Date expiresIn = null;

            if (accessGrant.getExpireTime() != null) {
                if (accessGrant.getExpireTime() > 0L) {
                    expiresIn = new Date(new Date().getTime() + accessGrant.getExpireTime());
                }
            }

            try {
                oauth2CredentialsStoreService.storePersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM,
                        accessGrant.getAccessToken(), credentialInfo.getOAuthRefreshToken(), expiresIn,
                        new Date());
            } catch (NoSuchSystemException nsse) {
                throw nsse;
            }
        } else {
            throw new GoogleDocsAuthenticationException("No Access Grant Returned.");
        }

        log.debug("Access Token Refreshed");
        return accessGrant;

    } else {
        throw new GoogleDocsRefreshTokenException(
                "No Refresh Token Provided for " + AuthenticationUtil.getRunAsUser());
    }
}