Example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

/**
 * post a resource/*from   w w  w .  j  a va  2  s  .  c o  m*/
 * 
 * @param repoPath
 *            path in registry
 * @param resource
 *            resource to be posted, given in as input stream
 * @return
 * @throws RegistryExtException
 * @throws HttpException
 * @throws IOException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 */
public String postResource(String repoPath, ResourceISType resource)
        throws RegistryExtException, HttpException, IOException, OAuthSystemException, OAuthProblemException {

    Map<String, Object> session = ActionContext.getContext().getSession();

    int statusCode = 200;
    String accessToken = (String) session.get(Constants.SESSION_TOKEN);

    String requestURL = composeURL(FILEOPPREFIX, repoPath);

    if (logger.isDebugEnabled()) {
        logger.debug("Put request URL=" + requestURL);
    }

    HttpClient httpclient = new HttpClient();
    PutMethod put = new PutMethod(requestURL);
    put.addRequestHeader("Content-Type", resource.getMediaType());
    put.addRequestHeader("Authorization", "Bearer " + accessToken);
    put.setRequestEntity(new InputStreamRequestEntity(resource.getIs()));

    try {

        httpclient.executeMethod(put);
        statusCode = put.getStatusLine().getStatusCode();

        /* handle token expiration */
        if (statusCode == 401) {
            logger.info(String.format("Access token %s expired, going to refresh it", accessToken));

            refreshToken(session);

            // use refreshed access token
            accessToken = (String) session.get(Constants.SESSION_TOKEN);
            put.addRequestHeader("Authorization", "Bearer " + accessToken);

            // re-send the request
            httpclient.executeMethod(put);

            statusCode = put.getStatusLine().getStatusCode();

        }

        if (statusCode != 204) {
            throw new RegistryExtException(
                    "Failed in put resource : HTTP error code : " + put.getStatusLine().getStatusCode());
        }

    } finally {
        if (put != null)
            put.releaseConnection();
    }

    return repoPath;
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

private void publishShapefile(String workspace, String datastore, String shp) {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/" + workspace + "/datastores/" + datastore
            + "/external.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "text/plain");
    put.setRequestEntity(new StringRequestEntity(shp));
    put.setDoAuthentication(true);/*from w  w  w. j a  v  a  2  s .  c  om*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }
}

From source file:com.owncloud.android.lib.resources.shares.UpdateRemoteShareOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    /// prepare array of parameters to update
    List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>();
    if (mPassword != null) {
        parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword));
    }/* www.  j a v a 2  s .co  m*/
    if (mExpirationDateInMillis < 0) {
        // clear expiration date
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, ""));

    } else if (mExpirationDateInMillis > 0) {
        // set expiration date
        DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE);
        Calendar expirationDate = Calendar.getInstance();
        expirationDate.setTimeInMillis(mExpirationDateInMillis);
        String formattedExpirationDate = dateFormat.format(expirationDate.getTime());
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate));

    } // else, ignore - no update

    /* TODO complete rest of parameters
    if (mPermissions > 0) {
    parametersToUpdate.add(new Pair("permissions", Integer.toString(mPermissions)));
    }
    if (mPublicUpload != null) {
    parametersToUpdate.add(new Pair("publicUpload", mPublicUpload.toString());
    }
    */

    /// perform required PUT requests
    PutMethod put = null;
    String uriString = null;

    try {
        Uri requestUri = client.getBaseUri();
        Uri.Builder uriBuilder = requestUri.buildUpon();
        uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1));
        uriBuilder.appendEncodedPath(Long.toString(mRemoteId));
        uriString = uriBuilder.build().toString();

        for (Pair<String, String> parameter : parametersToUpdate) {
            if (put != null) {
                put.releaseConnection();
            }
            put = new PutMethod(uriString);
            put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
            put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second,
                    ENTITY_CONTENT_TYPE, ENTITY_CHARSET));

            status = client.executeMethod(put);

            if (status == HttpStatus.SC_OK) {
                String response = put.getResponseBodyAsString();

                // Parse xml response
                ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser(
                        new ShareXMLParser());
                parser.setOwnCloudVersion(client.getOwnCloudVersion());
                parser.setServerBaseUri(client.getBaseUri());
                result = parser.parse(response);

            } else {
                result = new RemoteOperationResult(false, status, put.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while updating remote share ", e);
        if (put != null) {
            put.releaseConnection();
        }

    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
    return result;
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_PUT_Local() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme/datastores/zeleznice/external.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "text/plain");
    put.setRequestEntity(new StringRequestEntity("file:///data/shpdata/cr-shp-wgs84/linie/zeleznice.shp"));
    put.setDoAuthentication(true);/*from   w  w w. ja  va2s. c om*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(put.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }

    return "http://localhost:8080/geoserver/acme/wms?service=WMS&version=1.3.0&request=GetCapabilities";
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String testREST_PUT() {
    String strURL = "http://localhost:8080/geoserver/rest/workspaces/acme/datastores/reky/file.shp";
    PutMethod put = new PutMethod(strURL);

    put.setRequestHeader("Content-type", "application/zip");
    put.setRequestEntity(new FileRequestEntity(new File("reky.zip"), "application/zip"));
    put.setDoAuthentication(true);/*from  w ww  . j ava 2  s .  c  om*/

    HttpClient httpclient = new HttpClient();

    Credentials defaultcreds = new UsernamePasswordCredentials("admin", "geoserver");
    httpclient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    try {

        int response = httpclient.executeMethod(put);

        System.out.println("Response: ");
        BufferedReader br = new BufferedReader(new InputStreamReader(put.getResponseBodyAsStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        //System.out.println(post.getResponseBodyAsStream());

    } catch (IOException ex) {
        Logger.getLogger(Examples.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        put.releaseConnection();
    }

    return "TestREST2";
}

From source file:com.intuit.tank.http.BaseRequest.java

/**
 * Execute the post. Use this to force the type of response
 * //from  w w  w.  j a  v  a  2 s.  c  o  m
 * @param newResponse
 *            The response object to populate
 */
public void doPut(BaseResponse response) {
    PutMethod httpput = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        httpput = new PutMethod(url.toString());
        String requestBody = this.getBody(); // Multiple calls can be
                                             // expensive, so get it once
        StringRequestEntity entity;

        entity = new StringRequestEntity(requestBody, getContentType(), contentTypeCharSet);
        httpput.setRequestEntity(entity);
        sendRequest(response, httpput, requestBody);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (null != httpput)
            httpput.releaseConnection();
    }
}

From source file:com.cerema.cloud2.lib.resources.shares.UpdateRemoteShareOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    /// prepare array of parameters to update
    List<Pair<String, String>> parametersToUpdate = new ArrayList<Pair<String, String>>();
    if (mPassword != null) {
        parametersToUpdate.add(new Pair<String, String>(PARAM_PASSWORD, mPassword));
    }//from www .  ja  v  a2  s.c om
    if (mExpirationDateInMillis < 0) {
        // clear expiration date
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, ""));

    } else if (mExpirationDateInMillis > 0) {
        // set expiration date
        DateFormat dateFormat = new SimpleDateFormat(FORMAT_EXPIRATION_DATE);
        Calendar expirationDate = Calendar.getInstance();
        expirationDate.setTimeInMillis(mExpirationDateInMillis);
        String formattedExpirationDate = dateFormat.format(expirationDate.getTime());
        parametersToUpdate.add(new Pair(PARAM_EXPIRATION_DATE, formattedExpirationDate));

    } // else, ignore - no update
    if (mPermissions > 0) {
        // set permissions
        parametersToUpdate.add(new Pair(PARAM_PERMISSIONS, Integer.toString(mPermissions)));
    }

    if (mPublicUpload != null) {
        parametersToUpdate.add(new Pair(PARAM_PUBLIC_UPLOAD, Boolean.toString(mPublicUpload)));
    }

    /// perform required PUT requests
    PutMethod put = null;
    String uriString = null;

    try {
        Uri requestUri = client.getBaseUri();
        Uri.Builder uriBuilder = requestUri.buildUpon();
        uriBuilder.appendEncodedPath(ShareUtils.SHARING_API_PATH.substring(1));
        uriBuilder.appendEncodedPath(Long.toString(mRemoteId));
        uriString = uriBuilder.build().toString();

        for (Pair<String, String> parameter : parametersToUpdate) {
            if (put != null) {
                put.releaseConnection();
            }
            put = new PutMethod(uriString);
            put.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
            put.setRequestEntity(new StringRequestEntity(parameter.first + "=" + parameter.second,
                    ENTITY_CONTENT_TYPE, ENTITY_CHARSET));

            status = client.executeMethod(put);

            if (status == HttpStatus.SC_OK) {
                String response = put.getResponseBodyAsString();

                // Parse xml response
                ShareToRemoteOperationResultParser parser = new ShareToRemoteOperationResultParser(
                        new ShareXMLParser());
                parser.setOwnCloudVersion(client.getOwnCloudVersion());
                parser.setServerBaseUri(client.getBaseUri());
                result = parser.parse(response);

            } else {
                result = new RemoteOperationResult(false, status, put.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while updating remote share ", e);
        if (put != null) {
            put.releaseConnection();
        }

    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
    return result;
}

From source file:com.panet.imeta.cluster.SlaveServer.java

public String sendXML(String xml, String service) throws Exception {
    // The content
    // /*  ww w . j ava  2s.com*/
    byte[] content = xml.getBytes(Const.XML_ENCODING);

    // Prepare HTTP put
    // 
    String urlString = constructUrl(service);
    log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ConnectingTo", urlString)); //$NON-NLS-1$
    PutMethod put = new PutMethod(urlString);

    // Request content will be retrieved directly from the input stream
    // 
    RequestEntity entity = new ByteArrayRequestEntity(content);

    put.setRequestEntity(entity);
    put.setDoAuthentication(true);
    put.addRequestHeader(new Header("Content-Type", "text/xml;charset=" + Const.XML_ENCODING));

    // post.setContentChunked(true);

    // Get HTTP client
    // 
    HttpClient client = new HttpClient();
    addCredentials(client);

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

        // The status code
        log.logDebug(toString(),
                Messages.getString("SlaveServer.DEBUG_ResponseStatus", Integer.toString(result))); //$NON-NLS-1$

        // the response
        InputStream inputStream = new BufferedInputStream(put.getResponseBodyAsStream(), 1000);

        StringBuffer bodyBuffer = new StringBuffer();
        int c;
        while ((c = inputStream.read()) != -1)
            bodyBuffer.append((char) c);
        inputStream.close();
        String bodyTmp = bodyBuffer.toString();

        switch (result) {
        case 401: // Security problem: authentication required
            // Non-internationalized message
            String message = "Authentication failed" + Const.DOSCR + Const.DOSCR + bodyTmp; //$NON-NLS-1$
            WebResult webResult = new WebResult(WebResult.STRING_ERROR, message);
            bodyBuffer.setLength(0);
            bodyBuffer.append(webResult.getXML());
            break;
        }

        String body = bodyBuffer.toString();

        // String body = post.getResponseBodyAsString(); 
        log.logDebug(toString(), Messages.getString("SlaveServer.DEBUG_ResponseBody", body)); //$NON-NLS-1$

        return body;
    } finally {
        // Release current connection to the connection pool once you are done
        put.releaseConnection();
        log.logDetailed(toString(),
                Messages.getString("SlaveServer.DETAILED_SentXmlToService", service, hostname)); //$NON-NLS-1$
    }
}

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

@Override
public UserQueryResult findUsers(Long userId, String name, int offset, int limit, UserOrder sortOrder,
        boolean ascending) {
    PutMethod method = new PutMethod(baseUrl + QUERY);

    UserQuery request = new UserQuery();
    request.setUserId(userId);/*from  w w  w.  j  a  va2s  .  co  m*/
    request.setUserName(name);
    request.setQueryOffset(offset);
    request.setQueryLimit(limit);
    request.setAscending(ascending);
    request.setOrder(sortOrder);

    try {
        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 null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, UserQueryResult.class);

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

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:de.mpg.mpdl.inge.pubman.web.sword.SwordUtil.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * //w  w  w  .  ja va 2  s  . c  o  m
 * @param InputStream to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(InputStream in, String mimetype, String userHandle, ZipEntry zipEntry)
        throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = PropertyReader.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    InitialContext context = new InitialContext();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}