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

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

Introduction

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

Prototype

int SC_CREATED

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

Click Source Link

Document

<tt>201 Created</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.vmware.aurora.vc.VcFileManager.java

static private void uploadFileWork(String url, boolean isPost, File file, String contentType, String cookie,
        ProgressListener listener) throws Exception {
    EntityEnclosingMethod method;// w  ww .  j av  a 2 s.  c  o  m
    final RequestEntity entity = new ProgressListenerRequestEntity(file, contentType, listener);
    if (isPost) {
        method = new PostMethod(url);
        method.setContentChunked(true);
    } else {
        method = new PutMethod(url);
        method.addRequestHeader("Cookie", cookie);
        method.setContentChunked(false);
        HttpMethodParams params = new HttpMethodParams();
        params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        method.setParams(params);
    }
    method.setRequestEntity(entity);

    logger.info("upload " + file + " to " + url);
    long t1 = System.currentTimeMillis();
    boolean ok = false;
    try {
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(method);
        String response = method.getResponseBodyAsString(100);
        logger.debug("status: " + statusCode + " response: " + response);
        if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw new Exception("Http post failed");
        }
        method.releaseConnection();
        ok = true;
    } finally {
        if (!ok) {
            method.abort();
        }
    }
    long t2 = System.currentTimeMillis();
    logger.info("upload " + file + " done in " + (t2 - t1) + " ms");
}

From source file:com.zimbra.cs.dav.client.CalDavClient.java

public String sendCalendarData(Appointment appt) throws IOException, DavException {
    HttpInputStream resp = sendPut(appt.href, appt.data.getBytes("UTF-8"), MimeConstants.CT_TEXT_CALENDAR,
            appt.etag, null);//from  w  w  w  .  ja  va  2 s .co  m
    String etag = resp.getHeader(DavProtocol.HEADER_ETAG);
    ZimbraLog.dav.debug("ETags: " + appt.etag + ", " + etag);
    int status = resp.getStatusCode();
    if (status != HttpStatus.SC_OK && status != HttpStatus.SC_CREATED && status != HttpStatus.SC_NO_CONTENT) {
        throw new DavException("Can't send calendar data (status=" + status + ")", status);
    }
    if (mSchedulingEnabled)
        sendSchedulingMessage(appt);
    return etag;
}

From source file:com.cloud.network.nicira.NiciraNvpApiTest.java

@Test
public void testCreateSecurityProfile() throws NiciraNvpApiException, IOException {
    // Prepare// w  w w  .j av a2s . c om
    final SecurityProfile inputSecProfile = new SecurityProfile();
    method = mock(PostMethod.class);
    when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
    when(method.getResponseBodyAsString()).thenReturn(SEC_PROFILE_JSON_RESPONSE);

    // Execute
    final SecurityProfile actualSecProfile = api.createSecurityProfile(inputSecProfile);

    // Assert
    verify(method, times(1)).releaseConnection();
    assertEquals("Wrong Uuid in the newly created SecurityProfile", UUID, actualSecProfile.getUuid());
    assertEquals("Wrong Uuid in the newly created SecurityProfile", HREF, actualSecProfile.getHref());
    assertEquals("Wrong Schema in the newly created SecurityProfile", SCHEMA, actualSecProfile.getSchema());
    assertEquals("Wrong URI for SecurityProfile creation REST service", NiciraNvpApi.SEC_PROFILE_URI_PREFIX,
            uri);
    assertEquals("Wrong HTTP method for SecurityProfile creation REST service", NiciraNvpApi.POST_METHOD_TYPE,
            type);
}

From source file:com.cloud.utils.rest.RESTServiceConnector.java

@SuppressWarnings("unchecked")
public <T> T executeCreateObject(final T newObject, final Type returnObjectType, final String uri,
        final Map<String, String> parameters) throws CloudstackRESTException {

    final PostMethod pm = (PostMethod) createMethod(POST_METHOD_TYPE, uri);
    pm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    try {//from   www .j a  va2 s.  c o  m
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), JSON_CONTENT_TYPE, null));
    } catch (final UnsupportedEncodingException e) {
        throw new CloudstackRESTException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_CREATED) {
        final String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to create object : " + errorMessage);
        throw new CloudstackRESTException("Failed to create object : " + errorMessage);
    }

    T result;
    try {
        result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType());
    } catch (final IOException e) {
        throw new CloudstackRESTException("Failed to decode json response body", e);
    } finally {
        pm.releaseConnection();
    }

    return result;
}

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

@Override
public String finishUpload(ExternalUploadedBlob blob) throws IOException, ServiceException {
    TritonBlob tb = (TritonBlob) blob;/*from w w w  .  j ava2  s.  c om*/
    PostMethod post = new PostMethod(url + tb.getUploadId());
    ZimbraLog.store.info("posting to %s with locator %s", post.getURI(), tb.getLocator());
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    try {
        post.addRequestHeader(TritonHeaders.OBJECTID, tb.getLocator());
        post.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
        post.addRequestHeader(TritonHeaders.SERVER_TOKEN, tb.getServerToken().getToken());
        int statusCode = HttpClientUtil.executeMethod(client, post);
        if (statusCode == HttpStatus.SC_CREATED) {
            return tb.getLocator();
        } else {
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            throw ServiceException.FAILURE("unable to store blob " + statusCode + ":" + post.getStatusText(),
                    null);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:cuanto.api.CuantoConnector.java

/**
 * Creates a new TestOutcome for the specified TestRun on the Cuanto server using the details provided.  The ID value on
 * the testOutcome argument will be set upon successful creation.
 *
 * @param testOutcome The TestOutcome to be created on the Cuanto server.
 * @param testRun     The TestRun to which the TestOutcome should be added.
 * @return The server-assigned ID of the TestOutcome.
 *//*from www  .j av  a 2s.c om*/
public Long addTestOutcome(TestOutcome testOutcome, TestRun testRun) {
    PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestOutcome");
    try {
        testOutcome.setTestRun(testRun);
        testOutcome.setProjectKey(this.projectKey);
        post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null));
        int httpStatus = getHttpClient().executeMethod(post);
        if (httpStatus == HttpStatus.SC_CREATED) {
            TestOutcome fetchedOutcome = TestOutcome.fromJSON(getResponseBodyAsString(post));
            testOutcome.setId(fetchedOutcome.getId());
            testOutcome.getTestCase().setId(fetchedOutcome.getTestCase().getId());
            return fetchedOutcome.getId();
        } else {
            throw new RuntimeException("Adding the TestOutcome failed with HTTP status code " + httpStatus
                    + ": \n" + getResponseBodyAsString(post));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing server response", e);
    }
}

From source file:davmail.exchange.dav.ExchangeDavMethod.java

/**
 * Return method http status code.//from  w w w  . ja v a  2  s.  co m
 *
 * @return http status code
 * @throws HttpException on error
 */
public int getResponseStatusCode() throws HttpException {
    String responseDescription = getResponse().getResponseDescription();
    if ("HTTP/1.1 201 Created".equals(responseDescription)) {
        return HttpStatus.SC_CREATED;
    } else {
        return HttpStatus.SC_OK;
    }
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Client call to upload the run back to the originating server.
 * This method does nothing if the run is local.
 * @param runId The id of the run/*from w w  w  . ja va2s .com*/
 * @throws IOException If the upload fails
 */
public static void uploadIfOrigin(String runId) throws IOException {

    // 1. Check origin
    File originFile = new File(
            Config.OUT_DIR + File.separator + runId + File.separator + "META-INF" + File.separator + "origin");

    if (!originFile.isFile())
        return; // Is local run, do nothing.

    String originSpec = readStringFromFile(originFile);
    int idx = originSpec.lastIndexOf('.');
    if (idx == -1) { // This is wrong, we do not accept this.
        logger.severe("Bad origin spec.");
        return;
    }
    idx = originSpec.lastIndexOf('.', idx - 1);
    if (idx == -1) {
        logger.severe("Bad origin spec.");
        return;
    }

    String host = originSpec.substring(0, idx);
    String key = null;
    URL target = null;
    String proxyHost = null;
    int proxyPort = -1;

    // Search the poll hosts for this origin.
    for (int i = 0; i < Config.pollHosts.length; i++) {
        Config.HostInfo pollHost = Config.pollHosts[i];
        if (host.equals(pollHost.name)) {
            key = pollHost.key;
            target = new URL(pollHost.url, "upload");
            proxyHost = pollHost.proxyHost;
            proxyPort = pollHost.proxyPort;
            break;
        }
    }

    if (key == null) {
        logger.severe("Origin host/url/key not found!");
        return;
    }

    // 2. Jar up the run
    String[] files = new File(Config.OUT_DIR, runId).list();
    File jarFile = new File(Config.TMP_DIR, runId + ".jar");
    jar(Config.OUT_DIR + runId, files, jarFile.getAbsolutePath());

    // 3. Upload the run
    ArrayList<Part> params = new ArrayList<Part>();
    //MultipartPostMethod post = new MultipartPostMethod(target.toString());
    params.add(new StringPart("host", Config.FABAN_HOST));
    params.add(new StringPart("key", key));
    params.add(new StringPart("origin", "true"));
    params.add(new FilePart("jarfile", jarFile));
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);
    PostMethod post = new PostMethod(target.toString());
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    if (proxyHost != null)
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status == HttpStatus.SC_FORBIDDEN)
        logger.severe("Server " + host + " denied permission to upload run " + runId + '!');
    else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
        logger.severe("Run " + runId + " origin error!");
    else if (status != HttpStatus.SC_CREATED)
        logger.severe(
                "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
    jarFile.delete();
}

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

/**
 * Run SIS operation against remote server. If a blob already exists for the locator the remote ref count is incremented.
 * @param hash: The content hash of the blob
 * @return true if blob already exists, false if not
 * @throws IOException//from w ww. j av  a2 s . co  m
 * @throws ServiceException
 */
private boolean sisCreate(byte[] hash) throws IOException {
    String locator = getLocator(hash);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(blobApiUrl + locator);
    ZimbraLog.store.info("SIS create URL: %s", post.getURI());
    try {
        post.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
        int statusCode = HttpClientUtil.executeMethod(client, post);
        if (statusCode == HttpStatus.SC_CREATED) {
            return true; //exists, ref count incremented
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            if (emptyLocator.equals(locator)) {
                //empty file
                return true;
            } else {
                return false; //does not exist
            }
        } else if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            //does not exist, probably wrong hash algorithm
            ZimbraLog.store.warn("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            return false;
        } else {
            //unexpected condition
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            throw new IOException("unable to SIS create " + statusCode + ":" + post.getStatusText(), null);
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:de.lemo.apps.restws.client.AnalysisImpl.java

@Override
public String computeQFrequentPathBIDE(final Long lemoUserId, final List<Long> courseIds,
        final List<Long> userIds, final List<String> types, final Long minLength, final Long maxLength,
        final Double minSup, final Boolean sessionWise, final Long startTime, final Long endTime,
        final List<Long> gender) {
    try {//from w w w .  j a  v a  2 s. co m

        if (init.defaultConnectionCheck()) {

            Response response = qFrequentPathBide.compute(lemoUserId, courseIds, userIds, types, minLength,
                    maxLength, minSup, sessionWise, startTime, endTime, gender);

            if (response.getStatus() == HttpStatus.SC_CREATED) {
                logger.debug("BIDE future result created.");

                // return the id of the result for polling
                // TODO use some random path instead of insecure user id
                @SuppressWarnings("unchecked")
                ClientResponse<String> clientResponse = (ClientResponse<String>) response;
                String resultPath = clientResponse.getEntity(String.class);

                // XXX why is this even quoted?
                resultPath = StringUtils.strip(resultPath, "\"");

                return resultPath;
            }
            // TODO do something on failure
            logger.warn("BIDE invalid response: Status code " + response.getStatus());
            return "null";
        }

    } catch (final Exception e) {
        logger.error("Bide failed", e);
    }
    logger.info("Returning empty result set.");
    return "null";
}