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:eu.learnpad.rest.utils.internal.DefaultRestUtils.java

@Override
public boolean putAttachment(String spaceName, String pageName, String attachmentName, byte[] attachment) {
    HttpClient httpClient = getClient();

    String uri = REST_URI + "/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName + "/attachments/"
            + attachmentName;/*from  www. ja v  a  2  s  . c  o  m*/
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", "application/xml");
    putMethod.addRequestHeader("Accept-Ranges", "bytes");
    RequestEntity fileRequestEntity = new ByteArrayRequestEntity(attachment, "application/xml");
    putMethod.setRequestEntity(fileRequestEntity);
    try {
        httpClient.executeMethod(putMethod);
        return true;
    } catch (HttpException e) {
        logger.error("Unable to process PUT request for the attachment '" + spaceName + "." + pageName + "/"
                + attachmentName + "'.", e);
        return false;
    } catch (IOException e) {
        logger.error(
                "Unable to PUT the attachment '" + spaceName + "." + pageName + "/" + attachmentName + "'.", e);
        return false;
    }
}

From source file:com.utest.webservice.client.rest.RestClient.java

public HttpMethod createPut(String service, String path, Map<String, Object> parameters) {
    PutMethod put = new PutMethod(baseUrl + servicePath + service + "/" + path + paramsToString(parameters));
    setHeader(put);/*from  w  w  w.  ja  v a2s  .  c o m*/
    return put;
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Setup the request.// w w  w  .  ja v  a2  s .co  m
 *
 * @param context the context
 */
protected void setupRequest(ProxyContext context) {
    // set the proxy to send requests through
    ExternalProxySettings externalProxy = context.getExternalProxySettings();
    if (externalProxy != null) {
        String proxyServer = externalProxy.getProxyServer();

        if (proxyServer != null) {
            context.getTarget().getHostConfig().setProxy(proxyServer, externalProxy.getProxyPort());
            if (context.getProxyCredentials() != null) {
                context.getHttpClient().getState().setProxyCredentials(ProxyUtil.getDefaultAuthScope(),
                        context.getProxyCredentials());
            }
        }
    }

    String method = context.getMethod();
    String encodedPath = context.getTarget().getEncodedPath();
    if (MessageIOConstants.METHOD_POST.equals(method)) {
        FlexPostMethod postMethod = new FlexPostMethod(encodedPath);
        context.setHttpMethod(postMethod);
        if (context.hasAuthorization()) {
            postMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_GET.equals(method)) {
        FlexGetMethod getMethod = new FlexGetMethod(context.getTarget().getEncodedPath());
        context.setHttpMethod(getMethod);
        if (context.hasAuthorization()) {
            getMethod.setConnectionForced(true);
        }
    } else if (ProxyConstants.METHOD_HEAD.equals(method)) {
        HeadMethod headMethod = new HeadMethod(encodedPath);
        context.setHttpMethod(headMethod);
    } else if (ProxyConstants.METHOD_PUT.equals(method)) {
        PutMethod putMethod = new PutMethod(encodedPath);
        context.setHttpMethod(putMethod);
    } else if (ProxyConstants.METHOD_OPTIONS.equals(method)) {
        OptionsMethod optionsMethod = new OptionsMethod(encodedPath);
        context.setHttpMethod(optionsMethod);
    } else if (ProxyConstants.METHOD_DELETE.equals(method)) {
        DeleteMethod deleteMethod = new DeleteMethod(encodedPath);
        context.setHttpMethod(deleteMethod);
    } else if (ProxyConstants.METHOD_TRACE.equals(method)) {
        TraceMethod traceMethod = new TraceMethod(encodedPath);
        context.setHttpMethod(traceMethod);
    } else {
        ProxyException pe = new ProxyException(INVALID_METHOD);
        pe.setDetails(INVALID_METHOD, "1", new Object[] { method });
        throw pe;
    }

    HttpMethodBase httpMethod = context.getHttpMethod();
    if (httpMethod instanceof EntityEnclosingMethod) {
        ((EntityEnclosingMethod) httpMethod).setContentChunked(context.getContentChunked());
    }
}

From source file:au.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.setConnectionTimeout(10000);//from www  .j a v a  2s.  c o  m
    client.setTimeout(60000);

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

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

    // 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);

        output = result + ": " + put.getResponseBodyAsString();

    } catch (Exception e) {
        output = "0: " + e.getMessage();
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:net.sf.ufsc.http.HttpFile.java

/**
 * @see net.sf.ufsc.File#getOutputStream()
 *//*from w w  w  .  j a v a 2 s  .c o m*/
public OutputStream getOutputStream(boolean append) throws java.io.IOException {
    if (append)
        throw new UnsupportedOperationException();

    final java.io.File file = java.io.File.createTempFile("ufsc", null); //$NON-NLS-1$

    StreamClosedListener listener = new StreamClosedListener() {
        public void closed(StreamClosedEvent event) throws IOException {
            PutMethod method = new PutMethod(HttpFile.this.getURI().toString());

            try {
                InputStream inputStream = new FileInputStream(file);

                method.setRequestEntity(new InputStreamRequestEntity(inputStream));

                HttpFile.this.execute(method);

                inputStream.close();
            } finally {
                method.releaseConnection();

                file.delete();
            }
        }
    };

    return new OutputStreamAdapter(new FileOutputStream(file), listener);
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag,
        Collection<Pair<String, String>> headers) throws IOException {
    boolean done = false;
    PutMethod put = null;/*from   ww  w  . j  a va 2 s .co  m*/
    while (!done) {
        put = new PutMethod(mBaseUrl + href);
        put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType));
        if (mDebugEnabled && contentType.startsWith("text"))
            ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8"));
        if (etag != null)
            put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag);
        if (headers != null)
            for (Pair<String, String> h : headers)
                put.addRequestHeader(h.getFirst(), h.getSecond());
        executeMethod(put, Depth.zero);
        int ret = put.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = put.getResponseHeader("Location");
            if (newLocation != null) {
                href = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + href);
                put.releaseConnection();
                continue;
            }
        }
        done = true;
    }
    return new HttpInputStream(put);
}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs an HTTP request against an URL.
 *
 * @param url         the URL to call//  www.  j av a  2 s . co m
 * @param method      the HTTP method to execute
 * @param body        the body of a POST or PUT request, can be <code>null</code>
 * @param queryParams a Hash with the query parameter, can be <code>null</code>
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 */
@SuppressWarnings("deprecation")
public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) {

    NameValuePair[] query = null;

    if (queryParams != null) {
        query = new NameValuePair[queryParams.size()];

        int counter = 0;
        for (Entry<String, String> queryParam : queryParams.entrySet()) {
            query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue());
            counter++;
        }
    }

    org.apache.commons.httpclient.HttpMethod request = null;

    if (method == HttpMethod.GET) {
        request = new GetMethod(url);
    } else if (method == HttpMethod.POST) {
        PostMethod postRequest = new PostMethod(url);
        if (body != null) {
            postRequest.setRequestBody(body);
        }
        request = postRequest;
    } else if (method == HttpMethod.PUT) {
        PutMethod putRequest = new PutMethod(url);
        if (body != null) {
            putRequest.setRequestBody(body);
        }
        request = putRequest;
    } else if (method == HttpMethod.DELETE) {
        request = new DeleteMethod(url);
    }

    request.setRequestHeader("Content-type", "application/xml;charset=utf-8");
    if (query != null) {
        request.setQueryString(query);
    }

    int resultCode = 0;
    StringBuilder resultBodyBuilder = new StringBuilder();

    try {
        resultCode = this.httpClient.executeMethod(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8")));
        String line = null;
        while ((line = reader.readLine()) != null) {
            resultBodyBuilder.append(line);
        }

        if (resultCode != 200) {
            throw new HttpException(resultBodyBuilder.toString(), null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP request failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP request failed", ioException);
    } catch (NullPointerException npe) {
        throw new HttpException("HTTP request failed", npe);
    } finally {
        request.releaseConnection();
    }

    return resultBodyBuilder.toString();
}

From source file:ServiceController.java

@RequestMapping("/service")
public @ResponseBody Service service(
        @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);/*  w  w 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

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);

    // content-type is controlled in api_jsonrpc.php, so set it like this
    putMethod.setRequestHeader("Content-Type", "application/json-rpc");
    String request = setRequest("net.tcp.service", authentication, hostid);

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

    return serviceResponse(hostid, putMethod, name);
}

From source file:eu.impact_project.resultsrepository.DavHandlerTest.java

@Test
public void testRetrieveTextFile() throws HttpException, IOException {
    DavHandler dav = new DavHandler(folders);

    InputStream stream = new ByteArrayInputStream("some text".getBytes());
    PutMethod putMethod = new PutMethod("http://localhost:9002/parent/child/textToRetrieve.txt");
    putMethod.setRequestEntity(new InputStreamRequestEntity(stream));
    HttpClient client = new HttpClient();
    client.executeMethod(putMethod);/*  w w w.  j a v  a 2 s .co  m*/
    stream.close();
    putMethod.releaseConnection();

    String retrieved = dav.retrieveTextFile("http://localhost:9002/parent/child/textToRetrieve.txt");
    assertEquals("some text", retrieved);
}

From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchIndex.java

private void initializeIndex() {
    if (haveMappingInfo) {
        return;// w w  w.  ja v a  2 s  . co  m
    }
    if (!refreshIndexIfNecessary()) {
        try {
            ElasticSearchConnector connector = new ElasticSearchConnector();
            JSONObject mappingInfo = createMappingInfo();
            PutMethod putMethod = new PutMethod(ElasticSearchConnector.actualUrl(indexUrl));
            putMethod.setRequestEntity(new StringRequestEntity(mappingInfo.toString(),
                    MimeConstants.CT_APPLICATION_JSON, MimeConstants.P_CHARSET_UTF8));
            int statusCode = connector.executeMethod(putMethod);
            if (statusCode == HttpStatus.SC_OK) {
                haveMappingInfo = true;
                refreshIndexIfNecessary(); // Sometimes searches don't seem to honor mapping info.  Try to force it
            } else {
                ZimbraLog.index.error("Problem Setting mapping information for index with key=%s httpstatus=%d",
                        key, statusCode);
            }
        } catch (HttpException e) {
            ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
        } catch (IOException e) {
            ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
        } catch (JSONException e) {
            ZimbraLog.index.error("Problem Setting mapping information for index with key=" + key, e);
        }
    }
}