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.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);//ww w  .ja  v a2  s.c  om

    try {
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult.java

public void connectionError(Localizable message) {
    this.message = message;
    httpCode = HttpStatus.SC_BAD_REQUEST;
}

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

/**
 * Test registerUser with Invalid User.//from ww  w.j  av  a 2 s.c om
 */
@Test
public void ifUserInvalidThenFailRegistration() {
    final UserAccount newUser = new UserAccount();
    newUser.setFirstName("Test");
    newUser.setPermissions(new LinkedHashSet<Permission>());
    newUser.setCreated(new Date());
    newUser.setUpdated(new Date());

    given().contentType(ContentType.JSON).body(newUser).expect().statusCode(HttpStatus.SC_BAD_REQUEST).when()
            .post(RestApiTest.URL_ROOT + "/user/register/");
}

From source file:com.bbva.arq.devops.ae.mirrorgate.jenkins.plugin.utils.RestCall.java

public MirrorGateResponse makeRestCallGet(String url, String user, String password) {
    MirrorGateResponse response;//from  w ww. j ava  2s.  c  o m
    GetMethod get = new GetMethod(url);
    try {
        HttpClient client = getHttpClient();

        if (user != null && password != null) {
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            get.setDoAuthentication(true);
        }

        get.getParams().setContentCharset("UTF-8");
        int responseCode = client.executeMethod(get);
        String responseString = get.getResponseBodyAsStream() != null
                ? getResponseString(get.getResponseBodyAsStream())
                : "";
        response = new MirrorGateResponse(responseCode, responseString);
    } catch (HttpException e) {
        LOGGER.log(Level.WARNING, "Error connecting to MirrorGate", e);
        response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Error connecting to MirrorGate", e);
        response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
    } finally {
        get.releaseConnection();
    }
    return response;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.commons.student.ViewStudentApplicationDA.java

public ActionForward downloadDocument(final ActionMapping mapping, final ActionForm form,
        final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    final IndividualCandidacyDocumentFile document = getDomainObject(request, "documentOID");
    if (document != null && isAuthorized(document)) {
        response.setContentType(document.getContentType());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + document.getFilename() + "\"");
        response.setContentLength(document.getSize().intValue());
        final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
        dos.write(document.getContent());
        dos.close();/*  w w  w .  j a  v a  2  s.c o m*/
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return null;
}

From source file:com.moss.bdbadmin.openejb.BdbAdminOpenEjbAdapter.java

public void onMessage(final HttpRequest request, final HttpResponse response) throws Exception {

    final IdProof assertion;
    {/*  w ww  .j a v  a 2  s  .c o m*/
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (request.getURI().getPath().length() >= contextPath.length()) {
            path = request.getURI().getPath().substring(contextPath.length()).trim();
        } else {
            path = request.getURI().getPath();
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            service.clearDb(assertion, db);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod().name())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatusCode(HttpStatus.SC_OK);
                            } else {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.ExecutionCourseDA.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    final String executionCourseIDString = request.getParameter("executionCourseID");

    ExecutionCourse executionCourse = null;
    if (executionCourseIDString != null) {
        final DomainObject object = FenixFramework.getDomainObject(executionCourseIDString);
        if (object instanceof ExecutionCourse) {
            executionCourse = (ExecutionCourse) object;
        } else {/*from ww w .j a  va 2 s.  c o m*/
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
            response.getWriter().close();
            return null;
        }
    } else {
        ExecutionCourseSite site = SiteMapper.getSite(request);
        executionCourse = site.getSiteExecutionCourse();
    }

    OldCmsSemanticURLHandler.selectSite(request, executionCourse.getSite());
    request.setAttribute("executionCourse", executionCourse);
    request.setAttribute("executionCourseID", executionCourse.getExternalId());

    return super.execute(mapping, actionForm, request, response);
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

/** Run method of the thread */
public void run() {

    queue = manager.workQueue;//from   ww w .j  av a2s .c o  m
    while (manager.hasWorkLeft()) {

        working = false;
        // code to make the worker pause, if the pause button has been presed

        // if the stop signal has been given stop the thread
        if (stop) {
            return;
        }

        // this pauses the thread
        synchronized (this) {
            while (pleaseWait) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        HttpMethodBase httpMethod = null;

        try {

            work = (WorkUnit) queue.take();
            working = true;
            url = work.getWork();
            int code = 0;

            String response = "";
            String rawResponse = "";

            httpMethod = createHttpMethod(work.getMethod(), url.toString());

            // if the work is a head request
            if (work.getMethod().equalsIgnoreCase("HEAD")) {
                code = makeRequest(httpMethod);
                httpMethod.releaseConnection();

            }
            // if we are doing a get request
            else if (work.getMethod().equalsIgnoreCase("GET")) {
                code = makeRequest(httpMethod);

                String rawHeader = getHeadersAsString(httpMethod);
                response = getResponseAsString(httpMethod);

                rawResponse = rawHeader + response;
                // clean the response

                if (Config.parseHTML && !work.getBaseCaseObj().isUseRegexInstead()) {
                    parseHtml(httpMethod, response);
                }

                response = FilterResponce.CleanResponce(response, work);

                Thread.sleep(10);
                httpMethod.releaseConnection();
            }

            // if we need to check the against the base case
            if (work.getMethod().equalsIgnoreCase("GET") && work.getBaseCaseObj().useContentAnalysisMode()) {
                if (code == HttpStatus.SC_OK) {
                    verifyResponseForValidRequests(code, response, rawResponse);
                } else if (code == HttpStatus.SC_NOT_FOUND || code == HttpStatus.SC_BAD_REQUEST) {
                    if (Config.debug) {
                        System.out
                                .println("DEBUG Worker[" + threadId + "]: " + code + " for: " + url.toString());
                    }
                } else {
                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }
            }
            /*
             * use the custom regex check instead
             */
            else if (work.getBaseCaseObj().isUseRegexInstead()) {
                Pattern regexFindFile = Pattern.compile(work.getBaseCaseObj().getRegex());

                Matcher m = regexFindFile.matcher(rawResponse);

                if (m.find()) {
                    // do nothing as we have a 404
                    if (Config.debug) {
                        System.out.println("DEBUG Worker[" + threadId + "]: Regex matched so it's a 404, "
                                + url.toString());
                    }

                } else {
                    if (Config.parseHTML) {
                        parseHtml(httpMethod, rawResponse);
                    }

                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }

            }
            // just check the response code
            else {
                // if is not the fail code, a 404 or a 400 then we have a possible
                if (code != work.getBaseCaseObj().getFailCode() && verifyIfCodeIsValid(code)) {
                    if (work.getMethod().equalsIgnoreCase("HEAD")) {
                        httpMethod = createHttpMethod("GET", url.toString());
                        int newCode = makeRequest(httpMethod);

                        // in some cases the second get can return a different result, than the
                        // first head request!
                        if (newCode != code) {
                            manager.foundError(url,
                                    "Return code for first HEAD, is different to the second GET: " + code
                                            + " - " + newCode);
                        }

                        // build a string version of the headers
                        rawResponse = getHeadersAsString(httpMethod);

                        if (httpMethod.getResponseContentLength() > 0) {

                            String responseBodyAsString = getResponseAsString(httpMethod);
                            rawResponse = rawResponse + responseBodyAsString;

                            if (Config.parseHTML) {
                                parseHtml(httpMethod, responseBodyAsString);
                            }
                        }

                        httpMethod.releaseConnection();
                    }

                    if (work.isDir()) {
                        manager.foundDir(url, code, rawResponse, work.getBaseCaseObj());
                    } else {
                        manager.foundFile(url, code, rawResponse, work.getBaseCaseObj());
                    }
                }
            }

            manager.workDone();
            Thread.sleep(20);

        } catch (NoHttpResponseException e) {
            manager.foundError(url, "NoHttpResponseException " + e.getMessage());
            manager.workDone();
        } catch (ConnectTimeoutException e) {
            manager.foundError(url, "ConnectTimeoutException " + e.getMessage());
            manager.workDone();
        } catch (URIException e) {
            manager.foundError(url, "URIException " + e.getMessage());
            manager.workDone();
        } catch (IOException e) {

            manager.foundError(url, "IOException " + e.getMessage());
            manager.workDone();
        } catch (InterruptedException e) {
            // manager.foundError(url, "InterruptedException " + e.getMessage());
            manager.workDone();
            return;
        } catch (IllegalArgumentException e) {

            e.printStackTrace();
            manager.foundError(url, "IllegalArgumentException " + e.getMessage());
            manager.workDone();
        } finally {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
}

From source file:com.cloud.cluster.ClusterServiceServletHttpHandler.java

protected void handleRequest(HttpRequest req, HttpResponse response) {
    String method = (String) req.getParams().getParameter("method");

    int nMethod = RemoteMethodConstants.METHOD_UNKNOWN;
    String responseContent = null;
    try {/*w  w  w.  ja v a2  s. c  om*/
        if (method != null) {
            nMethod = Integer.parseInt(method);
        }

        switch (nMethod) {
        case RemoteMethodConstants.METHOD_DELIVER_PDU:
            responseContent = handleDeliverPduMethodCall(req);
            break;

        case RemoteMethodConstants.METHOD_PING:
            responseContent = handlePingMethodCall(req);
            break;

        case RemoteMethodConstants.METHOD_UNKNOWN:
        default:
            assert (false);
            s_logger.error("unrecognized method " + nMethod);
            break;
        }
    } catch (Throwable e) {
        s_logger.error("Unexpected exception when processing cluster service request : ", e);
    }

    if (responseContent != null) {
        if (s_logger.isTraceEnabled())
            s_logger.trace("Write reponse with HTTP OK " + responseContent);

        writeResponse(response, HttpStatus.SC_OK, responseContent);
    } else {
        if (s_logger.isTraceEnabled())
            s_logger.trace("Write reponse with HTTP Bad request");

        writeResponse(response, HttpStatus.SC_BAD_REQUEST, null);
    }
}

From source file:edu.unc.lib.dl.admin.controller.MODSController.java

/**
 * Retrieves the MD_DESCRIPTIVE datastream, containing MODS, for this item if one is present. If it is not present,
 * then returns a blank MODS document.//from  ww w .  jav  a  2  s. com
 *
 * @param idPrefix
 * @param id
 * @return
 */
@RequestMapping(value = "{pid}/mods", method = RequestMethod.GET)
public @ResponseBody String getMods(@PathVariable("pid") String pid) {
    String mods = null;
    String dataUrl = swordUrl + "em/" + pid + "/" + ContentModelHelper.Datastream.MD_DESCRIPTIVE;

    HttpClient client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
    client.getParams().setAuthenticationPreemptive(true);
    GetMethod method = new GetMethod(dataUrl);

    // Pass the users groups along with the request
    AccessGroupSet groups = GroupsThreadStore.getGroups();
    method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, groups.joinAccessGroups(";"));

    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            try {
                mods = method.getResponseBodyAsString();
            } catch (IOException e) {
                log.info("Problem uploading MODS for " + pid + ": " + e.getMessage());
            } finally {
                method.releaseConnection();
            }
        } else {
            if (method.getStatusCode() == HttpStatus.SC_BAD_REQUEST
                    || method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                // Ensure that the object actually exists
                PID existingPID = tripleStoreQueryService.verify(new PID(pid));
                if (existingPID != null) {
                    // MODS doesn't exist, so pass back an empty record.
                    mods = "<mods:mods xmlns:mods=\"http://www.loc.gov/mods/v3\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></mods:mods>";
                } else {
                    throw new Exception(
                            "Unable to retrieve MODS.  Object " + pid + " does not exist in the repository.");
                }
            } else {
                throw new Exception("Failure to retrieve fedora content due to response of: "
                        + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
            }
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    }
    return mods;
}