Example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectiveUserAssessments(int learningObjectId, int instanceId, int[] userIds,
        List<LearningObjectiveAssessment> assessments) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveUserAssessments",
            learningObjectId, instanceId);
    QueryStringBuilder query = new QueryStringBuilder(uri, false);
    if (userIds != null && userIds.length > 0) {
        query.AddParameter("userIds", intArrayToCsvString(userIds));
    }/*  w  w  w  .  j  ava  2 s .  co m*/
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, query.getQueryString(),
            HttpMethodType.PUT);

    String assessmentsAsXml = serializeLearningObjectiveAssessmentsToXml(assessments);
    InputStream is = new ByteArrayInputStream(assessmentsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

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

/**
 * Create message in specified folder./* www .  j a v a 2s.  c  om*/
 * 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:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java

@Override
public final ScribeCommandObject updateObject(final ScribeCommandObject cADCommandObject) throws Exception {

    logger.debug("----Inside updateObject");
    PutMethod putMethod = null;
    try {/*from ww w  . j a  va 2 s.  c o  m*/
        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Check if crm user info is present in request */
        if (cADCommandObject.getCrmUserId() != null) {

            /* Get agent from session manager */
            final ScribeCacheObject agent = zDCRMSessionManager
                    .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

            /* Get CRM information from agent */
            serviceURL = agent.getScribeMetaObject().getCrmServiceURL();
            serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol();
            userId = agent.getScribeMetaObject().getCrmUserId();
            password = agent.getScribeMetaObject().getCrmPassword();
            sessionId = agent.getScribeMetaObject().getCrmSessionId();
            crmPort = agent.getScribeMetaObject().getCrmPort();
        }

        String crmObjectId = null;

        /* Check if XML content in request, is not null */
        if (cADCommandObject.getObject() != null && cADCommandObject.getObject().length == 1) {

            /* Get Id of CRM object */
            crmObjectId = ZDCRMMessageFormatUtils.getNodeValue("ID", cADCommandObject.getObject()[0]);

            if (crmObjectId == null) {
                /* Inform user about invalid request */
                throw new ScribeException(
                        ScribeResponseCodes._1008 + "CRM object id is not present in request");
            }
        } else {
            /* Inform user about invalid request */
            throw new ScribeException(
                    ScribeResponseCodes._1008 + "CRM object information is not present in request");
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType()
                + "s/" + crmObjectId + ".xml";

        logger.debug("----Inside updateObject zenDeskURL: " + zenDeskURL);

        /* Instantiate put method */
        putMethod = new PutMethod(zenDeskURL);

        /* Set request content type */
        putMethod.addRequestHeader("Content-Type", "application/xml");
        putMethod.addRequestHeader("accept", "application/xml");

        /* Cookie is required to be set for session management */
        putMethod.addRequestHeader("Cookie", sessionId);

        /* Add request entity */
        final RequestEntity entity = new StringRequestEntity(
                ZDCRMMessageFormatUtils.getCreateRequestXML(cADCommandObject), null, null);
        putMethod.setRequestEntity(entity);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(putMethod);
        logger.debug("----Inside updateObject response code: " + result + " & body: "
                + putMethod.getResponseBodyAsString());

        /* Check if object is updated */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Return the original object */
            return cADCommandObject;
        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE) {
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(putMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final ParserConfigurationException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM",
                exception);
    } catch (final IOException exception) {
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (putMethod != null) {
            putMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:com.inbravo.scribe.rest.service.crm.zd.ZDV2RESTCRMService.java

@Override
public final ScribeCommandObject updateObject(final ScribeCommandObject cADCommandObject) throws Exception {

    logger.debug("----Inside updateObject");
    PutMethod putMethod = null;
    try {//from   w w w  .  j  av  a 2 s.c om
        String serviceURL = null;
        String serviceProtocol = null;
        String userId = null;
        String password = null;
        String sessionId = null;
        String crmPort = "80";

        /* Get agent from session manager */
        final ScribeCacheObject cacheObject = zDCRMSessionManager
                .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId());

        /* Get CRM information from agent */
        serviceURL = cacheObject.getScribeMetaObject().getCrmServiceURL();
        serviceProtocol = cacheObject.getScribeMetaObject().getCrmServiceProtocol();
        userId = cacheObject.getScribeMetaObject().getCrmUserId();
        password = cacheObject.getScribeMetaObject().getCrmPassword();
        crmPort = cacheObject.getScribeMetaObject().getCrmPort();

        String crmObjectId = null;

        /* Check if response content in request, is not null */
        if (cADCommandObject.getObject() != null && cADCommandObject.getObject().length == 1) {

            /* Get Id of CRM object */
            crmObjectId = ZDCRMMessageFormatUtils.getNodeValue("ID", cADCommandObject.getObject()[0]);

            if (crmObjectId == null) {

                /* Inform user about invalid request */
                throw new ScribeException(
                        ScribeResponseCodes._1008 + "CRM object id is not present in request");
            }
        } else {
            /* Inform user about invalid request */
            throw new ScribeException(
                    ScribeResponseCodes._1008 + "CRM object information is not present in request");
        }

        /* Create Zen desk URL */
        final String zenDeskURL = serviceProtocol + "://" + serviceURL + zdAPISubPath
                + cADCommandObject.getObjectType().toLowerCase() + "s/" + crmObjectId + ".json";

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside updateObject zenDeskURL: " + zenDeskURL);
        }

        /* Instantiate put method */
        putMethod = new PutMethod(zenDeskURL);

        /* Set request content type */
        putMethod.addRequestHeader("Content-Type", "application/json");
        putMethod.addRequestHeader("accept", "application/json");

        /* Cookie is required to be set for session management */
        putMethod.addRequestHeader("Cookie", sessionId);

        /* Add request entity */
        final RequestEntity entity = new StringRequestEntity(
                ZDCRMMessageFormatUtils.getCreateRequestJSON(cADCommandObject), null, null);
        putMethod.setRequestEntity(entity);

        final HttpClient httpclient = new HttpClient();

        /* Set credentials */
        httpclient.getState().setCredentials(new AuthScope(serviceURL, this.validateCrmPort(crmPort)),
                new UsernamePasswordCredentials(userId, password));

        /* Execute method */
        int result = httpclient.executeMethod(putMethod);

        if (logger.isDebugEnabled()) {
            logger.debug("----Inside updateObject response code: " + result + " & body: "
                    + putMethod.getResponseBodyAsString());
        }

        /* Check if object is updated */
        if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) {

            /* Return the response object */
            return this.createCreateResponse(putMethod.getResponseBodyAsString(),
                    cADCommandObject.getObjectType().toLowerCase());

        } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED
                || result == HttpStatus.SC_NOT_ACCEPTABLE || result == HttpStatus.SC_UNPROCESSABLE_ENTITY) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : "
                    + ZDCRMMessageFormatUtils.getErrorFromResponse(putMethod.getResponseBodyAsStream()));
        } else if (result == HttpStatus.SC_UNAUTHORIZED) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM");
        } else if (result == HttpStatus.SC_NOT_FOUND) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM");
        } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) {

            /* Throw user error with valid reasons for failure */
            throw new ScribeException(ScribeResponseCodes._1004
                    + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct");
        }
    } catch (final ScribeException exception) {
        throw exception;
    } catch (final JSONException e) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                e);
    } catch (final ParserConfigurationException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final SAXException exception) {

        /* Throw user error */
        throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid response from Zendesk CRM",
                exception);
    } catch (final IOException exception) {

        /* Throw user error */
        throw new ScribeException(
                ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM",
                exception);
    } finally {
        /* Release connection socket */
        if (putMethod != null) {
            putMethod.releaseConnection();
        }
    }
    return cADCommandObject;
}

From source file:org.ala.spatial.util.UploadSpatialResource.java

public static String loadResource(String url, String extra, String username, String password,
        String resourcepath) {/*w  w w .  j a  v a  2s. c o m*/
    String output = "";

    HttpClient client = new HttpClient();

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);

    //put.addRequestHeader("Content-type", "application/zip");

    // Request content will be retrieved directly 
    // from the input stream 
    RequestEntity entity = new FileRequestEntity(input, "application/zip");
    put.setRequestEntity(entity);

    // Execute the request 
    try {
        int result = client.executeMethod(put);

        // get the status code
        System.out.println("Response status code: " + result);

        // Display response
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());

        output += result;

    } catch (Exception e) {
        System.out.println("Something went wrong with UploadSpatialResource");
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done 
        put.releaseConnection();
    }

    return output;

}

From source file:org.ala.spatial.util.UploadSpatialResource.java

public static String loadSld(String url, String extra, String username, String password, String resourcepath) {
    System.out.println("loadSld url:" + url);
    System.out.println("path:" + resourcepath);

    String output = "";

    HttpClient client = new HttpClient();

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    File input = new File(resourcepath);

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);/* ww  w  . j  a va2 s  . c  o m*/

    // Request content will be retrieved directly
    // from the input stream
    RequestEntity entity = new FileRequestEntity(input, "application/vnd.ogc.sld+xml");
    put.setRequestEntity(entity);

    // Execute the request
    try {
        int result = client.executeMethod(put);

        // get the status code
        System.out.println("Response status code: " + result);

        // Display response
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());

        output += result;

    } catch (Exception e) {
        System.out.println("Something went wrong with UploadSpatialResource");
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:org.ala.spatial.util.UploadSpatialResource.java

public static String assignSld(String url, String extra, String username, String password, String data) {
    System.out.println("assignSld url:" + url);
    System.out.println("data:" + data);

    String output = "";

    HttpClient client = new HttpClient();

    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);//from w  w w  . j av  a2s  .c om

    // Execute the request
    try {
        // Request content will be retrieved directly
        // from the input stream
        File file = File.createTempFile("sld", "xml");
        System.out.println("file:" + file.getPath());
        FileWriter fw = new FileWriter(file);
        fw.append(data);
        fw.close();
        RequestEntity entity = new FileRequestEntity(file, "text/xml");
        put.setRequestEntity(entity);

        int result = client.executeMethod(put);

        // get the status code
        System.out.println("Response status code: " + result);

        // Display response
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());

        output += result;

    } catch (Exception e) {
        System.out.println("Something went wrong with UploadSpatialResource");
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:org.ala.spatial.util.UploadSpatialResource.java

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload/*from w  ww  . j ava 2s . c  o  m*/
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output += result;
    } catch (Exception e) {
        SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java

/**
 * @see org.alfresco.jive.JiveOpenClient#updateDocument(java.lang.String, java.lang.String, java.lang.String, long, java.lang.String)
 */// w  w  w.j a v a 2 s. co  m
@Override
public void updateDocument(final String userId, final String cmisId, final String fileName, final long fileSize,
        final String mimeType) throws AuthenticationException, CallFailedException, DocumentNotFoundException,
        ServiceUnavailableException, DocumentSizeException {
    final PutMethod put = new PutMethod(buildUrl(OPENCLIENT_API_UPDATE_DOCUMENT));
    final PostMethod temp = new PostMethod();
    int status = -1;

    setCommonHeaders(userId, put);
    put.setRequestHeader("Content-Type", MIME_TYPE_FORM_URLENCODED);

    // These shenanigans are required because PutMethod doesn't directly support content as NameValuePairs.
    temp.setRequestBody(constructNameValuePairs(cmisId, fileName, fileSize, mimeType));
    put.setRequestEntity(temp.getRequestEntity());

    try {
        status = callJive(put);

        if (status >= 400) {
            if (status == 401 || status == 403) {
                throw new AuthenticationException();
            } else if (status == 404) {
                throw new DocumentNotFoundException(cmisId);
            } else if (status == 409) {
                throw new DocumentSizeException(fileName, fileSize);
            } else if (status == 503) {
                throw new ServiceUnavailableException();
            } else {
                throw new CallFailedException(status);
            }
        } else if (status >= 300) {
            log.warn("Status code: " + status + ". cmisObjectID: " + cmisId);
        }
    } catch (final HttpException he) {
        throw new CallFailedException(he);
    } catch (final IOException ioe) {
        throw new CallFailedException(ioe);
    } finally {
        put.releaseConnection();
    }
}

From source file:org.alfresco.repo.web.scripts.BaseWebScriptTest.java

/**
 * Send Remote Request to stand-alone Web Script Server
 * //w  w  w  .  jav  a2  s  .c o  m
 * @param req Request
 * @param expectedStatus int
 * @return response
 * @throws IOException
 */
protected Response sendRemoteRequest(Request req, int expectedStatus) throws IOException {
    String uri = req.getFullUri();
    if (!uri.startsWith("http")) {
        uri = remoteServer.baseAddress + uri;
    }

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        GetMethod get = new GetMethod(req.getFullUri());
        httpMethod = get;
    } else if (method.equalsIgnoreCase("POST")) {
        PostMethod post = new PostMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PATCH")) {
        PatchMethod post = new PatchMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PUT")) {
        PutMethod put = new PutMethod(req.getFullUri());
        put.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = put;
    } else if (method.equalsIgnoreCase("DELETE")) {
        DeleteMethod del = new DeleteMethod(req.getFullUri());
        httpMethod = del;
    } else {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }
    if (req.getHeaders() != null) {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet()) {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }

    // execute method
    httpClient.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod);
}