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:org.ngrinder.agent.controller.AgentManagerRestAPIControllerTest.java

@Ignore
@Test/*from  ww  w. jav a  2 s . c  om*/
public void testRestAPI() throws IOException {
    HttpClient client = new HttpClient();
    // To be avoided unless in debug mode
    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "111111");
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    PutMethod method = new PutMethod("http://localhost:8080/agent/api/36");
    final HttpMethodParams params = new HttpMethodParams();
    params.setParameter("action", "approve");
    method.setParams(params);
    final int i = client.executeMethod(method);
    System.out.println(method.getResponseBodyAsString());
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Upload a file to the Scality system.//w  w  w  . j  a  va  2 s.  com
 *
 * @param file
 * @return The file identifier (file digest) under which a file will be
 *         stored in the scality system
 */
protected String uploadFile(File file) {
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    PutMethod putMethod = new PutMethod(url);
    try {
        String contentMD5 = DigestGenerator.getMD5Checksum(file);
        String stringToSign = StringGenerator.getStringToSign(HTTPMethod.PUT, "", DEFAULT_CONTENT_TYPE,
                bucketName, contentMD5, new Date());
        String authorizationString = StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret);
        putMethod.addRequestHeader("Authorization", authorizationString);
        putMethod.addRequestHeader("x-amz-date", StringGenerator.getCurrentDateString());
        putMethod.setPath("/" + contentMD5);
        putMethod.setRequestEntity(new FileRequestEntity(file, DEFAULT_CONTENT_TYPE));
        log.debug(">>>" + authorizationString + "<<<");
        log.debug(">>" + stringToSign + "<<");
        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(putMethod);
        if (returnCode != HttpStatus.SC_OK) {
            String failedUploadMsg = "File upload failed for " + file.getName() + " Error:" + returnCode;
            log.debug(failedUploadMsg);
            throw new RuntimeException(failedUploadMsg);
        }
        log.debug(returnCode + putMethod.getResponseBodyAsString());
        putMethod.releaseConnection();
        log.debug(returnCode + putMethod.getResponseBodyAsString());
        return contentMD5;
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Creates a new bucket in the scality system.
 *
 * @param bucketName//ww  w .ja v a 2  s  .c  o m
 * @return true if a new bucket was created
 * @throws ScalityBucketExistsException
 */
public boolean createBucket(String bucketName) {
    boolean bucketExists = false;
    String remoteFileName = "";// no file needed to create the bucket
    String url = PROTOCOL_PREFIX + bucketName + "." + this.hostBase;
    log.debug(url);
    PutMethod putMethod = new PutMethod(url);
    String contentMD5 = "";
    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.PUT, contentMD5, DEFAULT_CONTENT_TYPE,
            bucketName, remoteFileName, new Date());

    // check if the bucket exists before trying to create it
    if (bucketExists(bucketName)) {
        return false;
    }

    try {
        putMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));

        log.debug("Using this stringToSign:" + stringToSign + " to create a bucket");
        putMethod.addRequestHeader("x-amz-date", StringGenerator.getCurrentDateString());
        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(putMethod);
        log.debug(putMethod.getResponseBodyAsString());
        if (returnCode != -1) {
            if (returnCode == HttpStatus.SC_OK) {
                bucketExists = true;
            }
        }
        putMethod.releaseConnection();
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return bucketExists;
}

From source file:org.nuxeo.ecm.platform.web.common.ajax.AjaxProxyServlet.java

protected static String doRequest(String method, String targetURL, HttpServletRequest req) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod httpMethod;//from  ww  w. ja  v a2  s. c o m

    if ("GET".equals(method)) {
        httpMethod = new GetMethod(targetURL);
    } else if ("POST".equals(method)) {
        httpMethod = new PostMethod(targetURL);
        ((PostMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else if ("PUT".equals(method)) {
        httpMethod = new PutMethod(targetURL);
        ((PutMethod) httpMethod).setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
    } else {
        throw new IllegalStateException("Unknown HTTP method: " + method);
    }

    Map<String, String[]> params = req.getParameterMap();
    for (String paramName : params.keySet()) {
        httpMethod.getParams().setParameter(paramName, params.get(paramName));
    }

    client.executeMethod(httpMethod);
    String body = httpMethod.getResponseBodyAsString();
    httpMethod.releaseConnection();
    return body;
}

From source file:org.nuxeo.ecm.webdav.WebDavClientTest.java

protected void doTestPutFile(String name, byte[] bytes, String mimeType, String expectedType) throws Exception {
    InputStream is = new ByteArrayInputStream(bytes);
    PutMethod method = new PutMethod(ROOT_URI + name);
    method.setRequestEntity(new InputStreamRequestEntity(is, bytes.length, mimeType));
    int status = client.executeMethod(method);
    assertEquals(HttpStatus.SC_CREATED, status);

    // check using Nuxeo Core APIs
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    PathRef pathRef = new PathRef("/workspaces/workspace/" + name);
    assertTrue(session.exists(pathRef));
    DocumentModel doc = session.getDocument(pathRef);
    assertEquals(expectedType, doc.getType());
    assertEquals(name, doc.getTitle());//from  w w  w  .j  av a  2s. c o  m
    BlobHolder bh = doc.getAdapter(BlobHolder.class);
    assertNotNull(bh);
    Blob blob = bh.getBlob();
    assertNotNull(blob);
    assertEquals(bytes.length, blob.getLength());
    assertEquals(mimeType, blob.getMimeType());
    assertArrayEquals(bytes, blob.getByteArray());
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;//  w w  w .j  a v a  2s  . c om
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.obm.caldav.client.AbstractPushTest.java

protected Document putQuery(Document doc) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DOMUtils.serialise(doc, out);//from   w  w w .  j a  v  a  2 s  . c o  m
    PutMethod pfq = new PutMethod(url);
    appendHeader(pfq, out);
    appendBody(pfq, out);
    Document ret = doRequest(pfq);
    return ret;
}

From source file:org.olat.admin.registration.SystemRegistrationManager.java

/**
 * Send the registration data now. If the user configured nothing to send, nothing will be sent.
 *///from w w w .ja va2s .c  o  m
public void sendRegistrationData() {
    // Do it optimistic and try to generate the XML message. If the message
    // doesn't contain anything, the user does not want to register this
    // instance
    final String registrationData = getRegistrationPropertiesMessage(null);
    String registrationKey = persitedProperties.getStringPropertyValue(CONF_SECRETKEY, false);
    if (StringHelper.containsNonWhitespace(registrationData)) {
        // only send when there is something to send
        final HttpClient client = HttpClientFactory.getHttpClientInstance();
        client.getParams().setParameter("http.useragent", "OLAT Registration Agent ; " + VERSION);
        final String url = REGISTRATION_SERVER
                + persitedProperties.getStringPropertyValue(CONF_KEY_IDENTIFYER, false) + "/";
        logInfo("URL:" + url, null);
        final PutMethod method = new PutMethod(url);
        if (registrationKey != null) {
            // updating
            method.setRequestHeader("Authorization", registrationKey);
            if (isLogDebugEnabled()) {
                logDebug("Authorization: " + registrationKey, null);
            } else {
                logDebug("Authorization: EXISTS", null);
            }
        } else {
            logInfo("Authorization: NONE", null);
        }
        method.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
        try {
            method.setRequestEntity(new StringRequestEntity(registrationData, "application/xml", "UTF8"));
            client.executeMethod(method);
            final int status = method.getStatusCode();
            if (status == HttpStatus.SC_NOT_MODIFIED || status == HttpStatus.SC_OK) {
                logInfo("Successfully registered OLAT installation on olat.org server, thank you for your support!",
                        null);
                registrationKey = method.getResponseBodyAsString();
                persitedProperties.setStringProperty(CONF_SECRETKEY, registrationKey, false);
                persitedProperties.savePropertiesAndFireChangedEvent();
            } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                logError("File could be created not on registration server::"
                        + method.getStatusLine().toString(), null);
            } else if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                logInfo(method.getResponseBodyAsString(), method.getStatusText());
            } else {
                logError("Unexpected HTTP Status::" + method.getStatusLine().toString()
                        + " during registration call", null);
            }
        } catch (final Exception e) {
            logError("Unexpected exception during registration call", e);
        }
    } else {
        logWarn("****************************************************************************************************************************************************************************",
                null);
        logWarn("* This OLAT installation is not registered. Please, help us with your statistical data and register your installation under Adminisration - Systemregistration. THANK YOU! *",
                null);
        logWarn("****************************************************************************************************************************************************************************",
                null);
    }
}

From source file:org.olat.test.OlatJerseyTestCase.java

public PutMethod createPut(final URI requestURI, final String accept, final boolean cookie) {
    final PutMethod method = new PutMethod(requestURI.toString());
    if (cookie) {
        method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    }//from  w ww  .  j a  v a  2s .c o  m
    if (StringHelper.containsNonWhitespace(accept)) {
        method.addRequestHeader("Accept", accept);
    }
    method.addRequestHeader("Accept-Language", "en");
    return method;
}

From source file:org.openhab.binding.garadget.internal.Connection.java

/**
 * Factory method to create a {@link HttpMethod}-object according to the
 * given String <code>httpMethod</code>
 *
 * @param httpMethodString//w  w w  . jav a 2s  .  co m
 *            the name of the {@link HttpMethod} to create
 * @param url
 *            the URL to include in the returned Method
 * @return
 *         an object of type {@link GetMethod}, {@link PutMethod},
 *         {@link PostMethod} or {@link DeleteMethod}
 * @throws
 *             IllegalArgumentException if <code>httpMethod</code> is none of
 *             <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code>
 */
private static HttpMethod createHttpMethod(String httpMethodString, String url) {

    if (HTTP_GET.equals(httpMethodString)) {
        return new GetMethod(url);
    } else if (HTTP_PUT.equals(httpMethodString)) {
        return new PutMethod(url);
    } else if (HTTP_POST.equals(httpMethodString)) {
        return new PostMethod(url);
    } else if (HTTP_DELETE.equals(httpMethodString)) {
        return new DeleteMethod(url);
    } else {
        throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown");
    }
}