Java 类com.google.api.client.http.json.JsonHttpContent 实例源码

项目:firebase-admin-java    文件:FirebaseAuthIT.java   
private String signInWithCustomToken(String customToken) throws IOException {
  GenericUrl url = new GenericUrl(ID_TOOLKIT_URL + "?key="
      + IntegrationTestUtils.getApiKey());
  Map<String, Object> content = ImmutableMap.<String, Object>of(
      "token", customToken, "returnSecureToken", true);
  HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
      new JsonHttpContent(jsonFactory, content));
  request.setParser(new JsonObjectParser(jsonFactory));
  HttpResponse response = request.execute();
  try {
    GenericJson json = response.parseAs(GenericJson.class);
    return json.get("idToken").toString();
  } finally {
    response.disconnect();
  }
}
项目:msbotframework    文件:ConnectorClient.java   
protected <E> E postRequest(String path, Object body, Class<E> responseType){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl(uri);

        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        E response = (E) request.execute().parseAs(responseType);
        if ( logger.isDebugEnabled() ){
            logger.debug("Response back from botframework api:");
            logger.debug(JSON_FACTORY.toPrettyString(response));
        }
        return response;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:msbotframework    文件:ConnectorClient.java   
protected Future<HttpResponse> postRequestAsync(String path, Object body){
    try {
        URI uri = uri(path);
        GenericUrl url = new GenericUrl();
        if ( logger.isDebugEnabled() ){
            logger.debug("Request POSTed into botframework api " + uri + ":");
            logger.debug(JSON_FACTORY.toPrettyString(body));
        }
        HttpContent content = new JsonHttpContent(JSON_FACTORY,body);
        HttpRequest request = requestFactory.buildPostRequest(url,content);
        if ( this.executor != null ){
            return request.executeAsync(this.executor);
        }
        else{
            return request.executeAsync();
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:copybara    文件:GitHubApiTransportImpl.java   
@SuppressWarnings("unchecked")
@Override
public <T> T post(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials());

  GenericUrl url = new GenericUrl(URI.create(API_URL + "/" + path));
  try {
    HttpRequest httpRequest = requestFactory.buildPostRequest(url,
        new JsonHttpContent(JSON_FACTORY, request));
    HttpResponse response = httpRequest.execute();
    return (T) response.parseAs(responseType);
  } catch (IOException e) {
    throw new RepoException("Error running GitHub API operation " + path, e);
  }
}
项目:jdrivesync    文件:ResumableUpload.java   
private String requestUploadLocation(java.io.File fileToUpload, String mimeType, HttpRequestFactory requestFactory, com.google.api.services.drive.model.File remoteFile) throws IOException {
    GenericUrl initializationUrl = new GenericUrl("https://www.googleapis.com/upload/drive/v2/files");
    initializationUrl.put("uploadType", "resumable");
    HttpRequest httpRequest = createHttpRequest(requestFactory, HttpMethods.POST, initializationUrl, new JsonHttpContent(DriveFactory.getJsonFactory(), remoteFile));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.put("X-Upload-Content-Type", mimeType);
    httpHeaders.put("X-Upload-Content-Length", fileToUpload.length());
    httpRequest.getHeaders().putAll(httpHeaders);
    LOGGER.log(Level.FINE, "Executing initial upload location request.");
    HttpResponse httpResponse = executeHttpRequest(httpRequest);
    if(!httpResponse.isSuccessStatusCode()) {
        throw new IOException("Request for upload location was not successful. Status-Code: " + httpResponse.getStatusCode());
    }
    String location = httpResponse.getHeaders().getLocation();
    LOGGER.log(Level.FINE, "URL for resumable upload: " + location);
    return location;
}
项目:onedrive-java-client    文件:RWOneDriveProvider.java   
public OneDriveItem createFolder(OneDriveItem parent, File target) throws IOException {

        WriteFolderFacet newFolder = new WriteFolderFacet(target.getName());

        HttpRequest request = requestFactory.buildPostRequest(
                OneDriveUrl.children(parent.getId()),
                new JsonHttpContent(JSON_FACTORY, newFolder));

        Item response = request.execute().parseAs(Item.class);
        OneDriveItem item = OneDriveItem.FACTORY.create(response);

        // Set the remote timestamps
        BasicFileAttributes attr = Files.readAttributes(target.toPath(), BasicFileAttributes.class);
        item = updateFile(item, new Date(attr.creationTime().toMillis()), new Date(attr.lastModifiedTime().toMillis()));

        return item;
    }
项目:datacollector    文件:Policy.java   
public boolean create(String name, String rules) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("rules", rules);

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/policy/" + name),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }
}
项目:jdrivesync    文件:ResumableUpload.java   
private String requestUploadLocation(java.io.File fileToUpload, String mimeType, HttpRequestFactory requestFactory, com.google.api.services.drive.model.File remoteFile) throws IOException {
    GenericUrl initializationUrl = new GenericUrl("https://www.googleapis.com/upload/drive/v2/files");
    initializationUrl.put("uploadType", "resumable");
    HttpRequest httpRequest = createHttpRequest(requestFactory, HttpMethods.POST, initializationUrl, new JsonHttpContent(DriveFactory.getJsonFactory(), remoteFile));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.put("X-Upload-Content-Type", mimeType);
    httpHeaders.put("X-Upload-Content-Length", fileToUpload.length());
    httpRequest.getHeaders().putAll(httpHeaders);
    LOGGER.log(Level.FINE, "Executing initial upload location request.");
    HttpResponse httpResponse = executeHttpRequest(httpRequest);
    if(!httpResponse.isSuccessStatusCode()) {
        throw new IOException("Request for upload location was not successful. Status-Code: " + httpResponse.getStatusCode());
    }
    String location = httpResponse.getHeaders().getLocation();
    LOGGER.log(Level.FINE, "URL for resumable upload: " + location);
    return location;
}
项目:GeoNote    文件:DropletServer.java   
public void putDroplets(String userName, List<Droplet> droplets) throws Exception {
    try {
        System.out.println("Perform droplet search ....");
        HttpRequestFactory httpRequestFactory = createRequestFactory(transport);

        HttpContent content = new JsonHttpContent(new JacksonFactory(), droplets);
        HttpRequest request = httpRequestFactory.buildPostRequest(
                new GenericUrl(DROPLET_POST_URL + userName),
                content);

        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

    } catch (HttpResponseException e) {
        System.err.println(e.getStatusMessage());
        throw e;
    }
}
项目:zefiro    文件:NodeService.java   
/**
 * Richiede ad Alfresco la creazione di una <i>thumbnail</i>.
 * <p>
 * Si tenga presente che in caso di creazione asincrona la <i>thumbnail</i> potrebbe non essere
 * subito disponibile anche se il metodo ha restituito informazioni valide.
 * 
 * @param pContentId
 *            L'id del contenuto.
 * @param pThumbDefinition
 *            Il nome della <i>thumbnail</i> di cui si richiede la crezione.
 * @param pAsync
 *            Se la crazione deve essere sincrona ({@code true} o asincrona ({@false}).
 * 
 * @return La <i>thumbnail</i> richiesta o {@code null} se il tipo di <i>thumbnail</i> di cui si
 *         è richiesta la creazione non è valido per il contenuto specificato.
 * 
 * @throws IOException
 */
public Thumbnail createThumbnail(String pContentId, String pThumbDefinition, boolean pAsync) throws IOException {
    /*
     * POST <base>/content{property}/thumbnails?as={async?}
     * 
     * {
     *     "thumbnailName": <name>
     * }
     */
    GenericUrl lUrl = getContentUrl(pContentId);
    lUrl.appendRawPath(URL_RELATIVE_THUMBNAILS);
    lUrl.set("as", pAsync);

    // Recupero delle definizioni valide
    // Purtroppo Alfresco restituisce successo anche se viene richiesta la generazione di una
    // thumbnail non possibile. Controllando preventivamente si può restituire null.
    List<String> lThumbDefinitions = getThumbnailDefinitions(pContentId);
    if (!lThumbDefinitions.contains(pThumbDefinition)) {
        return null;
    }

    JsonHttpContent lContent = new JsonHttpContent(JSON_FACTORY, new Thumbnail(pThumbDefinition));

    HttpHeaders lRequestHeaders = new HttpHeaders().setContentType("application/json");
    HttpRequest lRequest =
            mHttpRequestFactory.buildPostRequest(lUrl, lContent).setHeaders(lRequestHeaders);

    HttpResponse lResponse = lRequest.execute();
    Thumbnail lThumbnail = lResponse.parseAs(Thumbnail.class);

    return lThumbnail;
}
项目:nlu-api-client-java    文件:AmbiverseApiClient.java   
protected Post(AnalyzeInput input) {        
    super(AmbiverseApiClient.this,
          "POST",
          PATH,
          new JsonHttpContent(AmbiverseApiClient.this.getJsonFactory(), input),
          com.ambiverse.api.model.AnalyzeOutput.class);
}
项目:nlu-api-client-java    文件:AmbiverseApiClient.java   
protected Post(String... yagoIDs) {             
    super(AmbiverseApiClient.this,
          "POST",
          PATH,
          new JsonHttpContent(AmbiverseApiClient.this.getJsonFactory(), yagoIDs),
          com.ambiverse.api.model.Entities.class);
}
项目:nlu-api-client-java    文件:AmbiverseApiClient.java   
protected Post(String... yagoIDs) {             
                    super(AmbiverseApiClient.this,
                            "POST",
                            PATH, 
                            new JsonHttpContent(AmbiverseApiClient.this.getJsonFactory(), yagoIDs), 
                            com.ambiverse.api.model.Categories.class);
//                  this.yagoIDs = yagoIDs;
                }
项目:sync    文件:Networker.java   
public static boolean sendGCMSync(String userId, String senderId) {
    if(Constants.GCM_API_KEY == null) {
        log.info("GCM not set up, see readme for how to configure");
        return false;
    }
    try {
        GCMMessage message = new GCMMessage(userId);
        log.info("message:" + message);
        log.info("gson:" + gson.toJson(message));
        GenericData body = new GenericData();
        GenericData data = new GenericData();
        body.put("to", "/topics/" + userId);
        if(senderId != null) {
            data.put("senderId",senderId);
            body.put("data", data);
        }

        //why does this only take a generic map?
        HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(GCM_HOST),
                new JsonHttpContent(gsonFactory, body))
                .setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()))
                .setHeaders(new HttpHeaders().setAuthorization("key=" + Constants.GCM_API_KEY));
        request.getContent().writeTo(System.out);
        HttpResponse response = request.execute();
        log.info("response" + response);
        return true;
    } catch(IOException e) {
        log.info("could not send http message:");
        e.printStackTrace();
        return false;
    }
}
项目:copybara    文件:GerritApiTransportImpl.java   
@Override
public <T> T post(String path, Object request, Type responseType)
    throws RepoException, ValidationException {
  HttpRequestFactory requestFactory = getHttpRequestFactory(getCredentials(uri.toString()));
  GenericUrl url = getUrl(path);
  try {
    return execute(responseType, requestFactory.buildPostRequest(
        url, new JsonHttpContent(JSON_FACTORY, request)));
  } catch (IOException e) {
    throw new RepoException("Error running Gerrit API operation " + url, e);
  }
}
项目:jdrivesync    文件:GoogleDriveAdapter.java   
private HttpResponse executeSessionInitiationRequest(Drive drive, File remoteFile) throws IOException {
    GenericUrl url = new GenericUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
    JsonHttpContent metadataContent = new JsonHttpContent(drive.getJsonFactory(), remoteFile);
    HttpRequest httpRequest = drive.getRequestFactory().buildPostRequest(url, metadataContent);
    LOGGER.log(Level.FINE, "Executing session initiation request to URL " + url);
    return httpRequest.execute();
}
项目:onedrive-java-client    文件:RWOneDriveProvider.java   
public OneDriveItem uploadFile(OneDriveItem parent, File file) throws IOException {

        if (!parent.isDirectory()) {
            throw new IllegalArgumentException("Parent is not a folder");
        }

        // Generate the update item
        BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        FileSystemInfoFacet fsi = new FileSystemInfoFacet();
        fsi.setLastModifiedDateTime(JsonDateSerializer.INSTANCE.serialize(new Date(attr.lastModifiedTime().toMillis())));
        fsi.setCreatedDateTime(JsonDateSerializer.INSTANCE.serialize(new Date(attr.creationTime().toMillis())));
        WriteItemFacet itemToWrite = new WriteItemFacet(file.getName(), fsi, true, false);

        MultipartContent content = new MultipartContent()
                .addPart(new MultipartContent.Part(
                        new HttpHeaders()
                                .set("Content-ID", "<metadata>")
                                .setAcceptEncoding(null),
                        new JsonHttpContent(JSON_FACTORY, itemToWrite)))
                .addPart(new MultipartContent.Part(
                        new HttpHeaders()
                                .set("Content-ID", "<content>")
                                .setAcceptEncoding(null),
                        new FileContent(null, file)));

        HttpRequest request = requestFactory.buildPostRequest(
                OneDriveUrl.postMultiPart(parent.getId()), content);

        request.setLoggingEnabled(true);

        return OneDriveItem.FACTORY.create(request.execute().parseAs(Item.class));
    }
项目:onedrive-java-client    文件:RWOneDriveProvider.java   
@Override
public OneDriveUploadSession startUploadSession(OneDriveItem parent, File file) throws IOException {

    HttpRequest request = requestFactory.buildPostRequest(
            OneDriveUrl.createUploadSession(parent.getId(), file.getName()),
            new JsonHttpContent(JSON_FACTORY, new UploadSessionFacet(file.getName())));

    UploadSession session = request.execute().parseAs(UploadSession.class);

    return new OneDriveUploadSession(parent, file, session.getUploadUrl(), session.getNextExpectedRanges());
}
项目:onedrive-java-client    文件:RWOneDriveProvider.java   
public OneDriveItem updateFile(OneDriveItem item, Date createdDate, Date modifiedDate) throws IOException {

        FileSystemInfoFacet fileSystem = new FileSystemInfoFacet();
        fileSystem.setCreatedDateTime(JsonDateSerializer.INSTANCE.serialize(createdDate));
        fileSystem.setLastModifiedDateTime(JsonDateSerializer.INSTANCE.serialize(modifiedDate));

        WriteItemFacet updateItem = new WriteItemFacet(item.getName(), fileSystem, false, item.isDirectory());

        HttpRequest request = requestFactory.buildPatchRequest(
                OneDriveUrl.item(item.getId()),
                new JsonHttpContent(JSON_FACTORY, updateItem));

        Item response = request.execute().parseAs(Item.class);
        return OneDriveItem.FACTORY.create(response);
    }
项目:datacollector    文件:Logical.java   
public Secret write(String path, Map<String, Object> params) throws VaultException {
  HttpContent content = new JsonHttpContent(
      getJsonFactory(),
      params
  );
  return getSecret("/v1/" + path, "POST", content);
}
项目:datacollector    文件:Auth.java   
public boolean enable(String path, String type, String description) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/auth/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
项目:datacollector    文件:Mounts.java   
public boolean mount(String path, String type, String description, Map<String, String> config) throws VaultException {
  Map<String, Object> data = new HashMap<>();
  data.put("type", type);

  if (description != null) {
    data.put("description", description);
  }

  if (config != null) {
    data.put("config", config);
  }

  HttpContent content = new JsonHttpContent(getJsonFactory(), data);

  try {
    HttpRequest request = getRequestFactory().buildRequest(
        "POST",
        new GenericUrl(getConf().getAddress() + "/v1/sys/mounts/" + path),
        content
    );
    HttpResponse response = request.execute();
    if (!response.isSuccessStatusCode()) {
      LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage());
    }

    return response.isSuccessStatusCode();
  } catch (IOException e) {
    LOG.error(e.toString(), e);
    throw new VaultException("Failed to authenticate: " + e.toString(), e);
  }
}
项目:datacollector    文件:Authenticate.java   
public Secret appRole(String roleId, String secretId) throws VaultException {
  HttpContent content = new JsonHttpContent(
      getJsonFactory(),
      ImmutableMap.of("role_id", roleId, "secret_id", secretId)
  );
  return getSecret("/v1/auth/approle/login", "POST", content);
}
项目:jdrivesync    文件:GoogleDriveAdapter.java   
private HttpResponse executeSessionInitiationRequest(Drive drive, File remoteFile) throws IOException {
    GenericUrl url = new GenericUrl("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");
    JsonHttpContent metadataContent = new JsonHttpContent(drive.getJsonFactory(), remoteFile);
    HttpRequest httpRequest = drive.getRequestFactory().buildPostRequest(url, metadataContent);
    LOGGER.log(Level.FINE, "Executing session initiation request to URL " + url);
    return httpRequest.execute();
}
项目:rqlite-java    文件:RequestFactory.java   
private HttpRequest buildPostRequest(GenericUrl url, String[] stmts) throws IOException {
    HttpRequest request = this.requestFactory.buildPostRequest(url, new JsonHttpContent(JSON_FACTORY, stmts));
    return request.setParser(new JsonObjectParser(JSON_FACTORY));
}
项目:java-docs-samples    文件:LabelsSample.java   
/**
 * Add or modify a label on a dataset.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  credential.refreshToken();
  String accessToken = credential.getAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
项目:java-docs-samples    文件:LabelsSample.java   
/**
 * Add or modify a label on a table.
 *
 * <p>See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelTable(
    String projectId,
    String datasetId,
    String tableId,
    String labelKey,
    String labelValue)
    throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredential credential = GoogleCredential.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  credential.refreshToken();
  String accessToken = credential.getAccessToken();

  // Set the content of the request.
  Table table = new Table();
  table.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, table);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, tableId, accessToken));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Table responseTable = response.parseAs(Table.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseTable.getLabels().get(labelKey));
}
项目:datacollector    文件:Authenticate.java   
public Secret renewSelf() throws VaultException {
  HttpContent content = new JsonHttpContent(getJsonFactory(), Collections.emptyMap());
  return getSecret("/v1/auth/token/renew-self", "POST", content);
}
项目:RedMetrics    文件:HttpBackend.java   
private HttpContent asJson(E entity) {
    return new JsonHttpContent(new GsonFactory(), entity);
}
项目:java-mapi-client    文件:MCashClient.java   
private JsonHttpContent buildJsonContent(Object object) {
    return new JsonHttpContent(JSON_FACTORY, object);
}
项目:audiobox-jlib    文件:User.java   
/**
 * Saves user preferences
 *
 * @param audioBoxClient the client
 *
 * @return true if operation succeed throws an exception if something goes wrong
 *
 * @throws fm.audiobox.core.exceptions.AudioBoxException if any of the remote error exception is detected.
 * @throws java.io.IOException                           if any connection problem occurs.
 * @see fm.audiobox.core.exceptions.AudioBoxException
 */
public boolean savePreferences(AudioBoxClient audioBoxClient) throws IOException {

  // 'api/v1/preference.json' endpoint accepts a user object that inherit
  // Preferences.class fields like this:
  //
  // {"user"=>{"prebuffer"=>"1", "accept_emails"=>"0", "js_demuxer"=>"1"}}
  //
  // This is why we need a custom crafted JSON and that's why we create a map.

  Map<String, Object> prefs = new HashMap<>();

  // Since preferences are an open set of fields that may
  // vary in space and time (:D) and we don't want to
  // update a map each time a preference is added or removed,
  // we proceed with reflection. This may reduce maintenance
  // hassles.
  Field[] fs = getPreferences().getClass().getDeclaredFields();

  for (Field f : fs ){

    // @Key annotated fields are the fields that we want to keep in sync
    if (f.isAnnotationPresent( Key.class ) ) {
      try {

        Object value = f.get( getPreferences() );

        // Drop null values
        if (value == null) {
          continue;
        }

        // Boolean values are transformed into 1 and 0 strings
        // because of some technical issue with the backend.
        if (f.getType() == boolean.class) {
          value = (Boolean) value ? "1" : "0";
        }

        prefs.put( f.getName(), value.toString() );

      } catch ( IllegalAccessException e ) {

        // Erroneous or problematic fields are just discarded,
        // but we don't want to abort the request, thus we catch
        // the exception and keep it going.
        log.error( "Preference field is not readable due to some unsupported state: " + e.getMessage() );
      }
    }
  }

  Map<String, Object> u = new HashMap<>();
  u.put("user", prefs);

  audioBoxClient.doPUT( Preferences.PATH, new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), u ) );
  return true;
}
项目:OpenbravoPOS    文件:ApiClient.java   
private JsonHttpContent buildJsonContent(Object object) {
    return new JsonHttpContent(JSON_FACTORY, object);
}
项目:kazoo-client    文件:KazooConnection.java   
/**
 * Send a POST request. Updates a resource by completely replacing it with the provided data.
 *
 * @param <S>
 * @param <U>
 * @param <T>
 * @param requestUrl
 * @param payload
 * @param payloadType
 * @return updated object.
 * @throws IOException
 */
public <S, U, T extends ResponseEnvelope<U>> U post(final GenericUrl requestUrl, final S payload, final Class<T> payloadType) throws IOException {
   RequestEnvelope<S> request = new RequestEnvelope<S>();
   request.setData(payload);
   HttpRequest httpRequest = requestFactory.buildPostRequest(requestUrl, new JsonHttpContent(KazooConnection.JSON_FACTORY, request));
   return execute(httpRequest, payloadType);
}
项目:kazoo-client    文件:KazooConnection.java   
/**
 * Send a PUT request. Creates a new resource with the provided data.
 *
 * @param <S>
 * @param <U>
 * @param <T>
 * @param requestUrl
 * @param payload
 * @param payloadType
 * @return new object.
 * @throws IOException
 */
public <S, U, T extends ResponseEnvelope<U>> U put(final GenericUrl requestUrl, final S payload, final Class<T> payloadType) throws IOException {
   RequestEnvelope<S> request = new RequestEnvelope<S>();
   request.setData(payload);
   HttpRequest httpRequest = requestFactory.buildPutRequest(requestUrl, new JsonHttpContent(KazooConnection.JSON_FACTORY, request));
   U response = execute(httpRequest, payloadType);
   return response;
}
项目:audiobox-jlib    文件:Playlist.java   
/**
 * Begin content sync with the remote platform. Supported only by syncable playlists.
 * <p>
 * Calling this method will initiate a job that will synchronize data with the remote storage,
 * such as Dropbox, SkyDrive and others.
 * <p>
 * Playlists supporting official storage such as AudioBox Cloud or AudioBox Desktop does not require syncing.
 *
 * @param audioBoxClient the client to use for the request
 *
 * @return true if operation succeeds.
 *
 * @throws SyncException                                 if any problem occurs.
 * @throws fm.audiobox.core.exceptions.AudioBoxException if any of the remote error exception is detected.
 * @throws java.io.IOException                           if any connection problem occurs.
 * @see fm.audiobox.core.exceptions.AudioBoxException
 */
public boolean sync(AudioBoxClient audioBoxClient) throws IOException {
  ensurePlaylistForRequest();
  if ( !this.isSyncable() ) // Well...
    throw new SyncException( HttpStatus.SC_UNPROCESSABLE_ENTITY );
  HttpResponse rsp;
  try {
    rsp = audioBoxClient.doPUT( getSyncPath(), new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), this ) );
  } catch ( AudioBoxException e ) {
    throw new SyncException( e.getResponse() );
  }

  return rsp != null && rsp.isSuccessStatusCode();
}
项目:audiobox-jlib    文件:Playlist.java   
/**
 * Add Media Files to a CustomPlaylist.
 * <p>
 * Shallow action that requires a list of media files tokens to be added to this custom playlist.
 * Media files can be added manually only to custom playlists.
 *
 * @param audioBoxClient the {@link fm.audiobox.core.AudioBoxClient} to use for the request
 * @param tokens         the list of the tokens string to add to this playlist
 *
 * @return the playlist instance in order to chain other operations on it if needed.
 *
 * @throws java.lang.IllegalStateException                       if the playlist is not persisted yet.
 * @throws fm.audiobox.core.exceptions.ResourceNotFoundException if the playlist not found or not of type CustomPlaylist.
 * @throws fm.audiobox.core.exceptions.AudioBoxException         if any of the remote error exception is detected.
 * @throws java.io.IOException                                   if any connection problem occurs.
 * @see fm.audiobox.core.exceptions.AudioBoxException
 */
public Playlist addMediaFiles(AudioBoxClient audioBoxClient, List<String> tokens) throws IOException {

  ensurePlaylistForRequest();

  GenericData d = new GenericData();
  for ( String token : tokens ) {
    d.put( MediaFiles.PARAM_TOKENS, token );
  }
  JsonHttpContent data = new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), d );
  audioBoxClient.doPOST( ModelUtil.interpolate( ADD_MEDIA_FILES_PATH, getToken() ), data, null, null );
  return this;
}
项目:audiobox-jlib    文件:MediaFile.java   
/**
 * Handle a single media file update.
 *
 * @param audioBoxClient the client to use for the request
 * @return the media file in order to chain other calls.
 * @throws fm.audiobox.core.exceptions.AudioBoxException if any of the remote error exception is detected.
 */
public MediaFile update(AudioBoxClient audioBoxClient) throws IOException {
  audioBoxClient.doPUT( ModelUtil.interpolate( getPath(), getToken() ), new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), this ) );
  return this;
}
项目:audiobox-jlib    文件:Playlist.java   
/**
 * Creates a new CustomPlaylist or SmartPlaylist depending on the input parameters.
 * <p>
 * The user can create a CustomPlaylist by setting the playlist name.
 * <p>
 * The user can create a SmartPlaylist by setting the playlist name AND playlist search_params.
 * <p>
 * NOTE: Currently the search_params hash construction is complex enough and therefore it's
 * restricted to the Cloud Web Player, we'll open up the possibility for developers to create them as well.
 *
 * @param audioBoxClient the client
 *
 * @return a new instance of the saved Playlist if success or null if any error occurs
 *
 * @throws fm.audiobox.core.exceptions.AudioBoxException if any of the remote error exception is detected.
 * @throws java.io.IOException                           if any connection problem occurs.
 * @see fm.audiobox.core.exceptions.AudioBoxException
 */
public Playlist create(AudioBoxClient audioBoxClient) throws IOException {
  validateForRequest( false );
  HttpResponse rsp = audioBoxClient.doPOST( Playlists.getPath(), new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), this ) );
  return rsp != null && rsp.isSuccessStatusCode() ? rsp.parseAs( PlaylistWrapper.class ).getPlaylist() : null;
}
项目:audiobox-jlib    文件:Playlist.java   
/**
 * Handle the update of a custom or smart playlist.
 * <p>
 * As a rule of thumb you can have one uniquely named playlist for each type.
 * <p>
 * SmartPlaylist's <code>search_params</code> can be set only on creation and thus cannot be changed, in this action.
 * <p>
 * SmartPlaylist cannot be tweaked in their <code>search_params</code> due to the complexity of their construct.
 * Since SmartPlaylist are compiled on demand, just destroy the old and create a new one.
 *
 * @param audioBoxClient the client
 *
 * @return the playlist
 *
 * @throws java.lang.IllegalStateException                       if the playlist is not persisted yet.
 * @throws fm.audiobox.core.exceptions.ForbiddenException        if no valid subscription found
 * @throws fm.audiobox.core.exceptions.ResourceNotFoundException if playlist is not found or immutable
 * @throws fm.audiobox.core.exceptions.ValidationException       if playlist data is not valid (ex: name already taken)
 * @throws fm.audiobox.core.exceptions.AudioBoxException         if any of the remote error exception is detected.
 * @throws java.io.IOException                                   if any connection problem occurs.
 * @see fm.audiobox.core.exceptions.AudioBoxException
 */
public Playlist update(AudioBoxClient audioBoxClient) throws IOException {
  ensurePlaylistForRequest();
  audioBoxClient.doPUT( ModelUtil.interpolate( getPath(), getToken() ), new JsonHttpContent( audioBoxClient.getConf().getJsonFactory(), this ) );
  return this;
}