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.indiana.d2i.registryext.RegistryExtAgent.java

/**
 * post a resource//from  www.  j a v  a  2  s .co 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:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void updatePassword(Long userId, String newPassword) {
    String resource = String.format(baseUrl + SET_PASSWORD, userId);
    PutMethod method = new PutMethod(resource);
    try {//  w  w w . ja  va  2s  .  c om
        ChangeUserPasswordRequest request = new ChangeUserPasswordRequest();
        request.setPassword(newPassword);
        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;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public void kpisImported(String modelSetId, String kpisId, KPIsFormat type) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/kpisimported/%s/%s", DefaultRestResource.REST_URI,
            modelSetId, kpisId);/*from  w w w. j ava  2s.c  o m*/
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", "application/xml");
    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("type", type.toString());
    putMethod.setQueryString(queryString);
    try {
        httpClient.executeMethod(putMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String putMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {/* w  w  w . j ava  2  s  .c o m*/
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PutMethod method = new PutMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Create the HTTP method./*from   www  .j  a v  a2 s.  c o m*/
 * <br/>A GetMethod will be created if the RequestEntity associated with
 * the ContentProvider is null. Otherwise, a PostMethod will be created.
 * @return the HTTP method
 */
private HttpMethodBase createMethod() throws IOException {
    HttpMethodBase method = null;
    MethodName name = this.getMethodName();

    // make the method
    if (name == null) {
        if (this.getContentProvider() == null) {
            this.setMethodName(MethodName.GET);
            method = new GetMethod(this.getUrl());
        } else {
            this.setMethodName(MethodName.POST);
            method = new PostMethod(this.getUrl());
        }
    } else if (name.equals(MethodName.DELETE)) {
        method = new DeleteMethod(this.getUrl());
    } else if (name.equals(MethodName.GET)) {
        method = new GetMethod(this.getUrl());
    } else if (name.equals(MethodName.POST)) {
        method = new PostMethod(this.getUrl());
    } else if (name.equals(MethodName.PUT)) {
        method = new PutMethod(this.getUrl());
    }

    // write the request body if necessary
    if (this.getContentProvider() != null) {
        if (method instanceof EntityEnclosingMethod) {
            EntityEnclosingMethod eMethod = (EntityEnclosingMethod) method;
            RequestEntity eAdapter = getContentProvider() instanceof MultiPartContentProvider
                    ? new MultiPartProviderAdapter(this, eMethod,
                            (MultiPartContentProvider) getContentProvider())
                    : new ApacheEntityAdapter(this, this.getContentProvider());
            eMethod.setRequestEntity(eAdapter);
            if (eAdapter.getContentType() != null) {
                eMethod.setRequestHeader("Content-type", eAdapter.getContentType());
            }
        } else {
            // TODO: possibly will need an exception here in the future
        }
    }

    // set headers, add the retry method
    for (Map.Entry<String, String> hdr : this.requestHeaders.entrySet()) {
        method.addRequestHeader(hdr.getKey(), hdr.getValue());
    }

    // declare possible gzip handling
    method.setRequestHeader("Accept-Encoding", "gzip");

    this.addRetryHandler(method);
    return method;
}

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

@Override
public void setUserAttribute(Long userId, String key, String value) {
    String resource = String.format(baseUrl + USER_ATTRIBUTES + "/" + key, userId);
    PutMethod method = new PutMethod(resource);
    try {// w  ww.j a va 2 s .  c  o  m
        method.setRequestEntity(new StringRequestEntity(value, "text/plain", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

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

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateScope(String scope, String description, Integer ccExpiresIn, Integer passExpiresIn) {
    PutMethod put = new PutMethod(baseOAuth20Uri + SCOPE_ENDPOINT + "/" + scope);
    String response = null;//from   ww w.j  a  va 2  s.  c om
    try {
        JSONObject json = new JSONObject();
        json.put("description", description);
        json.put("cc_expires_in", ccExpiresIn);
        json.put("pass_expires_in", passExpiresIn);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update scope", e);
    } catch (JSONException e) {
        log.error("cannot update scope", e);
    }
    return response;
}

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 ww  . j  a  va 2s.  c  o  m

    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.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void updateCurrency(Currency currency) {
    String resource = String.format(baseUrl + CURRENCIES, currency.getCode());
    PutMethod method = new PutMethod(resource);
    try {/*w  w  w  .ja  v  a2 s .  c o  m*/
        String data = serialize(currency);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

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

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateClientApp(String clientId, String scope, String description, Integer status,
        String redirectUri) {/*from   w  w w  .ja  v  a  2 s. co m*/
    PutMethod put = new PutMethod(baseOAuth20Uri + APPLICATION_ENDPOINT + "/" + clientId);
    String response = null;
    try {
        //put.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId));
        JSONObject json = new JSONObject();
        json.put("status", status);
        json.put("description", description);
        json.put("redirect_uri", redirectUri);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update client app", e);
    } catch (JSONException e) {
        log.error("cannot update client app", e);
    }
    return response;
}