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.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.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    PutMethod put = new PutMethod(url);
    put.setDoAuthentication(true);/*from  ww  w .  java  2  s .  c o m*/

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

        // get the status code
        System.out.println("Response status code: " + result);

        // Display response
        System.out.println("Response body: ");
        System.out.println(put.getResponseBodyAsString());

        output += result;

    } catch (Exception e) {
        System.out.println("Something went wrong with UploadSpatialResource");
        e.printStackTrace(System.out);
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
    }

    return output;
}

From source file:org.ala.spatial.util.UploadSpatialResource.java

/**
 * sends a PUT or POST call to a URL using authentication and including a
 * file upload/*from   w  w  w. ja  v a 2s .  c o  m*/
 *
 * @param type         one of UploadSpatialResource.PUT for a PUT call or
 *                     UploadSpatialResource.POST for a POST call
 * @param url          URL for PUT/POST call
 * @param username     account username for authentication
 * @param password     account password for authentication
 * @param resourcepath local path to file to upload, null for no file to
 *                     upload
 * @param contenttype  file MIME content type
 * @return server response status code as String or empty String if
 * unsuccessful
 */
public static String httpCall(int type, String url, String username, String password, String resourcepath,
        String contenttype) {
    String output = "";

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

    RequestEntity entity = null;
    if (resourcepath != null) {
        File input = new File(resourcepath);
        entity = new FileRequestEntity(input, contenttype);
    }

    HttpMethod call = null;
    ;
    if (type == PUT) {
        PutMethod put = new PutMethod(url);
        put.setDoAuthentication(true);
        if (entity != null) {
            put.setRequestEntity(entity);
        }
        call = put;
    } else if (type == POST) {
        PostMethod post = new PostMethod(url);
        if (entity != null) {
            post.setRequestEntity(entity);
        }
        call = post;
    } else {
        SpatialLogger.log("UploadSpatialResource", "invalid type: " + type);
        return output;
    }

    // Execute the request 
    try {
        int result = client.executeMethod(call);

        output += result;
    } catch (Exception e) {
        SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url);
    } finally {
        // Release current connection to the connection pool once you are done 
        call.releaseConnection();
    }

    return output;
}

From source file:org.alfresco.custom.rest.httpconnector.RemoteClientImpl.java

private org.apache.commons.httpclient.HttpMethod createRequestMethod(HttpMethod requestMethod,
        URI redirectURL) {/*from   ww  w .j  a va  2 s .  co m*/
    org.apache.commons.httpclient.HttpMethod method = null;

    switch (requestMethod) {
    default:
    case GET:
        method = new GetMethod(redirectURL.toString());
        break;
    case PUT:
        method = new PutMethod(redirectURL.toString());
        break;
    case POST:
        method = new PostMethod(redirectURL.toString());
        break;
    case DELETE:
        method = new DeleteMethod(redirectURL.toString());
        break;
    case HEAD:
        method = new HeadMethod(redirectURL.toString());
        break;
    }

    // Switch off automatic redirect handling as we want to process them
    // ourselves and maintain cookies
    method.setFollowRedirects(false);

    return method;
}

From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java

/**
 * @see org.alfresco.jive.JiveOpenClient#updateDocument(java.lang.String, java.lang.String, java.lang.String, long, java.lang.String)
 */// www  .  j  a  v a2s .  co  m
@Override
public void updateDocument(final String userId, final String cmisId, final String fileName, final long fileSize,
        final String mimeType) throws AuthenticationException, CallFailedException, DocumentNotFoundException,
        ServiceUnavailableException, DocumentSizeException {
    final PutMethod put = new PutMethod(buildUrl(OPENCLIENT_API_UPDATE_DOCUMENT));
    final PostMethod temp = new PostMethod();
    int status = -1;

    setCommonHeaders(userId, put);
    put.setRequestHeader("Content-Type", MIME_TYPE_FORM_URLENCODED);

    // These shenanigans are required because PutMethod doesn't directly support content as NameValuePairs.
    temp.setRequestBody(constructNameValuePairs(cmisId, fileName, fileSize, mimeType));
    put.setRequestEntity(temp.getRequestEntity());

    try {
        status = callJive(put);

        if (status >= 400) {
            if (status == 401 || status == 403) {
                throw new AuthenticationException();
            } else if (status == 404) {
                throw new DocumentNotFoundException(cmisId);
            } else if (status == 409) {
                throw new DocumentSizeException(fileName, fileSize);
            } else if (status == 503) {
                throw new ServiceUnavailableException();
            } else {
                throw new CallFailedException(status);
            }
        } else if (status >= 300) {
            log.warn("Status code: " + status + ". cmisObjectID: " + cmisId);
        }
    } catch (final HttpException he) {
        throw new CallFailedException(he);
    } catch (final IOException ioe) {
        throw new CallFailedException(ioe);
    } finally {
        put.releaseConnection();
    }
}

From source file:org.alfresco.repo.remoteconnector.RemoteConnectorRequestImpl.java

protected static HttpMethodBase buildHttpClientMethod(String url, String method) {
    if ("GET".equals(method)) {
        return new GetMethod(url);
    }/*from  ww  w .ja v a2 s  .c o  m*/
    if ("POST".equals(method)) {
        return new PostMethod(url);
    }
    if ("PUT".equals(method)) {
        return new PutMethod(url);
    }
    if ("DELETE".equals(method)) {
        return new DeleteMethod(url);
    }
    if (TestingMethod.METHOD_NAME.equals(method)) {
        return new TestingMethod(url);
    }
    throw new UnsupportedOperationException("Method '" + method + "' not supported");
}

From source file:org.alfresco.repo.web.scripts.BaseWebScriptTest.java

/**
 * Send Remote Request to stand-alone Web Script Server
 * /*from w  ww  .j  av a2 s .c  o  m*/
 * @param req Request
 * @param expectedStatus int
 * @return response
 * @throws IOException
 */
protected Response sendRemoteRequest(Request req, int expectedStatus) throws IOException {
    String uri = req.getFullUri();
    if (!uri.startsWith("http")) {
        uri = remoteServer.baseAddress + uri;
    }

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        GetMethod get = new GetMethod(req.getFullUri());
        httpMethod = get;
    } else if (method.equalsIgnoreCase("POST")) {
        PostMethod post = new PostMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PATCH")) {
        PatchMethod post = new PatchMethod(req.getFullUri());
        post.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = post;
    } else if (method.equalsIgnoreCase("PUT")) {
        PutMethod put = new PutMethod(req.getFullUri());
        put.setRequestEntity(new ByteArrayRequestEntity(req.getBody(), req.getType()));
        httpMethod = put;
    } else if (method.equalsIgnoreCase("DELETE")) {
        DeleteMethod del = new DeleteMethod(req.getFullUri());
        httpMethod = del;
    } else {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }
    if (req.getHeaders() != null) {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet()) {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }

    // execute method
    httpClient.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod);
}

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse put(final RequestContext rq, Binding cmisBinding, String version, String cmisOperation,
        final String body) throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), cmisBinding, version, cmisOperation,
            null);//  w  w  w  . j  a v a  2s.  c  om
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url.toString());
    if (body != null) {
        StringRequestEntity requestEntity = null;
        if (cmisBinding.equals(Binding.atom)) {
            requestEntity = new StringRequestEntity(body, "text/xml", "UTF-8");
        } else if (cmisBinding.equals(Binding.browser)) {
            requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
        }
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse put(final Class<?> c, final RequestContext rq, final Object entityId,
        final Object relationshipEntityId, final String body) throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url);
    if (body != null) {
        StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
        req.setRequestEntity(requestEntity);
    }/*from www .  j  a  v a 2  s  .co  m*/
    return submitRequest(req, rq);
}

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse put(final RequestContext rq, final String scope, final int version,
        final String entityCollectionName, final Object entityId, final String relationCollectionName,
        final Object relationshipEntityId, final String body, Map<String, String> params) throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName,
            entityId, relationCollectionName, relationshipEntityId, params);
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url);
    if (body != null) {
        StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
        req.setRequestEntity(requestEntity);
    }//  w  ww.ja v  a2 s  .  com
    return submitRequest(req, rq);
}

From source file:org.alfresco.rest.api.tests.client.PublicApiHttpClient.java

public HttpResponse putBinary(final RequestContext rq, final String scope, final int version,
        final String entityCollectionName, final Object entityId, final String relationCollectionName,
        final Object relationshipEntityId, final BinaryPayload payload, final Map<String, String> params)
        throws IOException {
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName,
            entityId, relationCollectionName, relationshipEntityId, params);
    String url = endpoint.getUrl();

    PutMethod req = new PutMethod(url);
    if (payload != null) {
        BinaryRequestEntity requestEntity = new BinaryRequestEntity(payload.getFile(), payload.getMimeType(),
                payload.getCharset());//from   ww  w. ja  v a 2 s .  c  o m
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}