Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.kagilum.plugins.icescrum.IceScrumSession.java

private boolean executeMethod(GetMethod method, int expectedCode) {
    boolean result = false;
    try {//from www  .ja  v  a 2 s.  co  m
        setAuthentication();
        method.setRequestHeader("accept", "application/json");
        client.executeMethod(method);
        int code = method.getStatusCode();
        if (code != HttpStatus.SC_OK && (expectedCode != 0 && expectedCode != code)) {
            checkServerStatus(code);
        } else {
            body = IOUtils.toString(method.getResponseBodyAsStream());
            result = true;
        }
    } catch (IOException e) {
        httpError = e.getMessage();
        LOGGER.log(Level.WARNING, httpError, e);
    } finally {
        method.releaseConnection();
    }
    return result;
}

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

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

    final IdProof assertion;
    {/*w  w  w .  j ava2 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:com.thoughtworks.go.server.service.materials.PackageRepositoryServiceTest.java

@Test
public void shouldSavePackageRepositoryAndReturnSuccess() throws Exception {
    service = spy(service);/*ww w  .  j a va 2s .c  o m*/
    PackageRepository packageRepository = new PackageRepository();
    packageRepository.setId("repoid");
    Username username = new Username(new CaseInsensitiveString("user"));
    UpdateConfigFromUI updateConfigFromUI = mock(UpdateConfigFromUI.class);

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

    when(goConfigService.updateConfigFromUI(eq(updateConfigFromUI), eq("md5"), eq(username),
            any(LocalizedOperationResult.class))).then(new Answer<ConfigUpdateResponse>() {
                @Override
                public ConfigUpdateResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
                    return new ConfigUpdateResponse(null, null, null, mock(ConfigAwareUpdate.class),
                            ConfigSaveState.UPDATED);
                }
            });

    when(localizer.localize("SAVED_CONFIGURATION_SUCCESSFULLY")).thenReturn("SAVED_CONFIGURATION_SUCCESSFULLY");

    ConfigUpdateAjaxResponse response = service.savePackageRepositoryToConfig(packageRepository, "md5",
            username);
    assertThat(response.isSuccessful(), is(true));
    assertThat(response.getMessage(), is("SAVED_CONFIGURATION_SUCCESSFULLY"));
    assertThat(response.getSubjectIdentifier(), is("repoid"));
    assertThat(response.getStatusCode(), is(HttpStatus.SC_OK));

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

From source file:com.gm.machine.util.CommonUtils.java

/**
 * /*from  w ww. j  a v a2 s  .  c  o m*/
 * ????
 * 
 * @since 2013-1-12
 * @author qingang
 * @param url
 *            ?????
 * @param remark
 *            
 * @param path
 *            ??
 * @param encoding
 *            ??
 * @throws Exception
 */
public static void createHtmlPage(String url, String remark, String path, String encoding) throws Exception {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod = new PostMethod(url);

    try {
        int returnCode = client.executeMethod(httpMethod);
        if (returnCode == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "ISO-8859-1"));
            String tmp = null;
            StringBuffer htmlRet = new StringBuffer();
            while ((tmp = reader.readLine()) != null) {
                htmlRet.append(tmp + "\n");
            }
            writeHtml(path,
                    Global.HMTLPAGE_CHARSET + new String(htmlRet.toString().getBytes("ISO-8859-1"), encoding),
                    encoding);
            System.out.println("??=====================??" + remark + "===" + url
                    + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                    + "=======================");
        } else if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
        }
    } catch (Exception e) {
        System.err.println(e);
        System.out.println("?=====================??" + remark + "===" + url
                + "===??:" + path + "===?" + getCurrentDate("yyyy-MM-dd HH:mm")
                + "=======================");
        e.printStackTrace();
        throw e;
    } finally {
        httpMethod.releaseConnection();
    }

}

From source file:com.twinsoft.convertigo.engine.util.RemoteAdmin.java

public void login(String username, String password) throws RemoteAdminException, EngineException {
    PostMethod loginMethod = null;//from  ww  w.  ja va  2  s  .c om

    try {
        String loginServiceURL = (bHttps ? "https" : "http") + "://" + serverBaseUrl
                + "/admin/services/engine.Authenticate";

        Protocol myhttps = null;

        hostConfiguration = httpClient.getHostConfiguration();

        if (bHttps) {
            if (bTrustAllCertificates) {
                ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();
                myhttps = new Protocol("https", socketFactory, serverPort);
                Protocol.registerProtocol("https", myhttps);

                hostConfiguration.setHost(host, serverPort, myhttps);
            }
        }

        if (("").equals(username) || username == null) {
            throw new RemoteAdminException(
                    "Unable to connect to the Convertigo server: \"Server administrator\" field is empty.");
        }
        if (("").equals(password) || password == null) {
            throw new RemoteAdminException(
                    "Unable to connect to the Convertigo server: \"Password\" field is empty.");
        }

        URL url = new URL(loginServiceURL);

        HttpState httpState = new HttpState();
        httpClient.setState(httpState);
        // Proxy configuration
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        loginMethod = new PostMethod(loginServiceURL);
        loginMethod.addParameter("authType", "login");
        loginMethod.addParameter("authUserName", username);
        loginMethod.addParameter("authPassword", password);

        int returnCode = httpClient.executeMethod(loginMethod);
        String httpResponse = loginMethod.getResponseBodyAsString();

        if (returnCode == HttpStatus.SC_OK) {
            Document domResponse;
            try {
                DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                domResponse = parser.parse(new InputSource(new StringReader(httpResponse)));
                domResponse.normalize();

                NodeList nodeList = domResponse.getElementsByTagName("error");

                if (nodeList.getLength() != 0) {
                    throw new RemoteAdminException(
                            "Unable to connect to the Convertigo server: wrong username or password.");
                }
            } catch (ParserConfigurationException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: \n"
                        + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            } catch (IOException e) {
                throw new RemoteAdminException(
                        "An unexpected error has occured during the Convertigo server login.\n"
                                + "(IOException) " + e.getMessage() + "\n" + "Received response: "
                                + httpResponse,
                        e);
            } catch (SAXException e) {
                throw new RemoteAdminException("Unable to parse the Convertigo server response: "
                        + e.getMessage() + ".\n" + "Received response: " + httpResponse);
            }
        } else {
            decodeResponseError(httpResponse);
        }
    } catch (HttpException e) {
        throw new RemoteAdminException("An unexpected error has occured during the Convertigo server login.\n"
                + "Cause: " + e.getMessage(), e);
    } catch (UnknownHostException e) {
        throw new RemoteAdminException(
                "Unable to find the Convertigo server (unknown host): " + e.getMessage());
    } catch (IOException e) {
        String message = e.getMessage();

        if (message.indexOf("unable to find valid certification path") != -1) {
            throw new RemoteAdminException(
                    "The SSL certificate of the Convertigo server is not trusted.\nPlease check the 'Trust all certificates' checkbox.");
        } else
            throw new RemoteAdminException(
                    "Unable to reach the Convertigo server: \n" + "(IOException) " + e.getMessage(), e);
    } catch (GeneralSecurityException e) {
        throw new RemoteAdminException(
                "Unable to reach the Convertigo server: \n" + "(GeneralSecurityException) " + e.getMessage(),
                e);
    } finally {
        Protocol.unregisterProtocol("https");
        if (loginMethod != null)
            loginMethod.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 {//from  ww w.  j a v  a  2 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:com._17od.upm.transport.HTTPTransport.java

public void put(String targetLocation, File file, String username, String password) throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "upload.php";

    PostMethod post = new PostMethod(targetLocation);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {/*from  w  w  w.  j  a v  a 2  s.  c  o  m*/

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

public void upload(String artifactName, File file, String description, String repositoryUrl) {
    assertNotNull(artifactName, "artifactName");
    assertNotNull(file, "file");
    assertNotNull(repositoryUrl, "repositoryUrl");
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login),
            new NameValuePair("token", token), new NameValuePair("file_name", artifactName),
            new NameValuePair("file_size", String.valueOf(file.length())),
            new NameValuePair("description", description == null ? "" : description) });

    try {/*from   www  .  j av a  2 s .com*/

        int response = httpClient.executeMethod(githubPost);

        if (response == HttpStatus.SC_OK) {

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class);

            PostMethod s3Post = new PostMethod(GITHUB_S3_URL);

            Part[] parts = { new StringPart("Filename", artifactName),
                    new StringPart("policy", node.path("policy").getTextValue()),
                    new StringPart("success_action_status", "201"),
                    new StringPart("key", node.path("path").getTextValue()),
                    new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()),
                    new StringPart("Content-Type", node.path("mime_type").getTextValue()),
                    new StringPart("signature", node.path("signature").getTextValue()),
                    new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) };

            MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams());
            s3Post.setRequestEntity(partEntity);

            int s3Response = httpClient.executeMethod(s3Post);
            if (s3Response != HttpStatus.SC_CREATED) {
                throw new GithubException(
                        "Cannot upload " + file.getName() + " to repository " + repositoryUrl);
            }

            s3Post.releaseConnection();
        } else if (response == HttpStatus.SC_NOT_FOUND) {
            throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
        } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            throw new GithubArtifactAlreadyExistException(
                    "File " + artifactName + " already exist in " + repositoryUrl + " repository");
        } else {
            throw new GithubException("Error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubPost.releaseConnection();
}

From source file:com.headwire.aem.tooling.intellij.util.BundleStateHelper.java

private static Object doRecalcDecorationState(
        //        IServer server,
        //        IProject project
        ServerConfiguration.Module module) {

    InputStream input = null;//from w w w  .  ja v a 2  s .c  om

    try {
        //            if (!ProjectHelper.isBundleProject(project)) {
        if (!module.isOSGiBundle()) {
            return EMPTY_STATE;
        }
        //            IJavaProject javaProject = ProjectHelper.asJavaProject(project);
        //            String hostname = server.getHost();
        //            int launchpadPort = server.getAttribute(ISlingLaunchpadServer.PROP_PORT, 8080);
        //            if (project.exists() && !javaProject.exists()) {
        //                // then it's not a java project..
        //                return EMPTY_STATE;
        //            }
        //            IPath outputLocation = javaProject.getOutputLocation();
        //            outputLocation = outputLocation.removeFirstSegments(1);
        //            IPath manifestFilePath = outputLocation.append("META-INF/MANIFEST.MF");
        //            IFile manifestFile = project.getVirtualFile(manifestFilePath);
        //AS TODO: This must be the actual OSGi Bundle Symbolic Name -> Support Override
        String bundleName = module.getSymbolicName();
        //            if (manifestFile.exists()) {
        //                Manifest manifest = new Manifest(manifestFile.getContents());
        //                bundlename = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
        //            } else {
        //                String groupId = ProjectHelper.getMavenProperty(project, "groupId");
        //                String artifactId = ProjectHelper.getMavenProperty(project, "artifactId");
        //                if (groupId==null || groupId.isEmpty()) {
        //                    bundlename = artifactId;
        //                } else {
        //                    bundlename = groupId + "." + artifactId;
        //                }
        //            }
        //            String username = server.getAttribute(ISlingLaunchpadServer.PROP_USERNAME, "admin");
        //            String password = server.getAttribute(ISlingLaunchpadServer.PROP_PASSWORD, "admin");
        ServerConfiguration serverConfiguration = module.getParent();
        String bundleStateURL = MessageFormat.format("http://{0}:{1}/system/console/bundles/{2}.json",
                serverConfiguration.getHost(), serverConfiguration.getConnectionPort() + "", bundleName);
        //            GetMethod method = new GetMethod("http://"+hostname+":"+launchpadPort+"/system/console/bundles/"+bundlename+".json");
        GetMethod method = new GetMethod(bundleStateURL);
        int resultCode = getHttpClient(serverConfiguration.getUserName(),
                new String(serverConfiguration.getPassword())).executeMethod(method);
        if (resultCode != HttpStatus.SC_OK) {
            return " [" + resultCode + "]";
        }

        input = method.getResponseBodyAsStream();

        JSONObject result = new JSONObject(new JSONTokener(new InputStreamReader(input)));
        JSONArray dataArray = (JSONArray) result.get("data");
        JSONObject firstElement = (JSONObject) dataArray.get(0);
        return " [" + firstElement.get("state") + "]";
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.thoughtworks.twist.mingle.core.MingleClient.java

public TaskDataList getAllTaskData(String queryUrl) {
    HttpMethod method = getMethod(queryUrl(queryUrl));
    try {//from w  w  w .j a  v a2s  .c o m
        switch (executeMethod(method)) {
        case HttpStatus.SC_OK:
            return new TaskDataList((List) parse(getResponse(method)));
        case HttpStatus.SC_UNAUTHORIZED:
            throw new MingleAuthenticationException(
                    "Could not authenticate user. Check username and password.");
        }
        return new TaskDataList();
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}