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.braindrainpain.docker.DockerRepository.java

/**
 * Call the Docker API.//from   ww w.j a  v a 2s .c om
 * 
 * @param packageConfiguration
 * @return 
 */
private JsonObject allTags(final PackageConfiguration packageConfiguration) {
    JsonObject result = null;
    HttpClient client = super.getHttpClient();

    String repository = MessageFormat.format(DockerAPI.V1.getUrl(),
            repositoryConfiguration.get(Constants.REGISTRY).getValue(),
            packageConfiguration.get(Constants.REPOSITORY).getValue());

    try {
        GetMethod get = new GetMethod(repository);
        if (client.executeMethod(get) == HttpStatus.SC_OK) {
            String jsonString = get.getResponseBodyAsString();
            LOG.info("RECIEVED: " + jsonString);
            result = (JsonObject) new JsonParser().parse(jsonString);
        }
    } catch (IOException e) {
        // Wrap into a runtime. There is nothing useful to do here
        // when this happens.
        throw new RuntimeException("Cannot fetch the tags from " + repository, e);
    }

    return result;
}

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

public Set<String> listAvailableDownloads(String repositoryUrl) {
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    final Set<String> downloads = new HashSet<String>();
    final GetMethod githubGet = new GetMethod(toRepositoryDownloadUrl(repositoryUrl));

    int response;

    try {/*w  w  w. j  av  a  2  s.  c o  m*/

        response = httpClient.executeMethod(githubGet);
    } catch (IOException e) {
        throw new GithubRepositoryNotFoundException(
                "Cannot retrieve github repository " + repositoryUrl + " informations", e);
    }

    if (response == HttpStatus.SC_OK) {

        String githubResponse;

        try {

            githubResponse = githubGet.getResponseBodyAsString();
        } catch (IOException e) {
            throw new GithubRepositoryNotFoundException(
                    "Cannot retrieve github repository " + repositoryUrl + "  informations", e);
        }

        Pattern pattern = Pattern.compile(
                String.format("<a href=\"/downloads%s/?([^\"]+)\"", removeGithubUrlPart(repositoryUrl)));

        Matcher matcher = pattern.matcher(githubResponse);
        while (matcher.find()) {
            downloads.add(matcher.group(1));
        }

    } else if (response == HttpStatus.SC_NOT_FOUND) {
        throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
    } else {
        throw new GithubRepositoryNotFoundException(
                "Cannot retrieve github repository " + repositoryUrl + " informations");
    }

    githubGet.releaseConnection();

    return downloads;
}

From source file:com.zimbra.cs.store.triton.TritonIncomingBlob.java

@Override
protected long getRemoteSize() throws IOException {
    outStream.flush();/* ww w.java  2 s  .  com*/
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HeadMethod head = new HeadMethod(baseUrl + uploadUrl);
    ZimbraLog.store.info("heading %s", head.getURI());
    try {
        head.addRequestHeader(TritonHeaders.SERVER_TOKEN, serverToken.getToken());
        int statusCode = HttpClientUtil.executeMethod(client, head);
        if (statusCode == HttpStatus.SC_OK) {
            String contentLength = head.getResponseHeader(TritonHeaders.CONTENT_LENGTH).getValue();
            long remoteSize = -1;
            try {
                remoteSize = Long.valueOf(contentLength);
            } catch (NumberFormatException nfe) {
                throw new IOException("Content length can't be parsed to Long", nfe);
            }
            return remoteSize;
        } else {
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    head.getResponseBodyAsString());
            throw new IOException("unable to head blob " + statusCode + ":" + head.getStatusText(), null);
        }
    } finally {
        head.releaseConnection();
    }
}

From source file:com.baifendian.swordfish.webserver.controller.LoginController.java

/**
 * @param name ??/*w ww .  ja  v a2s .c  o  m*/
 * @param email  email
 * @param password ?
 * @param request ?
 * @param response ?
 */
@RequestMapping(value = "", method = { RequestMethod.POST, RequestMethod.GET })
public UserSessionDto login(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "password") String password, HttpServletRequest request,
        HttpServletResponse response) {
    logger.info("Login, user name: {}, email: {}, password: {}", name, email, "******");

    // 
    if (StringUtils.isEmpty(name) && StringUtils.isEmpty(email)) {
        throw new ParameterException("name or email");
    }

    // 
    if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(email)) {
        throw new ParameterException("name or email");
    }

    //  ip ?
    String ip = HttpUtil.getClientIpAddress(request);
    if (StringUtils.isEmpty(ip)) {
        throw new ParameterException("ip");
    }

    // ?????
    User user = userService.queryUser(name, email, password);

    if (user == null) {
        throw new UnAuthorizedException("User password error");
    }

    //  session
    UserSessionDto data = sessionService.createSession(user, ip);

    if (data == null) {
        throw new UnAuthorizedException("Create session error");
    }

    response.setStatus(HttpStatus.SC_OK);
    response.addCookie(new Cookie("sessionId", data.getSessionId()));

    return data;
}

From source file:net.sf.sail.webapp.dao.sds.impl.SdsOfferingGetCommandHttpRestImpl.java

/**
 * @see net.sf.sail.webapp.dao.sds.SdsCommand#generateRequest()
 *///from  w  ww . ja v a  2s .c om
public HttpGetRequest generateRequest() {
    final SdsOffering sdsOffering = this.getSdsOffering();
    final String url = "/offering/" + sdsOffering.getSdsObjectId();
    return new HttpGetRequest(REQUEST_HEADERS_ACCEPT, EMPTY_STRING_MAP, url, HttpStatus.SC_OK);
}

From source file:com.glaf.core.util.http.CommonsHttpClientUtils.java

/**
 * ??POST/*from  w  w  w . j av a2  s . c om*/
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doPost(String url, String encoding, Map<String, String> dataMap) {
    PostMethod method = null;
    String content = null;
    try {
        method = new PostMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding);
        if (dataMap != null && !dataMap.isEmpty()) {
            NameValuePair[] nameValues = new NameValuePair[dataMap.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues[i] = new NameValuePair(name, value);
                i++;
            }
            method.setRequestBody(nameValues);
        }
        HttpClient client = new HttpClient();
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            content = method.getResponseBodyAsString();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
            method = null;
        }
    }
    return content;
}

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

private MingleClient clientWithCards() {
    MingleClient mingleClient = new TestMingleClient("http://localhost:30001/projects/foobar", "ketan", "ketan",
            HttpStatus.SC_OK) {
        @Override// ww w .j a va2 s  .  c o  m
        protected Reader getResponse(HttpMethod method) {
            return new StringReader("<cards>\n" + "        <card>\n" + "                <number>1</number>\n"
                    + "                <name>Hello World Task</name>\n"
                    + "                <description>This card says hello world</description>\n"
                    + "                <someAttribute>attrib1</someAttribute>\n"
                    + "                <someAttribute1>attrib2</someAttribute1>\n" + "        </card>\n"
                    + "        <card>\n" + "                <number>id2</number>\n"
                    + "                <name>name2</name>\n"
                    + "                <description>description2</description>\n" + "        </card>\n"
                    + "</cards>\n");
        }
    };
    return mingleClient;
}

From source file:com.zimbra.cs.store.http.HttpStoreManager.java

@Override
public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    GetMethod get = new GetMethod(getGetUrl(mbox, locator));
    int statusCode = HttpClientUtil.executeMethod(client, get);
    if (statusCode == HttpStatus.SC_OK) {
        return new UserServlet.HttpInputStream(get);
    } else {//from  w w w. j a v a 2 s .c  o m
        get.releaseConnection();
        throw new IOException("unexpected return code during blob GET: " + get.getStatusText());
    }
}

From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java

private Map<String, String> login() throws HttpException, IOException {
    StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT)
            .append(ACHttpPropertiesConstant.HTTP_SESSION_CONTROL_URL);
    postMethod = new PostMethod(sb.toString());

    postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE);

    StringRequestEntity requestEntity = new StringRequestEntity(
            ACHttpBodyUtil.buildLoginRequestBody(USER_ID, PASSWORD), null,
            ACHttpPropertiesConstant.HTTP_CHARSET);
    postMethod.setRequestEntity(requestEntity);

    int statusCode = client.executeMethod(postMethod);

    assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode);

    return ACHttpBodyUtil.buildParameterMap(postMethod.getResponseBodyAsStream(),
            ACHttpPropertiesConstant.HTTP_CHARSET);
}

From source file:com.cerema.cloud2.lib.resources.status.GetRemoteStatusOperation.java

private boolean tryConnection(OwnCloudClient client) {
    boolean retval = false;
    GetMethod get = null;//from   w  w w.  j  ava  2  s.  c  o m
    String baseUrlSt = client.getBaseUri().toString();
    try {
        get = new GetMethod(baseUrlSt + AccountUtils.STATUS_PATH);

        HttpParams params = get.getParams().getDefaultParams();
        params.setParameter(HttpMethodParams.USER_AGENT, OwnCloudClientManagerFactory.getUserAgent());
        get.getParams().setDefaults(params);

        client.setFollowRedirects(false);
        boolean isRedirectToNonSecureConnection = false;
        int status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
        mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                get.getResponseHeaders());

        String redirectedLocation = mLatestResult.getRedirectedLocation();
        while (redirectedLocation != null && redirectedLocation.length() > 0 && !mLatestResult.isSuccess()) {

            isRedirectToNonSecureConnection |= (baseUrlSt.startsWith("https://")
                    && redirectedLocation.startsWith("http://"));
            get.releaseConnection();
            get = new GetMethod(redirectedLocation);
            status = client.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
            mLatestResult = new RemoteOperationResult((status == HttpStatus.SC_OK), status,
                    get.getResponseHeaders());
            redirectedLocation = mLatestResult.getRedirectedLocation();
        }

        String response = get.getResponseBodyAsString();
        if (status == HttpStatus.SC_OK) {
            JSONObject json = new JSONObject(response);
            if (!json.getBoolean(NODE_INSTALLED)) {
                mLatestResult = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            } else {
                String version = json.getString(NODE_VERSION);
                OwnCloudVersion ocVersion = new OwnCloudVersion(version);
                if (!ocVersion.isVersionValid()) {
                    mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);

                } else {
                    // success
                    if (isRedirectToNonSecureConnection) {
                        mLatestResult = new RemoteOperationResult(
                                RemoteOperationResult.ResultCode.OK_REDIRECT_TO_NON_SECURE_CONNECTION);
                    } else {
                        mLatestResult = new RemoteOperationResult(
                                baseUrlSt.startsWith("https://") ? RemoteOperationResult.ResultCode.OK_SSL
                                        : RemoteOperationResult.ResultCode.OK_NO_SSL);
                    }

                    ArrayList<Object> data = new ArrayList<Object>();
                    data.add(ocVersion);
                    mLatestResult.setData(data);
                    retval = true;
                }
            }

        } else {
            mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (JSONException e) {
        mLatestResult = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);

    } catch (Exception e) {
        mLatestResult = new RemoteOperationResult(e);

    } finally {
        if (get != null)
            get.releaseConnection();
    }

    if (mLatestResult.isSuccess()) {
        Log_OC.i(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());

    } else if (mLatestResult.getException() != null) {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage(),
                mLatestResult.getException());

    } else {
        Log_OC.e(TAG, "Connection check at " + baseUrlSt + ": " + mLatestResult.getLogMessage());
    }

    return retval;
}