Search in sources :

Example 41 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project cloudstack by apache.

the class Action method executePut.

protected void executePut(final String uri, final StringRequestEntity entity) throws NeutronRestApiException {
    try {
        validateCredentials();
    } catch (NeutronInvalidCredentialsException e) {
        throw new NeutronRestApiException("Invalid credentials!", e);
    }
    NeutronRestFactory factory = NeutronRestFactory.getInstance();
    NeutronRestApi neutronRestApi = factory.getNeutronApi(PutMethod.class);
    PutMethod putMethod = (PutMethod) neutronRestApi.createMethod(url, uri);
    try {
        putMethod.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
        putMethod.setRequestEntity(entity);
        String encodedCredentials = encodeCredentials();
        putMethod.setRequestHeader("Authorization", "Basic " + encodedCredentials);
        neutronRestApi.executeMethod(putMethod);
        if (putMethod.getStatusCode() != HttpStatus.SC_OK) {
            String errorMessage = responseToErrorMessage(putMethod);
            putMethod.releaseConnection();
            s_logger.error("Failed to update object : " + errorMessage);
            throw new NeutronRestApiException("Failed to update object : " + errorMessage);
        }
    } catch (NeutronRestApiException e) {
        s_logger.error("NeutronRestApiException caught while trying to execute HTTP Method on the Neutron Controller", e);
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    } finally {
        putMethod.releaseConnection();
    }
}
Also used : NeutronRestFactory(org.apache.cloudstack.network.opendaylight.api.NeutronRestFactory) NeutronRestApi(org.apache.cloudstack.network.opendaylight.api.NeutronRestApi) NeutronInvalidCredentialsException(org.apache.cloudstack.network.opendaylight.api.NeutronInvalidCredentialsException) PutMethod(org.apache.commons.httpclient.methods.PutMethod) NeutronRestApiException(org.apache.cloudstack.network.opendaylight.api.NeutronRestApiException)

Example 42 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project hive by apache.

the class TestWebHCatE2e method doHttpCall.

/**
 * Does a basic HTTP GET and returns Http Status code + response body
 * Will add the dummy user query string
 */
private static MethodCallRetVal doHttpCall(String uri, HTTP_METHOD_TYPE type, Map<String, Object> data, NameValuePair[] params) throws IOException {
    HttpClient client = new HttpClient();
    HttpMethod method;
    switch(type) {
        case GET:
            method = new GetMethod(uri);
            break;
        case DELETE:
            method = new DeleteMethod(uri);
            break;
        case PUT:
            method = new PutMethod(uri);
            if (data == null) {
                break;
            }
            String msgBody = JsonBuilder.mapToJson(data);
            LOG.info("Msg Body: " + msgBody);
            StringRequestEntity sre = new StringRequestEntity(msgBody, "application/json", charSet);
            ((PutMethod) method).setRequestEntity(sre);
            break;
        default:
            throw new IllegalArgumentException("Unsupported method type: " + type);
    }
    if (params == null) {
        method.setQueryString(new NameValuePair[] { new NameValuePair("user.name", username) });
    } else {
        NameValuePair[] newParams = new NameValuePair[params.length + 1];
        System.arraycopy(params, 0, newParams, 1, params.length);
        newParams[0] = new NameValuePair("user.name", username);
        method.setQueryString(newParams);
    }
    String actualUri = "no URI";
    try {
        // should this be escaped string?
        actualUri = method.getURI().toString();
        LOG.debug(type + ": " + method.getURI().getEscapedURI());
        int httpStatus = client.executeMethod(method);
        LOG.debug("Http Status Code=" + httpStatus);
        String resp = method.getResponseBodyAsString();
        LOG.debug("response: " + resp);
        return new MethodCallRetVal(httpStatus, resp, actualUri, method.getName());
    } catch (IOException ex) {
        LOG.error("doHttpCall() failed", ex);
    } finally {
        method.releaseConnection();
    }
    return new MethodCallRetVal(-1, "Http " + type + " failed; see log file for details", actualUri, method.getName());
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) IOException(java.io.IOException) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 43 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project SSM by Intel-bigdata.

the class ZeppelinHubRealm method authenticateUser.

/**
 * Send to ZeppelinHub a login request based on the request body which is a JSON that contains 2
 * fields "login" and "password".
 *
 * @param requestBody JSON string of ZeppelinHub payload.
 * @return Account object with login, name (if set in ZeppelinHub), and mail.
 * @throws AuthenticationException if fail to login.
 */
protected User authenticateUser(String requestBody) {
    PutMethod put = new PutMethod(Joiner.on("/").join(zeppelinhubUrl, USER_LOGIN_API_ENDPOINT));
    String responseBody = StringUtils.EMPTY;
    String userSession = StringUtils.EMPTY;
    try {
        put.setRequestEntity(new StringRequestEntity(requestBody, JSON_CONTENT_TYPE, UTF_8_ENCODING));
        int statusCode = httpClient.executeMethod(put);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Cannot login user, HTTP status code is {} instead on 200 (OK)", statusCode);
            put.releaseConnection();
            throw new AuthenticationException("Couldnt login to ZeppelinHub. " + "Login or password incorrect");
        }
        responseBody = put.getResponseBodyAsString();
        userSession = put.getResponseHeader(USER_SESSION_HEADER).getValue();
        put.releaseConnection();
    } catch (IOException e) {
        LOG.error("Cannot login user", e);
        throw new AuthenticationException(e.getMessage());
    }
    User account = null;
    try {
        account = gson.fromJson(responseBody, User.class);
    } catch (JsonParseException e) {
        LOG.error("Cannot deserialize ZeppelinHub response to User instance", e);
        throw new AuthenticationException("Cannot login to ZeppelinHub");
    }
    onLoginSuccess(account.login, userSession);
    return account;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) AuthenticationException(org.apache.shiro.authc.AuthenticationException) PutMethod(org.apache.commons.httpclient.methods.PutMethod) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException)

Example 44 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project zeppelin by apache.

the class ZeppelinHubRealm method authenticateUser.

/**
   * Send to ZeppelinHub a login request based on the request body which is a JSON that contains 2 
   * fields "login" and "password".
   * 
   * @param requestBody JSON string of ZeppelinHub payload.
   * @return Account object with login, name (if set in ZeppelinHub), and mail.
   * @throws AuthenticationException if fail to login.
   */
protected User authenticateUser(String requestBody) {
    PutMethod put = new PutMethod(Joiner.on("/").join(zeppelinhubUrl, USER_LOGIN_API_ENDPOINT));
    String responseBody = StringUtils.EMPTY;
    String userSession = StringUtils.EMPTY;
    try {
        put.setRequestEntity(new StringRequestEntity(requestBody, JSON_CONTENT_TYPE, UTF_8_ENCODING));
        int statusCode = httpClient.executeMethod(put);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Cannot login user, HTTP status code is {} instead on 200 (OK)", statusCode);
            put.releaseConnection();
            throw new AuthenticationException("Couldnt login to ZeppelinHub. " + "Login or password incorrect");
        }
        responseBody = put.getResponseBodyAsString();
        userSession = put.getResponseHeader(USER_SESSION_HEADER).getValue();
        put.releaseConnection();
    } catch (IOException e) {
        LOG.error("Cannot login user", e);
        throw new AuthenticationException(e.getMessage());
    }
    User account = null;
    try {
        account = gson.fromJson(responseBody, User.class);
    } catch (JsonParseException e) {
        LOG.error("Cannot deserialize ZeppelinHub response to User instance", e);
        throw new AuthenticationException("Cannot login to ZeppelinHub");
    }
    // Add ZeppelinHub user_session token this singleton map, this will help ZeppelinHubRepo
    // to get specific information about the current user.
    UserSessionContainer.instance.setSession(account.login, userSession);
    /* TODO(khalid): add proper roles and add listener */
    HashSet<String> userAndRoles = new HashSet<String>();
    userAndRoles.add(account.login);
    ZeppelinServer.notebookWsServer.broadcastReloadedNoteList(new org.apache.zeppelin.user.AuthenticationInfo(account.login), userAndRoles);
    return account;
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) AuthenticationException(org.apache.shiro.authc.AuthenticationException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HashSet(java.util.HashSet)

Example 45 with PutMethod

use of org.apache.commons.httpclient.methods.PutMethod in project pinot by linkedin.

the class WebHdfsV1Client method uploadSegment.

// This method is based on:
// https://hadoop.apache.org/docs/r1.0.4/webhdfs.html#CREATE
public synchronized boolean uploadSegment(String webHdfsPath, String localFilePath) {
    // Step 1: Submit a HTTP PUT request without automatically following
    // redirects and without sending the file data.
    String firstPutReqString = String.format(WEB_HDFS_UPLOAD_PATH_TEMPLATE, _protocol, _host, _port, webHdfsPath, _overwrite, _permission);
    HttpMethod firstPutReq = new PutMethod(firstPutReqString);
    try {
        LOGGER.info("Trying to send request: {}.", firstPutReqString);
        int firstResponseCode = _httpClient.executeMethod(firstPutReq);
        if (firstResponseCode != 307) {
            LOGGER.error(String.format("Failed to execute the first PUT request to upload segment to webhdfs: %s. " + "Expected response code 307, but get %s. Response body: %s", firstPutReqString, firstResponseCode, firstPutReq.getResponseBodyAsString()));
            return false;
        }
    } catch (Exception e) {
        LOGGER.error(String.format("Failed to execute the first request to upload segment to webhdfs: %s.", firstPutReqString), e);
        return false;
    } finally {
        firstPutReq.releaseConnection();
    }
    // Step 2: Submit another HTTP PUT request using the URL in the Location
    // header with the file data to be written.
    String redirectedReqString = firstPutReq.getResponseHeader(LOCATION).getValue();
    PutMethod redirectedReq = new PutMethod(redirectedReqString);
    File localFile = new File(localFilePath);
    RequestEntity requestEntity = new FileRequestEntity(localFile, "application/binary");
    redirectedReq.setRequestEntity(requestEntity);
    try {
        LOGGER.info("Trying to send request: {}.", redirectedReqString);
        int redirectedResponseCode = _httpClient.executeMethod(redirectedReq);
        if (redirectedResponseCode != 201) {
            LOGGER.error(String.format("Failed to execute the redirected PUT request to upload segment to webhdfs: %s. " + "Expected response code 201, but get %s. Response: %s", redirectedReqString, redirectedResponseCode, redirectedReq.getResponseBodyAsString()));
        }
        return true;
    } catch (IOException e) {
        LOGGER.error(String.format("Failed to execute the redirected request to upload segment to webhdfs: %s.", redirectedReqString), e);
        return false;
    } finally {
        redirectedReq.releaseConnection();
    }
}
Also used : FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) PutMethod(org.apache.commons.httpclient.methods.PutMethod) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) File(java.io.File) HttpMethod(org.apache.commons.httpclient.HttpMethod) IOException(java.io.IOException)

Aggregations

PutMethod (org.apache.commons.httpclient.methods.PutMethod)94 Test (org.junit.Test)49 GetMethod (org.apache.commons.httpclient.methods.GetMethod)29 AbstractHttpTest (org.xwiki.test.rest.framework.AbstractHttpTest)21 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)19 Page (org.xwiki.rest.model.jaxb.Page)15 HttpClient (org.apache.commons.httpclient.HttpClient)14 IOException (java.io.IOException)13 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)13 DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)10 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)7 DeleteMethod (org.apache.jackrabbit.webdav.client.methods.DeleteMethod)7 Link (org.xwiki.rest.model.jaxb.Link)7 Header (org.apache.commons.httpclient.Header)6 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 FileRequestEntity (org.apache.commons.httpclient.methods.FileRequestEntity)6 File (java.io.File)5 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)5 Object (org.xwiki.rest.model.jaxb.Object)5