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:edu.unc.lib.dl.admin.controller.AbstractSwordController.java

public String updateDatastream(String pid, String datastream, HttpServletRequest request,
        HttpServletResponse response) {//from   w ww .  ja  v  a2  s .  c  om
    String responseString = null;
    String dataUrl = swordUrl + "object/" + pid;
    if (datastream != null)
        dataUrl += "/" + datastream;

    Abdera abdera = new Abdera();
    Entry entry = abdera.newEntry();
    Parser parser = abdera.getParser();
    Document<FOMExtensibleElement> doc;
    HttpClient client;
    PutMethod method;

    ParserOptions parserOptions = parser.getDefaultParserOptions();
    parserOptions.setCharset(request.getCharacterEncoding());

    try {

        doc = parser.parse(request.getInputStream(), parserOptions);
        entry.addExtension(doc.getRoot());

        client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword);
        client.getParams().setAuthenticationPreemptive(true);
        method = new PutMethod(dataUrl);
        // Pass the users groups along with the request
        method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());

        Header header = new Header("Content-Type", "application/atom+xml");
        method.setRequestHeader(header);
        StringWriter stringWriter = new StringWriter(2048);
        StringRequestEntity requestEntity;
        entry.writeTo(stringWriter);
        requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8");
        method.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        log.error("Encoding not supported", e);
        return null;
    } catch (IOException e) {
        log.error("IOException while writing entry", e);
        return null;
    }

    try {
        client.executeMethod(method);
        response.setStatus(method.getStatusCode());
        if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
            // success
            return "";
        } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) {
            if (method.getStatusCode() == 500)
                log.warn("Failed to upload " + datastream + " " + method.getURI().getURI());
            // probably a validation problem
            responseString = method.getResponseBodyAsString();
            return responseString;
        } else {
            response.setStatus(500);
            throw new Exception("Failure to update fedora content due to response of: "
                    + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI());
        }
    } catch (Exception e) {
        log.error("Error while attempting to stream Fedora content for " + pid, e);
    } finally {
        if (method != null)
            method.releaseConnection();
    }
    return responseString;
}

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from w  w w .j  av a 2s.co m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);
        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:edu.indiana.dlib.avalon.HydrantWorkflowListener.java

private void pingHydrant(String pid, long workflowId) {
    logger.trace("Starting to ping Hydrant: " + pid + " " + workflowId);
    try {//www . ja v a2s.c  o  m
        String url = UrlSupport.concat(new String[] { hydrantUrl, "master_files", pid });
        MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        HttpClient client = new HttpClient(mgr);

        PutMethod put = new PutMethod(url);

        Part[] parts = { new StringPart("workflow_id", String.valueOf(workflowId)), };
        put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));
        logger.trace("About to ping Hydrant");
        int status = client.executeMethod(put);
        logger.debug("Got status: " + status);
        logger.trace("Got response body: " + put.getResponseBodyAsString());
    } catch (Exception e) {
        logger.debug("Exception pinging Hydrant: " + e.getCause(), e);
    }
}

From source file:MemoryController.java

@RequestMapping("/memory")
public @ResponseBody Memory memory(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);/*from  ww w  .j  a v  a 2 s . c o  m*/

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "memory");
    params.put("search", search);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL);
    putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj2 = new JSONObject();
    jsonObj2.put("jsonrpc", "2.0");
    jsonObj2.put("method", "item.get");
    JSONObject params2 = new JSONObject();
    params2.put("output", "extend");
    params2.put("hostid", hostid);
    JSONObject search2 = new JSONObject();
    search2.put("key_", "swap");
    params2.put("search", search2);
    params2.put("sortfield", "name");
    jsonObj2.put("params", params2);
    jsonObj2.put("auth", authentication);// todo
    jsonObj2.put("id", new Integer(1));

    putMethod2.setRequestBody(jsonObj2.toString());

    String loginResponse = "";
    String loginResponse2 = "";
    String memory = "";
    String clock = "";
    String metricType = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response

        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        client.executeMethod(putMethod2); // send to request to the zabbix api

        loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response

        Object obj3 = parser.parse(loginResponse2);
        JSONObject obj4 = (JSONObject) obj3;
        String jsonrpc2 = (String) obj4.get("jsonrpc");
        JSONArray array2 = (JSONArray) obj4.get("result");

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            //         lastValue = getLastValue(tobj);
            //         lastClock = getLastClock(tobj);
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Total Memeory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Cached Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Free Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Buffered Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Shared Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }
        }

        for (int i = 0; i < array2.size(); i++) {
            JSONObject tobj2 = (JSONObject) array2.get(i);

            if (!tobj2.get("hostid").equals(hostid))
                continue;
            if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) {
                memory = (String) tobj2.get("lastvalue");
                clock = (String) tobj2.get("lastclock");
                metricType = "Free Swap Space";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }

        }

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    return new Memory(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:com.wandisco.s3hdfs.rewrite.redirect.Redirect.java

HttpMethod getHttpMethod(String scheme, String host, int port, String op, String userName, String uri,
        HTTP_METHOD method) {/*from  www  .j  av a2s  . co  m*/

    if (!uri.startsWith(WEBHDFS_PREFIX))
        uri = ADD_WEBHDFS(uri);

    String url = scheme + "://" + host + ":" + port + uri + "?user.name=" + userName + "&op=" + op;
    switch (method) {
    case GET:
        return new GetMethod(url);
    case PUT:
        return new PutMethod(url);
    case POST:
        return new PostMethod(url);
    case DELETE:
        return new DeleteMethod(url);
    case HEAD:
        return new HeadMethod(url);
    default:
        return null;
    }
}

From source file:CPUController.java

@RequestMapping("/cpu")
public @ResponseBody CPU cpu(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from  w w w  .ja  v a2s. co  m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "cpu");
    params.put("search", search);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";
    String cpu = "";
    String clock = "";
    String metricType = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);
            String key = (String) tobj.get("key_");
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("idle") && key.contains("idle")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu idle time";
            } else if (name.equals("iowait") && key.contains("iowait")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu iowait time";
            } else if (name.equals("nice") && key.contains("nice")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu nice time";
            } else if (name.equals("system") && key.contains("system")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu system time";
            } else if (name.equals("user") && key.contains("user")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "cpu user time";
            } else if (name.equals("load") && key.contains("load")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "processor load";
            } else if (name.equals("usage") && key.contains("usage")) {
                cpu = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "system cpu usage average";
            }
        }
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    if (cpu.equals("")) {
        return new CPU(
                "Error: Please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
    }

    return new CPU(hostid, metricType, cpu, clock);
}

From source file:demo.jaxrs.client.Client.java

public void updateCustomerInfo(String name, String password) throws Exception {

    System.out.println("HTTP PUT to update customer info, user : " + name + ", password : " + password);
    PutMethod put = new PutMethod("http://localhost:9002/customerservice/customers/123");
    setMethodHeaders(put, name, password);
    RequestEntity entity = new InputStreamRequestEntity(
            this.getClass().getClassLoader().getResourceAsStream("update_customer.xml"));
    put.setRequestEntity(entity);/*w ww.  j av a 2s.com*/

    handleHttpMethod(put);
}

From source file:CertStreamCallback.java

private static HttpMethod getHttpMethod(String url, String method) {
    if ("delete".equals(method)) {
        return new DeleteMethod(url);

    } else if ("get".equals(method)) {
        return new GetMethod(url);

    } else if ("post".equals(method)) {
        return new PostMethod(url);

    } else if ("put".equals(method)) {
        return new PutMethod(url);

    } else {/*from   w w w . jav a 2s  .  c  o  m*/
        throw ActionException.create(ClientMessages.NO_METHOD1, method);
    }
}

From source file:com.owncloud.android.lib.resources.files.UploadRemoteFileOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;

    try {/*from  w w w  . j a va2s.  c om*/
        // / perform the upload
        synchronized (mCancellationRequested) {
            if (mCancellationRequested.get()) {
                throw new OperationCancelledException();
            } else {
                mPutMethod = new PutMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath));
            }
        }

        int status = uploadFile(client);

        result = new RemoteOperationResult(isSuccess(status), status,
                (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));

    } catch (Exception e) {
        if (mCancellationRequested.get()) {
            result = new RemoteOperationResult(new OperationCancelledException());
        } else {
            result = new RemoteOperationResult(e);
        }
    }
    return result;
}

From source file:javaapplicationclientrest.ControllerCliente.java

public void atualizarNoticia(String id, String titulo) {
    PutMethod p = new PutMethod(String.format(Constants.PUT_NOTICIA, id, titulo));

    try {//from   w  w w.  j a  va 2 s.c om

        int statusCode = http.executeMethod(p);

        System.out.println(p.getStatusText());
    } catch (IOException ex) {
        Logger.getLogger(ControllerCliente.class.getName()).log(Level.SEVERE, null, ex);
    }

}