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.cloud.network.nicira.NiciraNvpApi.java

private <T> void executeUpdateObject(T newObject, String uri, Map<String, String> parameters)
        throws NiciraNvpApiException {
    String url;/*w  ww . j a  v  a2 s . c  o m*/
    try {
        url = new URL(_protocol, _host, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Connection to NVP Failed");
    }

    Gson gson = new Gson();

    PutMethod pm = new PutMethod(url);
    pm.setRequestHeader("Content-Type", "application/json");
    try {
        pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null));
    } catch (UnsupportedEncodingException e) {
        throw new NiciraNvpApiException("Failed to encode json request body", e);
    }

    executeMethod(pm);

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        String errorMessage = responseToErrorMessage(pm);
        pm.releaseConnection();
        s_logger.error("Failed to update object : " + errorMessage);
        throw new NiciraNvpApiException("Failed to update object : " + errorMessage);
    }
    pm.releaseConnection();
}

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

@Override
public void updateUser(User user) {
    String resource = String.format(baseUrl + USER, user.getUserId());
    PutMethod method = new PutMethod(resource);
    try {/*from   ww w  . j a va  2s. c  o m*/
        String data = serialize(user);
        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.xmlcalabash.library.ApacheHttpRequest.java

private PutMethod doPut(XdmNode body) {
    PutMethod method = new PutMethod(requestURI.toASCIIString());
    doPutOrPost(method, body);
    return method;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Performs an HTTP PUT request//from   w  w w .j ava 2  s . c  o m
 * 
 * @param httpServletRequest The {@link HttpServletRequest} object passed in by the servlet engine representing the client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which we can send a proxied response to the client
 */
public void doPut(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {

    try {

        URL url = null;
        String user = null, password = null;
        //Parse the queryString to not read the request body calling getParameter from httpServletRequest
        // so the method can simply forward the request body
        Map<String, String> pars = splitQuery(httpServletRequest.getQueryString());

        for (String key : pars.keySet()) {

            String value = pars.get(key);

            if ("user".equals(key)) {
                user = value;
            } else if ("password".equals(key)) {
                password = value;
            } else if ("url".equals(key)) {
                url = new URL(value);
            }
        }
        if (url != null) {

            onInit(httpServletRequest, httpServletResponse, url);

            // ////////////////////////////////
            // Create a standard PUT request
            // ////////////////////////////////

            PutMethod putMethodProxyRequest = new PutMethod(url.toExternalForm());

            // ////////////////////////////////
            // Forward the request headers
            // ////////////////////////////////

            final ProxyInfo proxyInfo = setProxyRequestHeaders(url, httpServletRequest, putMethodProxyRequest);

            // //////////////////////////////////////////////////
            // Check if this is a mulitpart (file upload) PUT
            // //////////////////////////////////////////////////

            if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
                this.handleMultipart(putMethodProxyRequest, httpServletRequest);
            } else {
                this.handleStandard(putMethodProxyRequest, httpServletRequest);
            }

            // ////////////////////////////////
            // Execute the proxy request
            // ////////////////////////////////

            this.executeProxyRequest(putMethodProxyRequest, httpServletRequest, httpServletResponse, user,
                    password, proxyInfo);

        }

    } catch (HttpErrorException ex) {
        httpServletResponse.sendError(ex.getCode(), ex.getMessage());
    } finally {
        onFinish();
    }

}

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

@Override
public EntriesQueryResult listEntries(ListEntriesRequest request) {
    String uri = baseUrl + ENTRIES;
    PutMethod method = new PutMethod(uri);
    try {//from  ww  w .  j a  v a  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, EntriesQueryResult.class);

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

    } catch (Exception e) {
        throw new RuntimeException("Failed listing entries via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}

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

@Override
public void setUserAvatarId(Long userId, String avatarId) {
    String resource = String.format(baseUrl + USER_AVATARID, userId);
    PutMethod method = new PutMethod(resource);
    try {//from  w w  w  .  j  ava 2s  .c o m
        ChangeUserAvatarIdRequest request = new ChangeUserAvatarIdRequest();
        request.setUserAvatarId(avatarId);
        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.delmar.station.service.impl.WFDetailServiceImpl.java

/**
   * POST/*from ww  w. j a v a  2s .c o  m*/
   * @param url
   * @param parms
   * @return
   * @throws java.io.UnsupportedEncodingException
   */
private static HttpMethod buildPostMethod(String url, Map<String, String> parms)
        throws UnsupportedEncodingException {
    //?? 
    NameValuePair[] data = new NameValuePair[parms.keySet().size()];
    Iterator<Entry<String, String>> it = parms.entrySet().iterator();
    int i = 0;
    while (it.hasNext()) {
        Entry<String, String> entry = (Entry) it.next();
        String key = entry.getKey();
        String value = entry.getValue();
        //System.out.println(key+":"+value);
        data[i] = new NameValuePair(key, value);
        i++;
    }
    PutMethod method = new PutMethod(url);
    method.setQueryString(data);
    //.setRequestBody(data);

    return method;
}

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;/*from w  w  w .j  a va 2 s. c o  m*/
    try {
        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:edu.stanford.epad.epadws.processing.pipeline.task.EpadStatisticsTask.java

@Override
public void run() {
    try {//from w  w  w  .  j a  v a 2s  . c  om
        log.info("Getting epad statistics");
        EpadStatistics es = new EpadStatistics();
        int users = new User().getCount("");
        int projects = new Project().getCount("");
        int patients = new Subject().getCount("");
        int studies = new Study().getCount("");
        int files = new EpadFile().getCount("");
        int templates = new EpadFile().getCount("filetype = '" + FileType.TEMPLATE.getName() + "'");
        int plugins = new Plugin().getCount("");
        int series = epadDatabaseOperations.getNumberOfSeries();
        int npacs = RemotePACService.getInstance().getRemotePACs().size();
        int aims = epadDatabaseOperations.getNumberOfAIMs("1 = 1");
        int dsos = epadDatabaseOperations.getNumberOfAIMs("DSOSeriesUID is not null or DSOSeriesUID != ''");
        int pacQueries = new RemotePACQuery().getCount("");
        int wls = 0;
        try {
            wls = new WorkList().getCount("");
        } catch (Exception x) {
        }
        String host = EPADConfig.xnatServer;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = System.getenv("DOCKER_HOST");
        ;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = System.getenv("HOSTNAME");
        ;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = InetAddress.getLocalHost().getHostName();
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = getIPAddress();
        es.setHost(host);
        es.setNumOfUsers(users);
        es.setNumOfProjects(projects);
        es.setNumOfPatients(patients);
        es.setNumOfStudies(studies);
        es.setNumOfSeries(series);
        es.setNumOfAims(aims);
        es.setNumOfDSOs(dsos);
        es.setNumOfWorkLists(wls);
        es.setNumOfPacs(npacs);
        es.setNumOfAutoQueries(pacQueries);
        es.setNumOfFiles(files);
        es.setNumOfPlugins(plugins);
        es.setNumOfTemplates(templates);
        es.setCreator("admin");
        es.save();

        //get the template statistics
        List<EpadStatisticsTemplate> templateStats = epadDatabaseOperations.getTemplateStats();

        Calendar now = Calendar.getInstance();
        boolean daily = true;
        if ("Weekly".equalsIgnoreCase(EPADConfig.getParamValue("StatisticsPeriod", "Daily")))
            daily = false;
        if (!"true".equalsIgnoreCase(EPADConfig.getParamValue("DISABLE_STATISTICS_TRANSMIT"))) {
            if (daily || now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                long delay = new Random().nextInt(1800 + 1);
                if (EPADConfig.xnatServer.indexOf("stanford") == -1)
                    Thread.sleep(1000 * delay); // So that all don't do this at the same time
                //send the number statistics
                String epadUrl = EPADConfig.getParamValue("EpadStatisticsURL",
                        "https://epad-public.stanford.edu/epad/statistics/");
                epadUrl = epadUrl + "?numOfUsers=" + users;
                epadUrl = epadUrl + "&numOfProjects=" + projects;
                epadUrl = epadUrl + "&numOfPatients=" + patients;
                epadUrl = epadUrl + "&numOfStudies=" + studies;
                epadUrl = epadUrl + "&numOfSeries=" + series;
                epadUrl = epadUrl + "&numOfAims=" + aims;
                epadUrl = epadUrl + "&numOfDSOs=" + dsos;
                epadUrl = epadUrl + "&numOfWorkLists=" + wls;
                epadUrl = epadUrl + "&numOfFiles=" + files;
                epadUrl = epadUrl + "&numOfPlugins=" + plugins;
                epadUrl = epadUrl + "&numOfTemplates=" + templates;
                epadUrl = epadUrl + "&host=" + host;
                HttpClient client = new HttpClient();
                PutMethod putMethod = new PutMethod(epadUrl);

                try {
                    log.info("Sending statistics to Central Epad, url:" + epadUrl);
                    int status = client.executeMethod(putMethod);
                    log.info("Done Sending, status:" + putMethod.getStatusLine());
                } catch (IOException e) {
                    log.warning("Error calling Central Epad with URL " + epadUrl, e);
                } finally {
                    putMethod.releaseConnection();
                }

                //send statistics for templates
                for (EpadStatisticsTemplate st : templateStats) {
                    //get the xml first
                    String filePath = st.getFilePath() + st.getFileId() + ".xml";
                    log.info("path " + filePath);
                    File f = null;
                    if (filePath != null && (f = new File(filePath)).exists()) {
                        st.setTemplateText(EPADFileUtils.readFileAsString(f));
                    }
                    st.setCreator("admin");
                    //persist to db
                    st.save();

                    epadUrl = EPADConfig.getParamValue("EpadTemplateStatisticsURL",
                            "https://epad-public.stanford.edu/epad/statistics/templates/");
                    epadUrl = epadUrl + "?templateCode=" + encode(st.getTemplateCode());
                    epadUrl = epadUrl + "&templateName=" + encode(st.getTemplateName());
                    epadUrl = epadUrl + "&authors=" + encode(st.getAuthors());
                    epadUrl = epadUrl + "&version=" + encode(st.getVersion());
                    epadUrl = epadUrl + "&templateLevelType=" + encode(st.getTemplateLevelType());
                    epadUrl = epadUrl + "&templateDescription=" + encode(st.getTemplateDescription());
                    epadUrl = epadUrl + "&numOfAims=" + st.getNumOfAims();
                    epadUrl = epadUrl + "&host=" + host;
                    putMethod = new PutMethod(epadUrl);
                    putMethod.setRequestEntity(
                            new StringRequestEntity(st.getTemplateText(), "text/xml", "UTF-8"));

                    try {
                        log.info("Sending template statistics to Central Epad, url:" + epadUrl);
                        int status = client.executeMethod(putMethod);
                        log.info("Done Sending, status:" + putMethod.getStatusLine());
                    } catch (IOException e) {
                        log.warning("Error calling Central Epad with URL " + epadUrl, e);
                    } finally {
                        putMethod.releaseConnection();
                    }
                }
            }
        }

    } catch (Exception e) {
        log.warning("Error is saving/sending statistics", e);
    }
    GetMethod getMethod = null;
    try {
        String epadUrl = EPADConfig.getParamValue("EpadStatusURL",
                "https://epad-public.stanford.edu/epad/status/");
        HttpClient client = new HttpClient();
        getMethod = new GetMethod(epadUrl);
        int status = client.executeMethod(getMethod);
        if (status == HttpServletResponse.SC_OK) {
            String response = getMethod.getResponseBodyAsString();
            int versInd = response.indexOf("Version:");
            if (versInd != -1) {
                String version = response.substring(versInd + "Version:".length() + 1);
                if (version.indexOf("\n") != -1)
                    version = version.substring(0, version.indexOf("\n"));
                if (version.indexOf(" ") != -1)
                    version = version.substring(0, version.indexOf(" "));
                log.info("Current ePAD version:" + version + " Our Version:"
                        + new EPadWebServerVersion().getVersion());
                if (!version.equals(new EPadWebServerVersion().getVersion())) {
                    newEPADVersion = version;
                    newEPADVersionAvailable = true;
                    String msg = "A new version of ePAD: " + version
                            + " is available, please go to ftp://epad-distribution.stanford.edu/ to download";
                    log.info(msg);
                    List<User> admins = new User().getObjects("admin = 1 and enabled = 1");
                    for (User admin : admins) {
                        List<Map<String, String>> userEvents = epadDatabaseOperations
                                .getEpadEventsForSessionID(admin.getUsername(), false);
                        boolean skip = false;
                        for (Map<String, String> event : userEvents) {
                            if (event.get("aim_name").equals("Upgrade")) {
                                skip = true;
                                break;
                            }
                        }
                        if (skip)
                            continue;
                        if (EPADConfig.xnatServer.indexOf("stanford") == -1)
                            epadDatabaseOperations.insertEpadEvent(admin.getUsername(), msg, // Message
                                    "", "", // aimUID, aimName
                                    "", // patient ID
                                    "", // patient Name
                                    "", // templateID
                                    "", // templateName
                                    "Please update ePAD"); // PluginName
                    }
                }
            }
        } else
            log.warning("Error is getting epad version");

    } catch (Exception x) {
        log.warning("Error is getting epad version", x);
    } finally {
        getMethod.releaseConnection();
    }

    //done with calculating and sending the statistics
    //calculate a monthly cumulative if it is there is no record for the month
    boolean isAlreadyCalced = false;
    Calendar now = Calendar.getInstance();
    try {
        EPADUsageList monthly = epadOperations.getMonthlyUsageSummaryForMonth(now.get(Calendar.MONTH) + 1);
        if (monthly != null && monthly.ResultSet.totalRecords > 0)
            isAlreadyCalced = true;
    } catch (Exception e) {
        log.warning("Couldn't get if the monthly cumulative statistics already calculated, assuming no", e);
    }
    if (isAlreadyCalced == false) {
        epadDatabaseOperations.calcMonthlyCumulatives();
    }

}

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

@Override
public TransactionQueryResult listTransactions(ListTransactionsRequest request) {
    String uri = baseUrl + TRANSACTIONS;
    PutMethod method = new PutMethod(uri);
    try {/*ww w .j a  v  a2 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, TransactionQueryResult.class);

        } else {
            throw new RuntimeException(
                    "Failed to list transactions, RESPONSE CODE: " + statusCode + " url: " + uri);
        }

    } catch (Exception e) {
        throw new RuntimeException("Failed listing transactions via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}