Search in sources :

Example 6 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-api-java-client by google.

the class ClientLogin method authenticate.

/**
 * Authenticates based on the provided field values.
 *
 * @throws ClientLoginResponseException if the authentication response has an error code, such as
 *         for a CAPTCHA challenge.
 */
public Response authenticate() throws IOException {
    GenericUrl url = serverUrl.clone();
    url.appendRawPath("/accounts/ClientLogin");
    HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this));
    request.setParser(AuthKeyValueParser.INSTANCE);
    request.setContentLoggingLimit(0);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    // check for an HTTP success response (2xx)
    if (response.isSuccessStatusCode()) {
        return response.parseAs(Response.class);
    }
    HttpResponseException.Builder builder = new HttpResponseException.Builder(response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
    // On error, throw a ClientLoginResponseException with the parsed error details
    ErrorInfo details = response.parseAs(ErrorInfo.class);
    String detailString = details.toString();
    StringBuilder message = HttpResponseException.computeMessageBuffer(response);
    if (!Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    throw new ClientLoginResponseException(builder, details);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl)

Example 7 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-api-java-client by google.

the class MethodOverrideTest method testInterceptMaxLength.

public void testInterceptMaxLength() throws IOException {
    HttpTransport transport = new MockHttpTransport();
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.set("a", "foo");
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.GET, request.getRequestMethod());
    assertNull(request.getHeaders().get(MethodOverride.HEADER));
    assertNull(request.getContent());
    char[] arr = new char[MethodOverride.MAX_URL_LENGTH];
    Arrays.fill(arr, 'x');
    url.set("a", new String(arr));
    request.setUrl(url);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.POST, request.getRequestMethod());
    assertEquals(HttpMethods.GET, request.getHeaders().get(MethodOverride.HEADER));
    assertEquals(HttpTesting.SIMPLE_GENERIC_URL, request.getUrl());
    char[] arr2 = new char[arr.length + 2];
    Arrays.fill(arr2, 'x');
    arr2[0] = 'a';
    arr2[1] = '=';
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    content.writeTo(out);
    assertEquals(new String(arr2), out.toString());
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 8 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-auth-library-java by google.

the class ServiceAccountCredentials method refreshAccessToken.

/**
 * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
 */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (createScopedRequired()) {
        throw new IOException("Scopes not configured for service account. Scoped should be specified" + " by calling createScoped or passing scopes to constructor.");
    }
    JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
    long currentTime = clock.currentTimeMillis();
    String assertion = createAssertion(jsonFactory, currentTime);
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("grant_type", GRANT_TYPE);
    tokenRequest.set("assertion", assertion);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
    request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()).setBackOffRequired(new BackOffRequired() {

        public boolean isRequired(HttpResponse response) {
            int code = response.getStatusCode();
            return (// Server error --- includes timeout errors, which use 500 instead of 408
            code / 100 == 5 || // https://github.com/google/google-api-java-client/issues/662
            code == 403);
        }
    }));
    HttpResponse response;
    try {
        response = request.execute();
    } catch (IOException e) {
        throw new IOException("Error getting access token for service account: ", e);
    }
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000L;
    return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonFactory(com.google.api.client.json.JsonFactory) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) IOException(java.io.IOException) GenericUrl(com.google.api.client.http.GenericUrl) BackOffRequired(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired) GenericData(com.google.api.client.util.GenericData) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) Date(java.sql.Date) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Example 9 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-auth-library-java by google.

the class UserCredentials method refreshAccessToken.

/**
 * Refreshes the OAuth2 access token by getting a new access token from the refresh token
 */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (refreshToken == null) {
        throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token.");
    }
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("client_id", clientId);
    tokenRequest.set("client_secret", clientSecret);
    tokenRequest.set("refresh_token", refreshToken);
    tokenRequest.set("grant_type", GRANT_TYPE);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(JSON_FACTORY));
    HttpResponse response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
    return new AccessToken(accessToken, new Date(expiresAtMilliseconds));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) GenericData(com.google.api.client.util.GenericData) Date(java.util.Date) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Example 10 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project googleads-java-lib by googleads.

the class ReportServiceLoggerTest method setUp.

/**
 * Sets all instance variables to values for a successful request. Tests that require failed
 * requests or null/empty values should mutate the instance variables accordingly.
 */
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    requestMethod = "POST";
    url = "http://www.foo.com/bar";
    reportServiceLogger = new ReportServiceLogger(loggerDelegate);
    requestFactory = new NetHttpTransport().createRequestFactory();
    // Constructs the request headers and adds headers that should be scrubbed
    rawRequestHeaders = ReportServiceLogger.SCRUBBED_HEADERS.stream().collect(Collectors.toMap(h -> h, h -> "foo" + h));
    // Adds headers that should not be scrubbed.
    rawRequestHeaders.put("clientCustomerId", "123-456-7890");
    rawRequestHeaders.put("someOtherHeader", "SomeOtherValue");
    GenericData postData = new GenericData();
    postData.put("__rdquery", "SELECT CampaignId FROM CAMPAIGN_PERFORMANCE_REPORT");
    httpRequest = requestFactory.buildPostRequest(new GenericUrl(url), new UrlEncodedContent(postData));
    for (Entry<String, String> rawHeaderEntry : rawRequestHeaders.entrySet()) {
        String key = rawHeaderEntry.getKey();
        if ("authorization".equalsIgnoreCase(key)) {
            httpRequest.getHeaders().setAuthorization(Collections.<String>singletonList(rawHeaderEntry.getValue()));
        } else {
            httpRequest.getHeaders().put(key, rawHeaderEntry.getValue());
        }
    }
    httpRequest.getResponseHeaders().setContentType("text/csv; charset=UTF-8");
    httpRequest.getResponseHeaders().put("someOtherResponseHeader", "foo");
    httpRequest.getResponseHeaders().put("multiValueHeader", Arrays.<String>asList("value1", "value2"));
}
Also used : NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) Matchers.containsString(org.hamcrest.Matchers.containsString) GenericData(com.google.api.client.util.GenericData) Before(org.junit.Before)

Aggregations

UrlEncodedContent (com.google.api.client.http.UrlEncodedContent)12 GenericUrl (com.google.api.client.http.GenericUrl)9 HttpRequest (com.google.api.client.http.HttpRequest)8 HttpResponse (com.google.api.client.http.HttpResponse)6 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)5 JsonObjectParser (com.google.api.client.json.JsonObjectParser)5 GenericData (com.google.api.client.util.GenericData)5 IOException (java.io.IOException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Date (java.util.Date)2 Credential (com.google.api.client.auth.oauth2.Credential)1 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)1 EmptyContent (com.google.api.client.http.EmptyContent)1 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)1 HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)1 BackOffRequired (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired)1 HttpContent (com.google.api.client.http.HttpContent)1 HttpHeaders (com.google.api.client.http.HttpHeaders)1 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)1 HttpResponseException (com.google.api.client.http.HttpResponseException)1