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.broadleafcommerce.core.web.api.BroadleafSpringRestExceptionMapper.java

@ExceptionHandler(MissingServletRequestParameterException.class)
public @ResponseBody ErrorWrapper handleMissingServletRequestParameterException(HttpServletRequest request,
        HttpServletResponse response, Exception ex) {
    ErrorWrapper errorWrapper = (ErrorWrapper) context.getBean(ErrorWrapper.class.getName());
    Locale locale = null;/*from   w w w .  j a  va 2s  .  co  m*/
    String parameterType = null;
    String parameterName = null;
    BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext();
    if (requestContext != null) {
        locale = requestContext.getJavaLocale();
    }
    if (ex instanceof MissingServletRequestParameterException) {
        MissingServletRequestParameterException castedException = (MissingServletRequestParameterException) ex;
        parameterType = castedException.getParameterType();
        parameterName = castedException.getParameterName();
    }

    LOG.error("An error occured invoking a REST service", ex);
    if (locale == null) {
        locale = Locale.getDefault();
    }
    if (parameterType == null) {
        parameterType = "String";
    }
    if (parameterName == null) {
        parameterName = "[unknown name]";
    }
    errorWrapper.setHttpStatusCode(HttpStatus.SC_BAD_REQUEST);
    response.setStatus(resolveResponseStatusCode(ex, errorWrapper));
    ErrorMessageWrapper errorMessageWrapper = (ErrorMessageWrapper) context
            .getBean(ErrorMessageWrapper.class.getName());
    errorMessageWrapper
            .setMessageKey(resolveClientMessageKey(BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT));
    errorMessageWrapper
            .setMessage(messageSource.getMessage(BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT,
                    new String[] { parameterType, parameterName },
                    BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT, locale));
    errorWrapper.getMessages().add(errorMessageWrapper);

    return errorWrapper;
}

From source file:org.carrot2.source.boss.BossSearchService.java

/**
 * Sends a search query to Yahoo! and parses the result.
 *//*from w w  w. jav  a2  s  . c  om*/
protected final SearchEngineResponse query(String query, int start, int results) throws IOException {
    results = Math.min(results, metadata.resultsPerPage);

    final ArrayList<NameValuePair> params = createRequestParams(query, start, results);
    params.add(new NameValuePair("appid", appid));
    params.add(new NameValuePair("start", Integer.toString(start)));
    params.add(new NameValuePair("count", Integer.toString(results)));
    params.add(new NameValuePair("format", "xml"));
    params.add(new NameValuePair("sites", sites));

    if (languageAndRegion != null) {
        try {
            params.add(new NameValuePair("lang", languageAndRegion.langCode));
            params.add(new NameValuePair("region", languageAndRegion.regionCode));
        } catch (IllegalArgumentException e) {
            throw new IOException("Language value: " + languageAndRegion);
        }
    }

    final String serviceURI = substituteAttributes(getServiceURI(), new NameValuePair("query", query));

    final HttpUtils.Response response = HttpUtils.doGET(serviceURI, params,
            Arrays.asList(new Header[] { HttpHeaders.USER_AGENT_HEADER_MOZILLA }));

    final int statusCode = response.status;

    if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
            || statusCode == HttpStatus.SC_BAD_REQUEST) {
        // Parse the data stream.
        final SearchEngineResponse ser = parseResponseXML(response.getPayloadAsStream());
        ser.metadata.put(SearchEngineResponse.COMPRESSION_KEY, response.compression);

        if (logger.isDebugEnabled()) {
            logger.debug("Received, results: " + ser.results.size() + ", total: " + ser.getResultsTotal());
        }

        return ser;
    } else {
        // Read the output and throw an exception.
        final String m = "BOSS returned HTTP Error: " + statusCode + ", HTTP payload: "
                + new String(response.payload, "iso8859-1");
        logger.warn(m);
        throw new IOException(m);
    }
}

From source file:org.carrot2.source.yahoo.YahooSearchService.java

/**
 * Sends a search query to Yahoo! and parses the result.
 *//*from  w w w  .  j av a2 s.c  o m*/
protected final SearchEngineResponse query(String query, int start, int results) throws IOException {
    // Yahoo's results start from 1.
    start++;
    results = Math.min(results, metadata.resultsPerPage);

    final ArrayList<NameValuePair> params = createRequestParams(query, start, results);
    params.add(new NameValuePair("output", "xml"));

    final HttpUtils.Response response = HttpUtils.doGET(getServiceURI(), params,
            Arrays.asList(new Header[] { HttpHeaders.USER_AGENT_HEADER_MOZILLA }));

    final int statusCode = response.status;
    if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
            || statusCode == HttpStatus.SC_BAD_REQUEST) {
        // Parse the data stream.
        final SearchEngineResponse ser = parseResponseXML(response.getPayloadAsStream());
        ser.metadata.put(SearchEngineResponse.COMPRESSION_KEY, response.compression);

        if (logger.isDebugEnabled()) {
            logger.debug("Received, results: " + ser.results.size() + ", total: " + ser.getResultsTotal()
                    + ", first: " + ser.metadata.get(FIRST_INDEX_KEY));
        }

        return ser;
    } else {
        // Read the output and throw an exception.
        final String m = "Yahoo returned HTTP Error: " + statusCode + ", HTTP payload: "
                + new String(response.payload, "iso8859-1");
        logger.warn(m);
        throw new IOException(m);
    }
}

From source file:org.dspace.submit.lookup.CiNiiService.java

/**
 * Get metadata by searching CiNii RDF API with CiNii NAID
 *
 *///ww  w  . jav a  2  s . co  m
private Record search(String id, String appId) throws IOException, HttpException {
    GetMethod method = null;
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        method = new GetMethod("http://ci.nii.ac.jp/naid/" + id + ".rdf?appid=" + appId);
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii RDF is not valid");
            else
                throw new RuntimeException("CiNii RDF Http call failed: " + method.getStatusLine());
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder db = factory.newDocumentBuilder();
            Document inDoc = db.parse(method.getResponseBodyAsStream());

            Element xmlRoot = inDoc.getDocumentElement();

            return CiNiiUtils.convertCiNiiDomToRecord(xmlRoot);
        } catch (Exception e) {
            throw new RuntimeException("CiNii RDF identifier is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.dspace.submit.lookup.CiNiiService.java

/**
 * Get CiNii NAIDs by searching CiNii OpenURL API with title, author and year
 *
 *//*from   w  ww  . j av  a2 s . co m*/
private List<String> getCiNiiIDs(String title, String author, int year, int maxResults, String appId)
        throws IOException, HttpException {
    // Need at least one query term
    if (title == null && author == null && year == -1) {
        return null;
    }

    GetMethod method = null;
    List<String> ids = new ArrayList<String>();
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        StringBuilder query = new StringBuilder();
        query.append("format=rss&appid=").append(appId).append("&count=").append(maxResults);
        if (title != null) {
            query.append("&title=").append(URLEncoder.encode(title, "UTF-8"));
        }
        if (author != null) {
            query.append("&author=").append(URLEncoder.encode(author, "UTF-8"));
        }
        if (year != -1) {
            query.append("&year_from=").append(String.valueOf(year));
            query.append("&year_to=").append(String.valueOf(year));
        }
        method = new GetMethod("http://ci.nii.ac.jp/opensearch/search?" + query.toString());
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii OpenSearch query is not valid");
            else
                throw new RuntimeException("CiNii OpenSearch call failed: " + method.getStatusLine());
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder db = factory.newDocumentBuilder();
            Document inDoc = db.parse(method.getResponseBodyAsStream());

            Element xmlRoot = inDoc.getDocumentElement();
            List<Element> items = XMLUtils.getElementList(xmlRoot, "item");

            int url_len = "http://ci.nii.ac.jp/naid/".length();
            for (Element item : items) {
                String about = item.getAttribute("rdf:about");
                if (about.length() > url_len) {
                    ids.add(about.substring(url_len));
                }
            }

            return ids;
        } catch (Exception e) {
            throw new RuntimeException("CiNii OpenSearch results is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.eclipse.andmore.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.  jav  a2 s .c  o  m*/
    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:org.eclipse.lyo.testsuite.oslcv2.CreationAndUpdateBaseTests.java

protected void updateCreatedResourceWithInvalidContent(String contentType, String accept, String content,
        String invalidContent) throws IOException {
    HttpResponse resp = createResource(contentType, accept, content);
    Header location = getRequiredLocationHeader(resp);
    Header eTag = resp.getFirstHeader("ETag");
    Header lastModified = resp.getFirstHeader("Last-Modified");

    // Ignore ETag and Last-Modified for these tests
    int size = headers.length;
    if (eTag != null)
        size++;//from w w w .  j  a v  a 2 s  .c om
    if (lastModified != null)
        size++;
    Header[] putHeaders = new Header[size];
    int i = 0;
    for (; i < headers.length; i++) {
        putHeaders[i] = headers[i];
    }
    if (eTag != null) {
        putHeaders[i++] = new BasicHeader("If-Match", eTag.getValue());
    }
    if (lastModified != null) {
        putHeaders[i++] = new BasicHeader("If-Unmodified-Since", lastModified.getValue());
    }

    // Now, go to the url of the new change request and update it.
    resp = OSLCUtils.putDataToUrl(location.getValue(), basicCreds, accept, contentType, invalidContent,
            putHeaders);
    if (resp.getEntity() != null) {
        EntityUtils.consume(resp.getEntity());
    }
    // Assert that an invalid PUT resulted in a 400 BAD REQUEST
    assertEquals(HttpStatus.SC_BAD_REQUEST, resp.getStatusLine().getStatusCode());

    // Clean up after the test by attempting to delete the created resource
    if (location != null)
        resp = OSLCUtils.deleteFromUrl(location.getValue(), basicCreds, "");

    if (resp != null && resp.getEntity() != null)
        EntityUtils.consume(resp.getEntity());
}

From source file:org.fao.geonet.util.XslUtil.java

/**
 * Returns the HTTP code  or error message if error occurs during URL connection.
 *
 * @param url       The URL to ckeck./*from  ww  w. j  a va  2  s.  co  m*/
 * @param tryNumber the number of remaining tries.
 */
public static String getUrlStatus(String url, int tryNumber) {
    if (tryNumber < 1) {
        // protect against redirect loops
        return "ERR_TOO_MANY_REDIRECTS";
    }
    HttpHead head = new HttpHead(url);
    GeonetHttpRequestFactory requestFactory = ApplicationContextHolder.get()
            .getBean(GeonetHttpRequestFactory.class);
    ClientHttpResponse response = null;
    try {
        response = requestFactory.execute(head, new Function<HttpClientBuilder, Void>() {
            @Nullable
            @Override
            public Void apply(@Nullable HttpClientBuilder originalConfig) {
                RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout(1000)
                        .setConnectionRequestTimeout(3000).setSocketTimeout(5000);
                RequestConfig requestConfig = config.build();
                originalConfig.setDefaultRequestConfig(requestConfig);

                return null;
            }
        });
        //response = requestFactory.execute(head);
        if (response.getRawStatusCode() == HttpStatus.SC_BAD_REQUEST
                || response.getRawStatusCode() == HttpStatus.SC_METHOD_NOT_ALLOWED
                || response.getRawStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            // the website doesn't support HEAD requests. Need to do a GET...
            response.close();
            HttpGet get = new HttpGet(url);
            response = requestFactory.execute(get);
        }

        if (response.getStatusCode().is3xxRedirection() && response.getHeaders().containsKey("Location")) {
            // follow the redirects
            return getUrlStatus(response.getHeaders().getFirst("Location"), tryNumber - 1);
        }

        return String.valueOf(response.getRawStatusCode());
    } catch (IOException e) {
        Log.error(Geonet.GEONETWORK, "IOException validating  " + url + " URL. " + e.getMessage(), e);
        return e.getMessage();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.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) {
        FenixFramework.atomic(() -> file.delete());
    } else {//w w w  .ja v  a  2 s . c o m
        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:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testOWSException() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/EPSG:4326/EPSG:4326:0/0/0/0/0");
    req.addParameter("format", "text/none");

    MockHttpServletResponse resp = dispatch(req);

    assertEquals(HttpStatus.SC_BAD_REQUEST, resp.getStatus());
    assertEquals("text/xml", resp.getContentType());

    Document doc = XMLUnit.buildTestDocument(resp.getContentAsString());
    assertXpathExists("//ows:ExceptionReport/ows:Exception[@exceptionCode='InvalidParameterValue']", doc);
}