Java Code Examples for com.google.gson.reflect.TypeToken

The following examples show how to use com.google.gson.reflect.TypeToken. These examples are extracted from open source projects. 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 Project: letv   Source File: ReflectiveTypeAdapterFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    Map<String, BoundField> result = new LinkedHashMap();
    if (!raw.isInterface()) {
        Type declaredType = type.getType();
        while (raw != Object.class) {
            for (Field field : raw.getDeclaredFields()) {
                boolean serialize = excludeField(field, true);
                boolean deserialize = excludeField(field, false);
                if (serialize || deserialize) {
                    field.setAccessible(true);
                    BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(C$Gson$Types.resolve(type.getType(), raw, field.getGenericType())), serialize, deserialize);
                    BoundField previous = (BoundField) result.put(boundField.name, boundField);
                    if (previous != null) {
                        throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name);
                    }
                }
            }
            type = TypeToken.get(C$Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
            raw = type.getRawType();
        }
    }
    return result;
}
 
Example 2
Source Project: twitter4j-ads   Source File: TwitterAdsCardsApiImpl.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
public BaseAdsListResponseIterable<TwitterWebsiteCard> getAllWebsiteCards(String accountId, List<String> cardIds, boolean withDeleted,
                                                                          Optional<Integer> count) throws TwitterException {
    TwitterAdUtil.ensureNotNull(accountId, ACCOUNT_ID);
    List<HttpParameter> params = Lists.newArrayList();
    params.add(new HttpParameter(PARAM_WITH_DELETED, withDeleted));
    if (TwitterAdUtil.isNotEmpty(cardIds)) {
        params.add(new HttpParameter(PARAM_CARD_IDS, TwitterAdUtil.getCsv(cardIds)));
    }
    if (count != null && count.isPresent()) {
        params.add(new HttpParameter(PARAM_COUNT, count.get()));
    }

    String url = twitterAdsClient.getBaseAdsAPIUrl() + PREFIX_ACCOUNTS_URI + accountId + PATH_WEBSITE_CARDS;
    Type type = new TypeToken<BaseAdsListResponse<TwitterWebsiteCard>>() {
    }.getType();
    return twitterAdsClient.executeHttpListRequest(url, params, type);
}
 
Example 3
Source Project: BigApp_Discuz_Android   Source File: CommentFragment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mListView = (RefreshListView) inflater.inflate(R.layout.fragment_list, container, false);
    ViewUtils.inject(this, mListView);
    mListView.setMode(PullToRefreshBase.Mode.DISABLED);

    BundleData bundleData = FragmentUtils.getData(this);

    ZogUtils.printObj(CommentFragment.class, bundleData);

    Type type = new TypeToken<ArrayList<CommentField>>() {
    }.getType();
    ArrayList<CommentField> list = bundleData.getArrayList(Key.CLAN_DATA,type);

    ZogUtils.printError(CommentFragment.class, "list.size():" + list.size());

    mAdapter = new CommentAdapter(getActivity(), list);
    mListView.setAdapter(mAdapter);
    return mListView;
}
 
Example 4
@Test
public void testDeserialize() {
  Page<OfferResponse> transactionsPage = GsonSingleton.getInstance().fromJson(json, new TypeToken<Page<OfferResponse>>() {}.getType());

  assertEquals(transactionsPage.getRecords().get(0).getId(), new Long(241));
  assertEquals(transactionsPage.getRecords().get(0).getSeller(), "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD");
  assertEquals(transactionsPage.getRecords().get(0).getPagingToken(), "241");
  assertEquals(transactionsPage.getRecords().get(0).getSelling(), Asset.createNonNativeAsset("INR", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD"));
  assertEquals(transactionsPage.getRecords().get(0).getBuying(), Asset.createNonNativeAsset("USD", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD"));
  assertEquals(transactionsPage.getRecords().get(0).getAmount(), "10.0000000");
  assertEquals(transactionsPage.getRecords().get(0).getPrice(), "11.0000000");
  assertEquals(transactionsPage.getRecords().get(0).getLastModifiedLedger(), new Integer(22200794));
  assertEquals(transactionsPage.getRecords().get(0).getLastModifiedTime(), "2019-01-28T12:30:38Z");

  assertEquals(transactionsPage.getLinks().getNext().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor=241");
  assertEquals(transactionsPage.getLinks().getPrev().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=desc&limit=10&cursor=241");
  assertEquals(transactionsPage.getLinks().getSelf().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor=");
}
 
Example 5
Source Project: gson   Source File: GsonBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Configures Gson for custom serialization or deserialization. This method combines the
 * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
 * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
 * all the required interfaces for custom serialization with Gson. If a type adapter was
 * previously registered for the specified {@code type}, it is overwritten.
 *
 * <p>This registers the type specified and no other types: you must manually register related
 * types! For example, applications registering {@code boolean.class} should also register {@code
 * Boolean.class}.
 *
 * @param type the type definition for the type adapter being registered
 * @param typeAdapter This object must implement at least one of the {@link TypeAdapter},
 * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
 * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
  $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
      || typeAdapter instanceof JsonDeserializer<?>
      || typeAdapter instanceof InstanceCreator<?>
      || typeAdapter instanceof TypeAdapter<?>);
  if (typeAdapter instanceof InstanceCreator<?>) {
    instanceCreators.put(type, (InstanceCreator) typeAdapter);
  }
  if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
    TypeToken<?> typeToken = TypeToken.get(type);
    factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
  }
  if (typeAdapter instanceof TypeAdapter<?>) {
    factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
  }
  return this;
}
 
Example 6
Source Project: lsp4j   Source File: MessageJsonHandlerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEnumParamNull() {
	Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
	supportedMethods.put("foo", JsonRpcMethod.request("foo",
			new TypeToken<Void>() {}.getType(),
			new TypeToken<List<MyEnum>>() {}.getType()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");
	RequestMessage message = (RequestMessage) handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"params\": [1, 2, null],\n"
			+ "\"method\":\"foo\"\n"
			+ "}");
	Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof List);

	List<?> parameters = (List<?>) message.getParams();
	Assert.assertEquals(Arrays.asList(MyEnum.A, MyEnum.B, null),
			parameters);
}
 
Example 7
Source Project: Saiy-PS   Source File: ResolveNuance.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void unpack(@NonNull final JSONObject payload) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "unpacking");
    }

    final GsonBuilder builder = new GsonBuilder();
    builder.disableHtmlEscaping();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    final Gson gson = builder.create();
    nluNuance = gson.fromJson(payload.toString(), new TypeToken<NLUNuance>() {
    }.getType());

    new NLUCoerce(getNLUNuance(), getContext(), getSupportedLanguage(), getVRLocale(), getTTSLocale(),
            getConfidenceArray(), getResultsArray()).coerce();
}
 
Example 8
Source Project: AndroidDemo   Source File: RequestHandler.java    License: MIT License 6 votes vote down vote up
private String updateTableDataAndGetResponse(String route) {
    UpdateRowResponse response;
    try {
        Uri uri = Uri.parse(URLDecoder.decode(route, "UTF-8"));
        String tableName = uri.getQueryParameter("tableName");
        String updatedData = uri.getQueryParameter("updatedData");
        List<RowDataRequest> rowDataRequests = mGson.fromJson(updatedData, new TypeToken<List<RowDataRequest>>() {
        }.getType());
        if (Constants.APP_SHARED_PREFERENCES.equals(mSelectedDatabase)) {
            response = PrefHelper.updateRow(mContext, tableName, rowDataRequests);
        } else {
            response = DatabaseHelper.updateRow(mDatabase, tableName, rowDataRequests);
        }
        return mGson.toJson(response);
    } catch (Exception e) {
        e.printStackTrace();
        response = new UpdateRowResponse();
        response.isSuccessful = false;
        return mGson.toJson(response);
    }
}
 
Example 9
Source Project: gson   Source File: InstanceCreatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testInstanceCreatorForParametrizedType() throws Exception {
  @SuppressWarnings("serial")
  class SubTreeSet<T> extends TreeSet<T> {}
  InstanceCreator<SortedSet> sortedSetCreator = new InstanceCreator<SortedSet>() {
    @Override public SortedSet createInstance(Type type) {
      return new SubTreeSet();
    }
  };
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(SortedSet.class, sortedSetCreator)
      .create();

  Type sortedSetType = new TypeToken<SortedSet<String>>() {}.getType();
  SortedSet<String> set = gson.fromJson("[\"a\"]", sortedSetType);
  assertEquals(set.first(), "a");
  assertEquals(SubTreeSet.class, set.getClass());

  set = gson.fromJson("[\"b\"]", SortedSet.class);
  assertEquals(set.first(), "b");
  assertEquals(SubTreeSet.class, set.getClass());
}
 
Example 10
Source Project: gson   Source File: MapTypeAdapterFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();

  Class<? super T> rawType = typeToken.getRawType();
  if (!Map.class.isAssignableFrom(rawType)) {
    return null;
  }

  Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type);
  Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc);
  TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
  TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
  ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);

  @SuppressWarnings({"unchecked", "rawtypes"})
  // we don't define a type parameter for the key or value types
  TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter,
      keyAndValueTypes[1], valueAdapter, constructor);
  return result;
}
 
Example 11
Source Project: zeppelin   Source File: OldZeppelinHubRepo.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<OldNoteInfo> list(AuthenticationInfo subject) throws IOException {
  if (!isSubjectValid(subject)) {
    return Collections.emptyList();
  }
  String token = getUserToken(subject.getUser());
  String response = restApiClient.get(token, StringUtils.EMPTY);
  List<OldNoteInfo> notes = GSON.fromJson(response, new TypeToken<List<OldNoteInfo>>() {}.getType());
  if (notes == null) {
    return Collections.emptyList();
  }
  LOG.info("ZeppelinHub REST API listing notes ");
  return notes;
}
 
Example 12
Source Project: che   Source File: UserServiceTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToGetSettings() throws Exception {
  final Response response =
      given()
          .auth()
          .basic(ADMIN_USER_NAME, ADMIN_USER_PASSWORD)
          .when()
          .get(SECURE_PATH + "/user/settings");

  assertEquals(response.getStatusCode(), 200);
  final Map<String, String> settings =
      new Gson().fromJson(response.print(), new TypeToken<Map<String, String>>() {}.getType());
  assertEquals(settings, ImmutableMap.of("che.auth.user_self_creation", "true"));
}
 
Example 13
Source Project: tencentcloud-sdk-java   Source File: RedisClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *本接口(DisassociateSecurityGroups)用于安全组批量解绑实例。
 * @param req DisassociateSecurityGroupsRequest
 * @return DisassociateSecurityGroupsResponse
 * @throws TencentCloudSDKException
 */
public DisassociateSecurityGroupsResponse DisassociateSecurityGroups(DisassociateSecurityGroupsRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DisassociateSecurityGroupsResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DisassociateSecurityGroupsResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DisassociateSecurityGroups"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 14
Source Project: gson   Source File: ReflectiveTypeAdapterFactory.java    License: Apache License 2.0 5 votes vote down vote up
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
  Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();
  if (raw.isInterface()) {
    return result;
  }

  Type declaredType = type.getType();
  while (raw != Object.class) {
    Field[] fields = raw.getDeclaredFields();
    for (Field field : fields) {
      boolean serialize = excludeField(field, true);
      boolean deserialize = excludeField(field, false);
      if (!serialize && !deserialize) {
        continue;
      }
      accessor.makeAccessible(field);
      Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
      List<String> fieldNames = getFieldNames(field);
      BoundField previous = null;
      for (int i = 0, size = fieldNames.size(); i < size; ++i) {
        String name = fieldNames.get(i);
        if (i != 0) serialize = false; // only serialize the default name
        BoundField boundField = createBoundField(context, field, name,
            TypeToken.get(fieldType), serialize, deserialize);
        BoundField replaced = result.put(name, boundField);
        if (previous == null) previous = replaced;
      }
      if (previous != null) {
        throw new IllegalArgumentException(declaredType
            + " declares multiple JSON fields named " + previous.name);
      }
    }
    type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
    raw = type.getRawType();
  }
  return result;
}
 
Example 15
Source Project: tencentcloud-sdk-java   Source File: KmsClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *随机数生成接口。
 * @param req GenerateRandomRequest
 * @return GenerateRandomResponse
 * @throws TencentCloudSDKException
 */
public GenerateRandomResponse GenerateRandom(GenerateRandomRequest req) throws TencentCloudSDKException{
    JsonResponseModel<GenerateRandomResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<GenerateRandomResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "GenerateRandom"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 16
Source Project: consul-api   Source File: HealthConsulClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response<List<HealthService>> getHealthServices(String serviceName, HealthServicesRequest healthServicesRequest) {
	HttpResponse httpResponse = rawClient.makeGetRequest("/v1/health/service/" + serviceName, healthServicesRequest.asUrlParameters());

	if (httpResponse.getStatusCode() == 200) {
		List<com.ecwid.consul.v1.health.model.HealthService> value = GsonFactory.getGson().fromJson(httpResponse.getContent(),
				new TypeToken<List<com.ecwid.consul.v1.health.model.HealthService>>() {
				}.getType());
		return new Response<List<com.ecwid.consul.v1.health.model.HealthService>>(value, httpResponse);
	} else {
		throw new OperationException(httpResponse);
	}
}
 
Example 17
Source Project: tencentcloud-sdk-java   Source File: SolarClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *项目库存详情
 * @param req DescribeProjectStockRequest
 * @return DescribeProjectStockResponse
 * @throws TencentCloudSDKException
 */
public DescribeProjectStockResponse DescribeProjectStock(DescribeProjectStockRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DescribeProjectStockResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DescribeProjectStockResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DescribeProjectStock"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 18
Source Project: tencentcloud-sdk-java   Source File: LiveClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *获取单个回调模板。
 * @param req DescribeLiveCallbackTemplateRequest
 * @return DescribeLiveCallbackTemplateResponse
 * @throws TencentCloudSDKException
 */
public DescribeLiveCallbackTemplateResponse DescribeLiveCallbackTemplate(DescribeLiveCallbackTemplateRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DescribeLiveCallbackTemplateResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DescribeLiveCallbackTemplateResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DescribeLiveCallbackTemplate"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 19
Source Project: submarine   Source File: SysDictRestApiTest.java    License: Apache License 2.0 5 votes vote down vote up
public static ListResult<SysDict> queryTestDictList() {
  Response response = sysDictRestApi.list("-SysDictRestApiTest-", "", "", "", "", 1, 10);
  String entity = (String) response.getEntity();
  Type type = new TypeToken<JsonResponse<ListResult<SysDict>>>() {}.getType();
  JsonResponse<ListResult<SysDict>> jsonResponse = gson.fromJson(entity, type);

  ListResult<SysDict> listResult = jsonResponse.getResult();
  return listResult;
}
 
Example 20
Source Project: EFRConnect-android   Source File: SharedPrefUtils.java    License: Apache License 2.0 5 votes vote down vote up
public HashMap<String, FilterDeviceParams> getMapFilter() {
    if (getString(MAP_KEY) == null) {
        return new HashMap<>();
    } else {
        Type type = new TypeToken<HashMap<String, FilterDeviceParams>>() {
        }.getType();
        return gson.fromJson(getString(MAP_KEY), type);
    }
}
 
Example 21
Source Project: alpha-wallet-android   Source File: DappBrowserUtils.java    License: MIT License 5 votes vote down vote up
public static List<DApp> getDappsList(Context context) {
    ArrayList<DApp> dapps;
    dapps = new Gson().fromJson(Utils.loadJSONFromAsset(context, DAPPS_LIST_FILENAME),
            new TypeToken<List<DApp>>() {
            }.getType());
    return dapps;
}
 
Example 22
Source Project: tencentcloud-sdk-java   Source File: AsClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *本接口(CreateNotificationConfiguration)用于创建通知。
 * @param req CreateNotificationConfigurationRequest
 * @return CreateNotificationConfigurationResponse
 * @throws TencentCloudSDKException
 */
public CreateNotificationConfigurationResponse CreateNotificationConfiguration(CreateNotificationConfigurationRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateNotificationConfigurationResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateNotificationConfigurationResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateNotificationConfiguration"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 23
Source Project: tencentcloud-sdk-java   Source File: DayuClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *添加L4转发规则
 * @param req CreateNewL4RulesRequest
 * @return CreateNewL4RulesResponse
 * @throws TencentCloudSDKException
 */
public CreateNewL4RulesResponse CreateNewL4Rules(CreateNewL4RulesRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateNewL4RulesResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateNewL4RulesResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateNewL4Rules"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 24
Source Project: huaweicloud-cs-sdk   Source File: JobApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 删除作业 (asynchronously)
 * 删除任何状态的作业
 * @param projectId project id, 用于不同project取token. (required)
 * @param jobId 作业ID (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call deleteJobAsync(String projectId, Long jobId, final ApiCallback<GlobalResponse> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = deleteJobValidateBeforeCall(projectId, jobId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GlobalResponse>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 25
Source Project: tencentcloud-sdk-java   Source File: PostgresClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *本接口 (InitDBInstances) 用于初始化云数据库PostgreSQL实例。
 * @param req InitDBInstancesRequest
 * @return InitDBInstancesResponse
 * @throws TencentCloudSDKException
 */
public InitDBInstancesResponse InitDBInstances(InitDBInstancesRequest req) throws TencentCloudSDKException{
    JsonResponseModel<InitDBInstancesResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<InitDBInstancesResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "InitDBInstances"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 26
Source Project: java-stellar-sdk   Source File: LedgersRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Requests specific <code>uri</code> and returns {@link Page} of {@link LedgerResponse}.
 * This method is helpful for getting the next set of results.
 * @return {@link Page} of {@link LedgerResponse}
 * @throws TooManyRequestsException when too many requests were sent to the Horizon server.
 * @throws IOException
 */
public static Page<LedgerResponse> execute(OkHttpClient httpClient, HttpUrl uri) throws IOException, TooManyRequestsException {
  TypeToken type = new TypeToken<Page<LedgerResponse>>() {};
  ResponseHandler<Page<LedgerResponse>> responseHandler = new ResponseHandler<Page<LedgerResponse>>(type);

  Request request = new Request.Builder().get().url(uri).build();
  Response response = httpClient.newCall(request).execute();

  return responseHandler.handleResponse(response);
}
 
Example 27
Source Project: director-sdk   Source File: DeploymentsApi.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * List all deployments (asynchronously)
 * 
 * @param environment  (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call listAsync(String environment, final ApiCallback<List<String>> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = listValidateBeforeCall(environment, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<List<String>>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 28
Source Project: tencentcloud-sdk-java   Source File: YunjingClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *本接口 (ModifyProVersionRenewFlag) 用于修改专业版包年包月续费标识。
 * @param req ModifyProVersionRenewFlagRequest
 * @return ModifyProVersionRenewFlagResponse
 * @throws TencentCloudSDKException
 */
public ModifyProVersionRenewFlagResponse ModifyProVersionRenewFlag(ModifyProVersionRenewFlagRequest req) throws TencentCloudSDKException{
    JsonResponseModel<ModifyProVersionRenewFlagResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<ModifyProVersionRenewFlagResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "ModifyProVersionRenewFlag"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 29
Source Project: tencentcloud-sdk-java   Source File: DayuClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *批量上传7层转发规则
 * @param req CreateL7RulesUploadRequest
 * @return CreateL7RulesUploadResponse
 * @throws TencentCloudSDKException
 */
public CreateL7RulesUploadResponse CreateL7RulesUpload(CreateL7RulesUploadRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateL7RulesUploadResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateL7RulesUploadResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateL7RulesUpload"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example 30
Source Project: tencentcloud-sdk-java   Source File: YunjingClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *本接口 (DescribeProVersionInfo) 用于获取专业版信息。
 * @param req DescribeProVersionInfoRequest
 * @return DescribeProVersionInfoResponse
 * @throws TencentCloudSDKException
 */
public DescribeProVersionInfoResponse DescribeProVersionInfo(DescribeProVersionInfoRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DescribeProVersionInfoResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DescribeProVersionInfoResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DescribeProVersionInfo"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}