com.google.api.client.http.UrlEncodedContent Java Examples

The following examples show how to use com.google.api.client.http.UrlEncodedContent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MastodonHttpUtilities.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
/** Posts a new status for the user, initially marked as private.**/
public void postStatus(String content, String idempotencyKey) throws IOException {
  ImmutableMap<String, String> formParams = ImmutableMap.of(
      "status", content,
      // Default everything to private to avoid a privacy incident
      "visibility", "private"
  );
  UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams);
  HttpRequest postRequest = TRANSPORT.createRequestFactory()
      .buildPostRequest(
          new GenericUrl(baseUrl + POST_URL),
          urlEncodedContent)
      .setThrowExceptionOnExecuteError(false);
  HttpHeaders headers = new HttpHeaders();
  headers.setAuthorization("Bearer " + accessToken);
  if (!Strings.isNullOrEmpty(idempotencyKey)) {
    // This prevents the same post from being posted twice in the case of network errors
    headers.set("Idempotency-Key", idempotencyKey);
  }
  postRequest.setHeaders(headers);

  HttpResponse response = postRequest.execute();

  validateResponse(postRequest, response, 200);
}
 
Example #2
Source File: OAuth2DataGenerator.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Override
public AuthData generateAuthData(String callbackBaseUrl, String authCode, String id,
    AuthData initialAuthData, String extra) {
  Preconditions.checkArgument(
      Strings.isNullOrEmpty(extra), "Extra data not expected for OAuth flow");
  Preconditions.checkArgument(initialAuthData == null,
      "Initial auth data not expected for " + config.getServiceName());

  Map<String, String> params = new LinkedHashMap<>();
  params.put("client_id", clientId);
  params.put("client_secret", clientSecret);
  params.put("grant_type", "authorization_code");
  params.put("redirect_uri", callbackBaseUrl);
  params.put("code", authCode);

  HttpContent content = new UrlEncodedContent(params);

  try {
    String tokenResponse = OAuthUtils.makeRawPostRequest(
        httpTransport, config.getTokenUrl(), content);

    return config.getResponseClass(tokenResponse);
  } catch (IOException e) {
    throw new RuntimeException("Error getting token", e); // TODO
  }
}
 
Example #3
Source File: MethodOverride.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void intercept(HttpRequest request) throws IOException {
  if (overrideThisMethod(request)) {
    String requestMethod = request.getRequestMethod();
    request.setRequestMethod(HttpMethods.POST);
    request.getHeaders().set(HEADER, requestMethod);
    if (requestMethod.equals(HttpMethods.GET)) {
      // take the URI query part and put it into the HTTP body
      request.setContent(new UrlEncodedContent(request.getUrl().clone()));
      // remove query parameters from URI
      request.getUrl().clear();
    } else if (request.getContent() == null) {
      // Google servers will fail to process a POST unless the Content-Length header is specified
      request.setContent(new EmptyContent());
    }
  }
}
 
Example #4
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Login an exiting Kickflip User and make it active.
 *
 * @param username The Kickflip user's username
 * @param password The Kickflip user's password
 * @param cb       This callback will receive a User in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)}
 *                 or an Exception {@link io.kickflip.sdk.api.KickflipCallback#onError(io.kickflip.sdk.exception.KickflipException)}.
 */
public void loginUser(String username, final String password, final KickflipCallback cb) {
    GenericData data = new GenericData();
    data.put("username", username);
    data.put("password", password);

    post(GET_USER_PRIVATE, new UrlEncodedContent(data), User.class, new KickflipCallback() {
        @Override
        public void onSuccess(final Response response) {
            if (VERBOSE)
                Log.i(TAG, "loginUser response: " + response);
            storeNewUserResponse((User) response, password);
            postResponseToCallback(cb, response);
        }

        @Override
        public void onError(final KickflipException error) {
            Log.w(TAG, "loginUser Error: " + error);
            postExceptionToCallback(cb, error);
        }
    });
}
 
Example #5
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Get public user info
 *
 * @param username The Kickflip user's username
 * @param cb       This callback will receive a User in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)}
 *                 or an Exception {@link io.kickflip.sdk.api.KickflipCallback#onError(io.kickflip.sdk.exception.KickflipException)}.
 */
public void getUserInfo(String username, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    data.put("username", username);

    post(GET_USER_PUBLIC, new UrlEncodedContent(data), User.class, new KickflipCallback() {
        @Override
        public void onSuccess(final Response response) {
            if (VERBOSE)
                Log.i(TAG, "getUserInfo response: " + response);
            postResponseToCallback(cb, response);
        }

        @Override
        public void onError(final KickflipException error) {
            Log.w(TAG, "getUserInfo Error: " + error);
            postExceptionToCallback(cb, error);
        }
    });
}
 
Example #6
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Start a new Stream owned by the given User. Must be called after
 * {@link io.kickflip.sdk.api.KickflipApiClient#createNewUser(KickflipCallback)}
 * Delivers stream endpoint destination data via a {@link io.kickflip.sdk.api.KickflipCallback}.
 *
 * @param user The Kickflip User on whose behalf this request is performed.
 * @param cb   This callback will receive a Stream subclass in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)}
 *             depending on the Kickflip account type. Implementors should
 *             check if the response is instanceof HlsStream, StartRtmpStreamResponse, etc.
 */
private void startStreamWithUser(User user, Stream stream, final KickflipCallback cb) {
    checkNotNull(user);
    checkNotNull(stream);
    GenericData data = new GenericData();
    data.put("uuid", user.getUUID());
    data.put("private", stream.isPrivate());
    if (stream.getTitle() != null) {
        data.put("title", stream.getTitle());
    }
    if (stream.getDescription() != null) {
        data.put("description", stream.getDescription());
    }
    if (stream.getExtraInfo() != null) {
        data.put("extra_info", new Gson().toJson(stream.getExtraInfo()));
    }
    post(START_STREAM, new UrlEncodedContent(data), HlsStream.class, cb);
}
 
Example #7
Source File: ReportServiceLogger.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) {
  StringBuilder messageBuilder = new StringBuilder();
  if (headers != null) {
    appendMapAsString(messageBuilder, headers);
  }
  if (content != null) {
    messageBuilder.append(String.format("%nContent:%n"));
    if (content instanceof UrlEncodedContent) {
      UrlEncodedContent encodedContent = (UrlEncodedContent) content;
      appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData()));
    } else if (content != null) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      try {
        content.writeTo(byteStream);
        messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name()));
      } catch (IOException e) {
        messageBuilder.append("Unable to read request content due to exception: " + e);
      }
    }
  }
  return messageBuilder.toString();
}
 
Example #8
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testConstructor_expiredBody() throws Exception {
  HttpRequest request =
      subtestConstructor_expired(BearerToken.formEncodedBodyAccessMethod(), new CheckAuth() {

        public boolean checkAuth(MockLowLevelHttpRequest req) {
          return NEW_ACCESS_TOKEN.equals(((Map<?, ?>) ((UrlEncodedContent) req
              .getStreamingContent()).getData()).get("access_token"));
        }
      });
  assertEquals(NEW_ACCESS_TOKEN,
      ((Map<?, ?>) ((UrlEncodedContent) request.getContent()).getData()).get("access_token"));
}
 
Example #9
Source File: CredentialTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void testConstructor_body() throws Exception {
  Credential credential =
      new Credential(BearerToken.formEncodedBodyAccessMethod()).setAccessToken(ACCESS_TOKEN);
  HttpRequest request = subtestConstructor(credential);
  assertEquals(ACCESS_TOKEN,
      ((Map<?, ?>) ((UrlEncodedContent) request.getContent()).getData()).get("access_token"));
}
 
Example #10
Source File: ClientParametersAuthenticationTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void test() throws Exception {
  HttpRequest request = new MockHttpTransport().createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  ClientParametersAuthentication auth =
      new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET);
  assertEquals(CLIENT_ID, auth.getClientId());
  assertEquals(CLIENT_SECRET, auth.getClientSecret());
  auth.intercept(request);
  UrlEncodedContent content = (UrlEncodedContent) request.getContent();
  @SuppressWarnings("unchecked")
  Map<String, ?> data = (Map<String, ?>) content.getData();
  assertEquals(CLIENT_ID, data.get("client_id"));
  assertEquals(CLIENT_SECRET, data.get("client_secret"));
}
 
Example #11
Source File: ClientParametersAuthentication.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void intercept(HttpRequest request) throws IOException {
  Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
  data.put("client_id", clientId);
  if (clientSecret != null) {
    data.put("client_secret", clientSecret);
  }
}
 
Example #12
Source File: ClientParametersAuthenticationTest.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
public void test_noSecret() throws Exception {
  HttpRequest request = new MockHttpTransport().createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  ClientParametersAuthentication auth =
      new ClientParametersAuthentication(CLIENT_ID, null);
  assertEquals(CLIENT_ID, auth.getClientId());
  assertNull(auth.getClientSecret());
  auth.intercept(request);
  UrlEncodedContent content = (UrlEncodedContent) request.getContent();
  @SuppressWarnings("unchecked")
  Map<String, ?> data = (Map<String, ?>) content.getData();
  assertEquals(CLIENT_ID, data.get("client_id"));
  assertNull(data.get("client_secret"));
}
 
Example #13
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Get a List of {@link io.kickflip.sdk.api.json.Stream}s near a geographic location.
 * <p/>
 * This method searches all public recordings made by Users of your Kickflip app.
 *
 * @param location The target Location
 * @param radius   The target Radius in meters
 * @param cb       A callback to receive the resulting List of Streams
 */
public void getStreamsByLocation(Location location, int radius, int pageNumber, int itemsPerPage, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    data.put("uuid", getActiveUser().getUUID());
    data.put("lat", location.getLatitude());
    data.put("lon", location.getLongitude());
    if (radius != 0) {
        data.put("radius", radius);
    }
    post(SEARCH_GEO, new UrlEncodedContent(data), StreamList.class, cb);
}
 
Example #14
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Get a List of {@link io.kickflip.sdk.api.json.Stream}s containing a keyword.
 * <p/>
 * This method searches all public recordings made by Users of your Kickflip app.
 *
 * @param keyword The String keyword to query
 * @param cb      A callback to receive the resulting List of Streams
 */
public void getStreamsByKeyword(String keyword, int pageNumber, int itemsPerPage, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    addPaginationData(pageNumber, itemsPerPage, data);
    data.put("uuid", getActiveUser().getUUID());
    if (keyword != null) {
        data.put("keyword", keyword);
    }
    post(SEARCH_KEYWORD, new UrlEncodedContent(data), StreamList.class, cb);
}
 
Example #15
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Get a List of {@link io.kickflip.sdk.api.json.Stream} objects created by the given Kickflip User.
 *
 * @param username the target Kickflip username
 * @param cb       A callback to receive the resulting List of Streams
 */
public void getStreamsByUsername(String username, int pageNumber, int itemsPerPage, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    addPaginationData(pageNumber, itemsPerPage, data);
    data.put("uuid", getActiveUser().getUUID());
    data.put("username", username);
    post(SEARCH_USER, new UrlEncodedContent(data), StreamList.class, cb);
}
 
Example #16
Source File: MultipartFormDataContent.java    From Broadsheet.ie-Android with MIT License 5 votes vote down vote up
public MultipartFormDataContent addUrlEncodedContent(String name, String value) {
    GenericData data = new GenericData();
    data.put(value, "");

    Part part = new Part();
    part.setContent(new UrlEncodedContent(data));
    part.setName(name);

    this.addPart(part);

    return this;
}
 
Example #17
Source File: AwqlReportBodyProvider.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Override
public HttpContent getHttpContent() {
  Map<String, String> data = Maps.newHashMap();
  data.put(REPORT_QUERY_KEY, reportQuery);
  data.put(FORMAT_KEY, format);
  return new UrlEncodedContent(data);
}
 
Example #18
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Send Stream Metadata for a {@link io.kickflip.sdk.api.json.Stream}.
 * The target Stream must be owned by the User created with {@link io.kickflip.sdk.api.KickflipApiClient#createNewUser(KickflipCallback)}
 * from this KickflipApiClient.
 *
 * @param stream the {@link io.kickflip.sdk.api.json.Stream} to get Meta data for
 * @param cb     A callback to receive the updated Stream upon request completion
 */
public void setStreamInfo(Stream stream, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    data.put("stream_id", stream.getStreamId());
    data.put("uuid", getActiveUser().getUUID());
    if (stream.getTitle() != null) {
        data.put("title", stream.getTitle());
    }
    if (stream.getDescription() != null) {
        data.put("description", stream.getDescription());
    }
    if (stream.getExtraInfo() != null) {
        data.put("extra_info", new Gson().toJson(stream.getExtraInfo()));
    }
    if (stream.getLatitude() != 0) {
        data.put("lat", stream.getLatitude());
    }
    if (stream.getLongitude() != 0) {
        data.put("lon", stream.getLongitude());
    }
    if (stream.getCity() != null) {
        data.put("city", stream.getCity());
    }
    if (stream.getState() != null) {
        data.put("state", stream.getState());
    }
    if (stream.getCountry() != null) {
        data.put("country", stream.getCountry());
    }

    if (stream.getThumbnailUrl() != null) {
        data.put("thumbnail_url", stream.getThumbnailUrl());
    }

    data.put("private", stream.isPrivate());
    data.put("deleted", stream.isDeleted());

    post(SET_META, new UrlEncodedContent(data), Stream.class, cb);
}
 
Example #19
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Stop a Stream owned by the given Kickflip User.
 *
 * @param cb This callback will receive a Stream subclass in #onSuccess(response)
 *           depending on the Kickflip account type. Implementors should
 *           check if the response is instanceof HlsStream, etc.
 */
private void stopStream(User user, Stream stream, final KickflipCallback cb) {
    checkNotNull(stream);
    // TODO: Add start / stop lat lon to Stream?
    GenericData data = new GenericData();
    data.put("stream_id", stream.getStreamId());
    data.put("uuid", user.getUUID());
    if (stream.getLatitude() != 0) {
        data.put("lat", stream.getLatitude());
    }
    if (stream.getLongitude() != 0) {
        data.put("lon", stream.getLongitude());
    }
    post(STOP_STREAM, new UrlEncodedContent(data), HlsStream.class, cb);
}
 
Example #20
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Set the current active user's meta info. Pass a null argument to leave it as-is.
 *
 * @param newPassword the user's new password
 * @param email       the user's new email address
 * @param displayName The desired display name
 * @param extraInfo   Arbitrary String data to associate with this user.
 * @param cb          This callback will receive a User in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)}
 *                    or an Exception {@link io.kickflip.sdk.api.KickflipCallback#onError(io.kickflip.sdk.exception.KickflipException)}.
 */
public void setUserInfo(final String newPassword, String email, String displayName, Map extraInfo, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    final String finalPassword;
    if (newPassword != null){
        data.put("new_password", newPassword);
        finalPassword = newPassword;
    } else {
        finalPassword = getPasswordForActiveUser();
    }
    if (email != null) data.put("email", email);
    if (displayName != null) data.put("display_name", displayName);
    if (extraInfo != null) data.put("extra_info", new Gson().toJson(extraInfo));

    post(EDIT_USER, new UrlEncodedContent(data), User.class, new KickflipCallback() {
        @Override
        public void onSuccess(final Response response) {
            if (VERBOSE)
                Log.i(TAG, "setUserInfo response: " + response);
            storeNewUserResponse((User) response, finalPassword);
            postResponseToCallback(cb, response);
        }

        @Override
        public void onError(final KickflipException error) {
            Log.w(TAG, "setUserInfo Error: " + error);
            postExceptionToCallback(cb, error);
        }
    });
}
 
Example #21
Source File: MethodOverrideTest.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #22
Source File: TaskQueueNotificationServlet.java    From abelana with Apache License 2.0 5 votes vote down vote up
@Override
public final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
    throws IOException {
  HttpTransport httpTransport;
  try {
    Map<Object, Object> params = new HashMap<>();
    params.putAll(req.getParameterMap());
    params.put("task", req.getHeader("X-AppEngine-TaskName"));

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential.getApplicationDefault()
        .createScoped(Collections.singleton("https://www.googleapis.com/auth/userinfo.email"));
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    GenericUrl url = new GenericUrl(ConfigurationConstants.IMAGE_RESIZER_URL);

    HttpRequest request = requestFactory.buildPostRequest(url, new UrlEncodedContent(params));
    credential.initialize(request);

    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      log("Call to the imageresizer failed: " + response.getContent().toString());
      resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
    } else {
      resp.setStatus(response.getStatusCode());
    }

  } catch (GeneralSecurityException | IOException e) {
    log("Http request error: " + e.getMessage());
    resp.setStatus(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
  }
}
 
Example #23
Source File: MicrosoftParametersAuthentication.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void intercept(HttpRequest request) throws IOException {
  Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
  if (clientSecret != null) {
    data.put("client_assertion", clientSecret);
  }
  data.put("client_assertion_type", CLIENT_ASSERTION_TYPE);
  data.put("grant_type", GRANT_TYPE);
}
 
Example #24
Source File: ReportDefinitionBodyProvider.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
@Override
public HttpContent getHttpContent() {
  Map<String, String> data = Maps.newHashMap();
  data.put(REPORT_XML_KEY, reportDefinitionXml);
  return new UrlEncodedContent(data);
}
 
Example #25
Source File: ReportServiceLoggerTest.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * 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"));
}
 
Example #26
Source File: AuthorizationCodeFlow.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new instance of an authorization code token request based on the given authorization
 * code.
 *
 * <p>
 * This is used to make a request for an access token using the authorization code. It uses
 * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()},
 * {@link #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}.
 * </p>
 *
 * <pre>
static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code)
    throws IOException, TokenResponseException {
  return flow.newTokenRequest(code).setRedirectUri("https://client.example.com/rd").execute();
}
 * </pre>
 *
 * @param authorizationCode authorization code.
 */
public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {
  HttpExecuteInterceptor pkceClientAuthenticationWrapper = new HttpExecuteInterceptor() {
    @Override
    public void intercept(HttpRequest request) throws IOException {
      clientAuthentication.intercept(request);
      if (pkce != null) {
        Map<String, Object> data = Data.mapOf(UrlEncodedContent.getContent(request).getData());
        data.put("code_verifier", pkce.getVerifier());
      }
    }
  };

  return new AuthorizationCodeTokenRequest(transport, jsonFactory,
      new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication(
      pkceClientAuthenticationWrapper).setRequestInitializer(requestInitializer).setScopes(scopes);
}
 
Example #27
Source File: BearerToken.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
private static Map<String, Object> getData(HttpRequest request) {
  return Data.mapOf(UrlEncodedContent.getContent(request).getData());
}
 
Example #28
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new Kickflip User.
 * The User created as a result of this request is cached and managed by this KickflipApiClient
 * throughout the life of the host Android application installation.
 * <p/>
 * The other methods of this client will be performed on behalf of the user created by this request,
 * unless noted otherwise.
 *
 * @param username    The desired username for this Kickflip User. Will be altered if not unique for this Kickflip app.
 * @param password    The password for this Kickflip user.
 * @param email       The email address for this Kickflip user.
 * @param displayName The display name for this Kickflip user.
 * @param extraInfo   Map data to be associated with this Kickflip User.
 * @param cb          This callback will receive a User in {@link io.kickflip.sdk.api.KickflipCallback#onSuccess(io.kickflip.sdk.api.json.Response)}
 *                    or an Exception {@link io.kickflip.sdk.api.KickflipCallback#onError(io.kickflip.sdk.exception.KickflipException)}.
 */
public void createNewUser(String username, String password, String email, String displayName, Map extraInfo, final KickflipCallback cb) {
    GenericData data = new GenericData();
    if (username != null) {
        data.put("username", username);
    }

    final String finalPassword;
    if (password != null) {
        finalPassword = password;
    } else {
        finalPassword = generateRandomPassword();
    }
    data.put("password", finalPassword);

    if (displayName != null) {
        data.put("display_name", displayName);
    }
    if (email != null) {
        data.put("email", email);
    }
    if (extraInfo != null) {
        data.put("extra_info", new Gson().toJson(extraInfo));
    }

    post(NEW_USER, new UrlEncodedContent(data), User.class, new KickflipCallback() {
        @Override
        public void onSuccess(final Response response) {
            if (VERBOSE)
                Log.i(TAG, "createNewUser response: " + response);
            storeNewUserResponse((User) response, finalPassword);
            postResponseToCallback(cb, response);
        }

        @Override
        public void onError(final KickflipException error) {
            Log.w(TAG, "createNewUser Error: " + error);
            postExceptionToCallback(cb, error);
        }
    });
}
 
Example #29
Source File: RestClient.java    From apigee-deploy-maven-plugin with Apache License 2.0 4 votes vote down vote up
public String activateBundleRevision(Bundle bundle) throws IOException {

		BundleActivationConfig deployment2 = new BundleActivationConfig();

		try {

			HttpHeaders headers = new HttpHeaders();
			headers.setAccept("application/json");

			GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/environments/%s/%s/%s/revisions/%d/deployments",
					profile.getHostUrl(),
					profile.getApi_version(),
					profile.getOrg(),
					profile.getEnvironment(),
					bundle.getType().getPathName(),
					bundle.getName(),
					bundle.getRevision()));

			GenericData data = new GenericData();
			data.set("override", Boolean.valueOf(getProfile().isOverride()).toString());

			//Fix for https://github.com/apigee/apigee-deploy-maven-plugin/issues/18
			if (profile.getDelayOverride() != 0) {
				data.set("delay", profile.getDelayOverride());
			}

			HttpRequest deployRestRequest = requestFactory.buildPostRequest(url, new UrlEncodedContent(data));
			deployRestRequest.setReadTimeout(0);
			deployRestRequest.setHeaders(headers);


			HttpResponse response = null;
			response = executeAPI(profile, deployRestRequest);

			if (getProfile().isOverride()) {
				SeamLessDeploymentStatus deployment3 = response.parseAs(SeamLessDeploymentStatus.class);
				Iterator<BundleActivationConfig> iter = deployment3.environment.iterator();
				while (iter.hasNext()) {
					BundleActivationConfig config = iter.next();
					if (config.environment.equalsIgnoreCase(profile.getEnvironment())) {
						if (!config.state.equalsIgnoreCase("deployed")) {
							log.info("Waiting to assert bundle activation.....");
							Thread.sleep(10);
							Long deployedRevision = getDeployedRevision(bundle);
							if (bundle.getRevision() != null && bundle.getRevision().equals(deployedRevision)) {
								log.info("Deployed revision is: " + bundle.getRevision());
								return "deployed";
							} else
								log.error("Deployment failed to activate");
							throw new MojoExecutionException("Deployment failed: Bundle did not activate within expected time. Please check deployment status manually before trying again");
						} else {
							log.info(PrintUtil.formatResponse(response, gson.toJson(deployment3)));
						}
					}
				}

			}

			deployment2 = response.parseAs(BundleActivationConfig.class);
			if (log.isInfoEnabled()) {
				log.info(PrintUtil.formatResponse(response, gson.toJson(deployment2)));
				log.info("Deployed revision is:{}", deployment2.revision);
			}
			applyDelay();

		} catch (Exception e) {
			log.error(e.getMessage());
			throw new IOException(e);
		}

		return deployment2.state;

	}
 
Example #30
Source File: KickflipApiClient.java    From kickflip-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Flag a {@link io.kickflip.sdk.api.json.Stream}. Used when the active Kickflip User does not own the Stream.
 * <p/>
 * To delete a recording the active Kickflip User owns, use
 * {@link io.kickflip.sdk.api.KickflipApiClient#setStreamInfo(io.kickflip.sdk.api.json.Stream, KickflipCallback)}
 *
 * @param stream The Stream to flag.
 * @param cb     A callback to receive the result of the flagging operation.
 */
public void flagStream(Stream stream, final KickflipCallback cb) {
    if (!assertActiveUserAvailable(cb)) return;
    GenericData data = new GenericData();
    data.put("uuid", getActiveUser().getUUID());
    data.put("stream_id", stream.getStreamId());

    post(FLAG_STREAM, new UrlEncodedContent(data), Stream.class, cb);
}