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

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

Introduction

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

Prototype

public PutMethod(String paramString) 

Source Link

Usage

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public UserQueryResult findUsers(Long userId, String name, int offset, int limit, UserOrder sortOrder,
        boolean ascending) {
    PutMethod method = new PutMethod(baseUrl + QUERY);

    UserQuery request = new UserQuery();
    request.setUserId(userId);/*  w ww.  j  av a 2s  . co  m*/
    request.setUserName(name);
    request.setQueryOffset(offset);
    request.setQueryLimit(limit);
    request.setAscending(ascending);
    request.setOrder(sortOrder);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, UserQueryResult.class);

        } else {
            throw new RuntimeException("Failed to query users, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.indiana.d2i.htrc.portal.HTRCAgentClient.java

public boolean saveJobs(List<String> jobIds) throws IOException {
    boolean res = true;
    for (String id : jobIds) {
        PutMethod saveJobId = null;/*  w  ww  . jav  a  2s.  co m*/
        try {
            String jobsaveURL = String
                    .format(PlayConfWrapper.agentEndpoint() + PlayConfWrapper.jobSaveURLTemplate(), id);
            saveJobId = new PutMethod(jobsaveURL);
            saveJobId.setRequestHeader("Authorization", "Bearer " + accessToken);
            log.info("Save job url: " + jobsaveURL);

            //                client.getHttpConnectionManager().getParams().setConnectionTimeout(PlayConfWrapper.agentConnectTimeout());
            //                client.getHttpConnectionManager().getParams().setSoTimeout(PlayConfWrapper.agentWaitTimeout());

            int response = client.executeMethod(saveJobId);
            this.responseCode = response;
            if (response == 200) {
                log.info("Saved Active Job ID :  " + id);
                renew = 0;
            } else if (response == 401 && (renew < MAX_RENEW)) {
                try {
                    accessToken = HTRCPersistenceAPIClient.renewToken(refreshToken);
                    renew++;
                    return saveJobs(jobIds); // bugs here
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                renew = 0;
                log.error(String.format("Unable to save job %s from agent. Response code %d", id, response));
                res = false;
            }
        } catch (Exception e) {
            log.error(String.valueOf(e));
        } finally {
            if (saveJobId != null) {
                saveJobId.releaseConnection();
                saveJobId = null;
            }
        }
    }
    return res;
}

From source file:edu.stanford.epad.epadws.xnat.XNATCreationOperations.java

public static int createXNATDICOMStudyExperiment(String xnatProjectLabel, String xnatSubjectLabel,
        String studyUID, String jsessionID) {
    String xnatStudyURL = XNATUtil.buildXNATDICOMStudyCreationURL(xnatProjectLabel, xnatSubjectLabel, studyUID);
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(xnatStudyURL);
    int xnatStatusCode;

    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID);

    try {/*w  w w  .  jav  a  2 s .  c  o m*/
        log.info("Creating study " + studyUID + " for patient " + xnatSubjectLabel + " in project "
                + xnatProjectLabel + " in XNAT");
        xnatStatusCode = client.executeMethod(putMethod);
        if (XNATUtil.unexpectedXNATCreationStatusCode(xnatStatusCode))
            log.warning("Failure calling XNAT with URL " + xnatStudyURL + "; status code = " + xnatStatusCode);
        else
            eventTracker.recordStudyEvent(jsessionID, xnatProjectLabel, xnatSubjectLabel, studyUID);
    } catch (IOException e) {
        log.warning("Error calling XNAT with URL " + xnatStudyURL, e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        putMethod.releaseConnection();
    }

    if (xnatStatusCode == HttpServletResponse.SC_CONFLICT)
        xnatStatusCode = HttpServletResponse.SC_OK;

    return xnatStatusCode;
}

From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Set up and initiate the PUT method, but leave the actual
 * technique of writing the request body to the caller.
 */// w w w .  jav a2 s . c o  m
private void startPutInternal(String collection, String type, NameValuePair options[], InputStream is)
        throws IOException, HttpException {
    if (lastPut != null)
        throw new IOException("Bad state: startPUT called twice without finishPUT.");

    String url = lookupHandle(collection);

    NameValuePair args[] = new NameValuePair[1 + (options == null ? 0 : options.length)];
    args[0] = new NameValuePair("package", type);
    if (options != null) {
        for (int i = 0; i < options.length; ++i)
            args[i + 1] = options[i];
    }
    lastPut = new PutMethod(url);
    lastPut.setDoAuthentication(true);
    lastPut.setQueryString(args);
    lastPut.setRequestEntity(new InputStreamRequestEntity(is, -1));
}

From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java

public void modifyDatastream(String pid, String dsId, String content) throws IOException {
    StringBuilder uri = new StringBuilder(getBaseUrl());
    uri.append("/objects/");
    uri.append(pid);/*from   w  w  w  .ja  v  a2 s. c  o m*/
    uri.append("/datastreams/");
    uri.append(dsId);
    PutMethod method = new PutMethod(uri.toString());
    method.setRequestEntity(new StringRequestEntity(content, "text/xml", "UTF-8"));
    executeMethod(method);
    method.releaseConnection();
}

From source file:au.edu.usq.fascinator.access.couch.CouchAccessControl.java

private void put(JsonConfigHelper oldRecord, List<String> newRoles, String method) throws Exception {
    EntityEnclosingMethod rq = null;/*from  w  ww  .  java2s.  com*/
    try {
        // Prepare to send
        String dataToSend = writeUpdateString(oldRecord, newRoles);
        String recordId = oldRecord.get("_id");

        // Get our connection ready
        if (method.equals("PUT")) {
            rq = new PutMethod(url + recordId);
        } else {
            rq = new PostMethod(url);
        }
        rq.addRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        rq.setRequestBody(dataToSend);
        int statusCode = couch.executeMethod(rq);

        // Valid responses are anywhere in 200 range for this
        if (statusCode < 200 || statusCode > 299) {
            throw new Exception(
                    "Database " + method + " failed!: '" + statusCode + "': " + rq.getResponseBodyAsString());
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (rq != null) {
            rq.releaseConnection();
        }
    }
}

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;//from  ww w .  ja va2 s  . c om
    try {
        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:com.urbancode.ds.jenkins.plugins.serenarapublisher.UrbanDeploySite.java

public String executeJSONPut(URI uri, String putContents) throws Exception {
    String result = null;//  w  ww. j  ava2s .  c om
    HttpClient httpClient = new HttpClient();

    if ("https".equalsIgnoreCase(uri.getScheme())) {
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory();
        Protocol https = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", https);
    }

    PutMethod method = new PutMethod(uri.toString());
    setDirectSsoInteractionHeader(method);
    method.setRequestBody(putContents);
    method.setRequestHeader("Content-Type", "application/json");
    method.setRequestHeader("charset", "utf-8");
    try {
        HttpClientParams params = httpClient.getParams();
        params.setAuthenticationPreemptive(true);

        UsernamePasswordCredentials clientCredentials = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, clientCredentials);

        int responseCode = httpClient.executeMethod(method);

        //if (responseCode < 200 || responseCode < 300) {
        if (responseCode != 200 && responseCode != 204) {
            throw new Exception("Serena DA returned error code: " + responseCode);
        } else {
            result = method.getResponseBodyAsString();
        }
    } catch (Exception e) {
        throw new Exception("Error connecting to SerenaRA: " + e.getMessage());
    } finally {
        method.releaseConnection();
    }

    return result;
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void setUserStatus(Long userId, UserStatus status) {
    String resource = String.format(baseUrl + SET_STATUS, userId);
    PutMethod method = new PutMethod(resource);
    try {/*from w ww . j a v  a2 s . c  o m*/
        ChangeUserStatusRequest request = new ChangeUserStatusRequest();
        request.setUserStatus(status);
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public AccountQueryResult listAccounts(ListAccountsRequest request) {
    String uri = baseUrl + ACCOUNTS;
    PutMethod method = new PutMethod(uri);
    try {/* www  . j  a  va  2 s  . co m*/
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AccountQueryResult.class);

        } else {
            throw new RuntimeException(
                    "Failed to list accounts, RESPONSE CODE: " + statusCode + " url: " + uri);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed listing accounts via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}