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:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder./*from   w ww .j  ava2  s .c o  m*/
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

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

protected void moveMessage(String sourceUrl, String targetFolder) throws IOException {
    String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
    MoveMethod method = new MoveMethod(URIUtil.encodePath(sourceUrl), targetPath, false);
    // allow rename if a message with the same name exists
    method.addRequestHeader("Allow-Rename", "t");
    try {//w  ww. j a  v a2  s  . co  m
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_MOVE_MESSAGE");
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}

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

protected void copyMessage(String sourceUrl, String targetFolder) throws IOException {
    String targetPath = URIUtil.encodePath(getFolderPath(targetFolder)) + '/' + UUID.randomUUID().toString();
    CopyMethod method = new CopyMethod(URIUtil.encodePath(sourceUrl), targetPath, false);
    // allow rename if a message with the same name exists
    method.addRequestHeader("Allow-Rename", "t");
    try {/*from   w  ww  . j  a v a  2 s . c  o  m*/
        int statusCode = httpClient.executeMethod(method);
        if (statusCode == HttpStatus.SC_PRECONDITION_FAILED) {
            throw new DavMailException("EXCEPTION_UNABLE_TO_COPY_MESSAGE");
        } else if (statusCode != HttpStatus.SC_CREATED) {
            throw DavGatewayHttpClientFacade.buildHttpException(method);
        }
    } finally {
        method.releaseConnection();
    }
}

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

@Override
protected void moveToTrash(ExchangeSession.Message message) throws IOException {
    String destination = URIUtil.encodePath(deleteditemsUrl) + '/' + UUID.randomUUID().toString();
    LOGGER.debug("Deleting : " + message.permanentUrl + " to " + destination);
    MoveMethod method = new MoveMethod(encodeAndFixUrl(message.permanentUrl), destination, false);
    method.addRequestHeader("Allow-rename", "t");

    int status = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, method);
    // do not throw error if already deleted
    if (status != HttpStatus.SC_CREATED && status != HttpStatus.SC_NOT_FOUND) {
        throw DavGatewayHttpClientFacade.buildHttpException(method);
    }//  w  ww .  j  a v  a2 s  .  c om
    if (method.getResponseHeader("Location") != null) {
        destination = method.getResponseHeader("Location").getValue();
    }

    LOGGER.debug("Deleted to :" + destination);
}

From source file:org.apache.ambari.funtest.server.tests.RoleBasedAccessControlBasicTest.java

/**
 * Creates a user with cluster administrator privilege and adds a cluster configuration.
 *
 * @throws Exception/*from  w w w .  j av a2 s . c  o m*/
 */
@Test
public void testAddClusterConfigAsClusterAdmin() throws Exception {
    ConnectionParams adminConnectionParams = createAdminConnectionParams();

    String clusterAdminName = "clusterAdmin";
    String clusterAdminPwd = "clusterAdmin";

    /**
     * Create a user with cluster admin role
     */
    ClusterUtils.createUserClusterAdministrator(adminConnectionParams, clusterName, clusterAdminName,
            clusterAdminPwd);

    /**
     * Create and add a configuration to our cluster using the new user's privilege
     */

    String configType = "test-hadoop-env";
    String configTag = "version1";
    ClusterConfigParams configParams = new ClusterConfigParams();
    configParams.setClusterName(clusterName);
    configParams.setConfigType(configType);
    configParams.setConfigTag(configTag);
    configParams.setProperties(new HashMap<String, String>() {
        {
            put("fs.default.name", "localhost:9995");
        }
    });

    /**
     * This user has enough privilege to create the cluster configuration. Should succeed with 201.
     */
    ConnectionParams userConnectionParams = createConnectionParams(clusterAdminName, clusterAdminPwd);
    WebRequest webRequest = new CreateConfigurationWebRequest(userConnectionParams, configParams);
    WebResponse webResponse = webRequest.getResponse();
    assertEquals(HttpStatus.SC_CREATED, webResponse.getStatusCode());

    /**
     * Delete the user
     */
    RestApiUtils.executeRequest(new DeleteUserWebRequest(adminConnectionParams, clusterAdminName));
}

From source file:org.apache.ambari.funtest.server.utils.RestApiUtils.java

/**
 * Executes a web request and throws an exception if the status code is incorrect.
 *
 * @param request/*from  w  w w  .j ava 2  s.c  o m*/
 * @return
 * @throws Exception
 */
public static JsonElement executeRequest(WebRequest request) throws Exception {
    WebResponse response = request.getResponse();
    int responseCode = response.getStatusCode();
    String responseBody = response.getContent();

    if (responseCode != HttpStatus.SC_OK && responseCode != HttpStatus.SC_CREATED
            && responseCode != HttpStatus.SC_ACCEPTED) {
        throw new RuntimeException(String.format("%d:%s", responseCode, responseBody));
    }

    return new JsonParser().parse(new JsonReader(new StringReader(responseBody)));
}

From source file:org.apache.cloudstack.network.element.SspClient.java

public TenantNetwork createTenantNetwork(String tenantUuid, String networkName) {
    TenantNetwork req = new TenantNetwork();
    req.name = networkName;//  w  w w.j  a  va 2s  .  c o  m
    req.tenantUuid = tenantUuid;

    PostMethod method = postMethod;
    method.setPath("/ssp.v1/tenant-networks");
    StringRequestEntity entity = null;
    try {
        entity = new StringRequestEntity(new Gson().toJson(req), "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        s_logger.error("failed creating http request body", e);
        return null;
    }
    method.setRequestEntity(entity);

    String response = executeMethod(method);
    if (response != null && method.getStatusCode() == HttpStatus.SC_CREATED) {
        return new Gson().fromJson(response, TenantNetwork.class);
    }
    return null;
}

From source file:org.apache.cloudstack.network.element.SspClient.java

public TenantPort createTenantPort(String tenantNetworkUuid) {
    TenantPort req = new TenantPort();
    req.networkUuid = tenantNetworkUuid;
    req.attachmentType = "NoAttachment";

    PostMethod method = postMethod;//from  w ww.  jav  a 2s .  co  m
    method.setPath("/ssp.v1/tenant-ports");
    StringRequestEntity entity = null;
    try {
        entity = new StringRequestEntity(new Gson().toJson(req), "application/json", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        s_logger.error("failed creating http request body", e);
        return null;
    }
    method.setRequestEntity(entity);

    String response = executeMethod(method);
    if (response != null && method.getStatusCode() == HttpStatus.SC_CREATED) {
        return new Gson().fromJson(response, TenantPort.class);
    }
    return null;
}

From source file:org.apache.cloudstack.network.element.SspClientTest.java

@Test
public void createNetworkTest() throws Exception {
    String networkName = "example network 1";
    String tenant_net_uuid = UUID.randomUUID().toString();

    when(_postMethod.getURI()).thenReturn(getUri());
    when(_postMethod.getStatusCode()).thenReturn(HttpStatus.SC_CREATED);
    when(_postMethod.getResponseBodyAsString()).thenReturn("{\"uuid\":\"" + tenant_net_uuid + "\",\"name\":\""
            + networkName + "\",\"tenant_uuid\":\"" + uuid + "\"}");
    SspClient.TenantNetwork tnet = sspClient.createTenantNetwork(uuid, networkName);
    assertEquals(tnet.name, networkName);
    assertEquals(tnet.uuid, tenant_net_uuid);
    assertEquals(tnet.tenantUuid, uuid);
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.Action.java

protected String executePost(final String uri, final StringRequestEntity entity)
        throws NeutronRestApiException {
    try {// ww w. j  av a 2s .com
        validateCredentials();
    } catch (NeutronInvalidCredentialsException e) {
        throw new NeutronRestApiException("Invalid credentials!", e);
    }

    NeutronRestFactory factory = NeutronRestFactory.getInstance();

    NeutronRestApi neutronRestApi = factory.getNeutronApi(PostMethod.class);
    PostMethod postMethod = (PostMethod) neutronRestApi.createMethod(url, uri);

    try {
        postMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
        postMethod.setRequestEntity(entity);

        String encodedCredentials = encodeCredentials();
        postMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials);

        neutronRestApi.executeMethod(postMethod);

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

        return postMethod.getResponseBodyAsString();
    } catch (NeutronRestApiException e) {
        s_logger.error(
                "NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller",
                e);
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    } catch (IOException e) {
        throw new NeutronRestApiException("Failed to load json response body", e);
    } finally {
        postMethod.releaseConnection();
    }
}