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

The following are top voted examples for showing how to use com.google.gson.reflect.TypeToken. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: avaire   File: PlaylistTransformer.java   Source Code and License 9 votes vote down vote up
public PlaylistTransformer(DataRow data) {
    super(data);

    if (hasData()) {
        id = data.getInt("id");
        size = data.getInt("size");
        guildId = data.getLong("guild_id");
        name = data.getString("name");

        if (data.has("songs") && data.getString("songs").length() > 0) {
            List<PlaylistSong> songs = AvaIre.GSON.fromJson(data.getString("songs"), (new TypeToken<List<PlaylistSong>>() {
            }.getType()));

            if (!songs.isEmpty()) {
                this.songs.addAll(songs);
            }
        }
    }
}
 
Example 2
Project: ObjectBoxDebugBrowser   File: RequestHandler.java   Source Code and License 8 votes vote down vote up
private String addTableDataAndGetResponse(String route) {
    UpdateRowResponse response;
    try {
        Uri uri = Uri.parse(URLDecoder.decode(route, "UTF-8"));
        String tableName = uri.getQueryParameter("tableName");
        String updatedData = uri.getQueryParameter("addData");
        List<RowDataRequest> rowDataRequests = mGson.fromJson(updatedData, new TypeToken<List<RowDataRequest>>() {
        }.getType());

        response = DatabaseHelper.addRow(null, tableName, rowDataRequests);
        return mGson.toJson(response);
    } catch (Exception e) {
        e.printStackTrace();
        response = new UpdateRowResponse();
        response.isSuccessful = false;
        return mGson.toJson(response);
    }
}
 
Example 3
Project: Jenisys3   File: BanList.java   Source Code and License 6 votes vote down vote up
public void load() {
    this.list = new LinkedHashMap<>();
    File file = new File(this.file);
    try {
        if (!file.exists()) {
            file.createNewFile();
            this.save();
        } else {

            LinkedList<TreeMap<String, String>> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken<LinkedList<TreeMap<String, String>>>() {
            }.getType());
            for (TreeMap<String, String> map : list) {
                BanEntry entry = BanEntry.fromMap(map);
                this.list.put(entry.getName(), entry);
            }
        }
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not load ban list: ", e);
    }

}
 
Example 4
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 6 votes vote down vote up
/**
 * Retrieves the types of processors that this NiFi supports (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @param bundleGroupFilter If specified, will only return types that are a member of this bundle group. (optional)
 * @param bundleArtifactFilter If specified, will only return types that are a member of this bundle artifact. (optional)
 * @param type If specified, will only return types whose fully qualified classname matches. (optional)
 * @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 getProcessorTypesAsync(String bundleGroupFilter, String bundleArtifactFilter, String type, final ApiCallback<ProcessorTypesEntity> 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 = getProcessorTypesValidateBeforeCall(bundleGroupFilter, bundleArtifactFilter, type, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ProcessorTypesEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 5
Project: android-apps   File: WeatherActivity.java   Source Code and License 6 votes vote down vote up
public List<CityData> getCityInfo() {
  if (citys.size() == 0) {
    try {
      InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("china_city_id.json"));
      BufferedReader bufferedReader = new BufferedReader(
          inputStreamReader);
      String line;
      StringBuilder stringBuilder = new StringBuilder();
      while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
      }
      bufferedReader.close();
      inputStreamReader.close();
      String json = stringBuilder.toString();
      citys = GsonUtil.getInstance().fromJson(json, new TypeToken<List<CityData>>() {
      }.getType());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return citys;
}
 
Example 6
Project: FriendBook   File: DataManager.java   Source Code and License 6 votes vote down vote up
/**
 * 获取小说列表
 *
 * @param page     页码
 * @param size     每页的条目数
 * @param bookType 图书类别ID ,传0为获取全部
 */
public Observable<DataList<Book>> getBookList(long bookType, int page, int size) {
    HashMap<String, Object> hashMap = new HashMap<>();
    hashMap.put("page_index", page);
    hashMap.put("page_size", size);
    if (bookType > 0) hashMap.put("book_type", bookType);
    return RequestClient
            .getServerAPI()
            .getBookList(hashMap)
            .map(new HttpResultFunc<DataList<Book>>())
            .compose(rxCache.<DataList<Book>>transformer("getBookList" + page + size + bookType, new TypeToken<DataList<Book>>() {
            }.getType(), CacheStrategy.firstCache()))
            .map(new Func1<CacheResult<DataList<Book>>, DataList<Book>>() {
                @Override
                public DataList<Book> call(CacheResult<DataList<Book>> cacheResult) {
                    return cacheResult.getData();
                }
            });
}
 
Example 7
Project: toyBatis   File: DbSession.java   Source Code and License 6 votes vote down vote up
private List<Mapper> getMapperFileData(Class<? extends Object> mapper) throws IOException
{
    if (mapper.isAnnotationPresent(Mapping.class))
    {
        Mapping mapping = mapper.getAnnotation(Mapping.class);
        String mappingFilename = mapping.filename();
        String mappingContent = IOUtils.resourceToString(mappingFilename, null,
                DbSession.class.getClassLoader());
        if (mappingContent != null && !mappingContent.isEmpty())
        {
            Type mapperListType = new TypeToken<ArrayList<Mapper>>(){}.getType();
            List<Mapper> mapperList = gson.fromJson(mappingContent, mapperListType);
            return mapperList;
        }
    }
    return null;
}
 
Example 8
Project: module-template   File: Unit2CreationTests.java   Source Code and License 6 votes vote down vote up
@DataProvider
public Iterator<Object[]> validUnits2FromJson() throws IOException {
    String json = "";

    try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/units2.json")))) {
        String line = reader.readLine();
        while (line != null) {
            json += line;
            line = reader.readLine();
        }
    }

    Gson gson = new Gson();
    List<Unit2Data> units2 = gson.fromJson(json, new TypeToken<List<Unit2Data>>(){}.getType()); // like a List<Unit2Data>.class
    return units2.stream().map((g) -> new Object[] {g}).collect(Collectors.toList()).iterator();
}
 
Example 9
Project: hauth-java   File: OrgController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(HttpServletResponse response, HttpServletRequest request) {
    String json = request.getParameter("JSON");
    List<OrgEntity> list = new GsonBuilder().create().fromJson(json,
            new TypeToken<List<OrgEntity>>() {
            }.getType());
    ;
    for (OrgEntity m : list) {

        String orgId = m.getOrg_id();
        String domainId = m.getDomain_id();

        AuthDTO authDTO = authService.domainAuth(request, domainId, "w");
        if (!authDTO.getStatus()) {
            return Hret.error(403, "您没有权限删除域【" + domainId + "】中的机构信息", null);
        }
    }

    RetMsg retMsg = orgService.delete(list);
    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }
    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
 
Example 10
Project: Hitalk   File: ExampleUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGson() throws ClassNotFoundException {
   /* B b = new B();
    b.b = "b";
    b.a = "a";
    String json = new Gson().toJson(b);
    A a = new Gson().fromJson(json,A.class);
    *//*A a1 = (A) new Gson().fromJson(json,Class.forName(a.className));*//*
    b = (B) a;*/
    HashMap<String,Integer> entries = new HashMap<>();
    entries.put("abc",1);

    System.out.println(new Gson().toJson(entries));

    HashMap hashMap = new Gson().fromJson(new Gson().toJson(entries), entries.getClass());

    Type type = new TypeToken<HashMap<String, Integer>>() {
    }.getType();
   // System.out.println(new Gson().fromJson(new Gson().toJson(entries), type));


}
 
Example 11
Project: CouponsTracker   File: ImportFromDriveService.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a {@link ContentValues} array of all the coupons in the
 * coupons JSON.
 */
private ContentValues[] getContentValuesArray(String couponsJson) {
    Gson gson = new Gson();
    /*
    Convert the json representation of the coupon data to an arrayList
    of coupons. Logic to perform this taken from:
    https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types
     */
    Type collectionType = new TypeToken<ArrayList<Coupon>>(){}.getType();
    ArrayList<Coupon> coupons = gson.fromJson(couponsJson, collectionType);
    ContentValues[] contentValuesArray = new ContentValues[coupons.size()];
    for (int i = 0; i < contentValuesArray.length; i++) {
        contentValuesArray[i] = Coupon.getContentValues(coupons.get(i));
    }
    return contentValuesArray;
}
 
Example 12
Project: boohee_v5.6   File: Gson.java   Source Code and License 6 votes vote down vote up
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException,
        JsonSyntaxException {
    boolean isEmpty = true;
    boolean oldLenient = reader.isLenient();
    reader.setLenient(true);
    try {
        reader.peek();
        isEmpty = false;
        T object = getAdapter(TypeToken.get(typeOfT)).read(reader);
        reader.setLenient(oldLenient);
        return object;
    } catch (Throwable e) {
        if (isEmpty) {
            reader.setLenient(oldLenient);
            return null;
        }
        throw new JsonSyntaxException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonSyntaxException(e22);
    } catch (Throwable th) {
        reader.setLenient(oldLenient);
    }
}
 
Example 13
Project: CommonsLab   File: StorageUtil.java   Source Code and License 6 votes vote down vote up
public ArrayList<FeedItem> retrieveRSS_Feed(MediaType mediaType) {
    if (mediaType == MediaType.PICTURE) {
        preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
    } else {
        preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
    }

    //Check if the feed is valid
    if (!preferences.getString("Date", "").equals(new Today().date())) return null;

    Gson gson = new Gson();
    String json = preferences.getString("RSS_Feed", null);
    Type type = new TypeToken<ArrayList<FeedItem>>() {
    }.getType();
    return gson.fromJson(json, type);
}
 
Example 14
Project: Regalia   File: GsonRealmListTest.java   Source Code and License 5 votes vote down vote up
@Test
public void parse() throws Exception {
    String json = TestUtil.getCatWithListOfFriendsJson();
    Type catRealmListType = new TypeToken<RealmList<Cat>>(){}.getType();
    CatListConverter catRealmListConverter = new CatListConverter();
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(catRealmListType, catRealmListConverter)
            .create();
    Cat cat = gson.fromJson(json, Cat.class);
    Assert.assertNotNull(cat);
    Assert.assertNotNull(cat.friends);
}
 
Example 15
Project: mazes_and_minotaurs   File: CharacterSerializer.java   Source Code and License 5 votes vote down vote up
@Override
public JsonElement serialize(PlayerCharacter src, Type typeOfSrc, JsonSerializationContext context) {
    BaseClass characterClass = src.getCharClass();
    characterClass.setCharacter(null);

    Type equipListType = new TypeToken<ArrayList<Equipment>>() {
    }.getType();
    Type moneyMapType = new TypeToken<HashMap<Money, Integer>>() {
    }.getType();

    JsonObject rootObject = new JsonObject();
    rootObject.add("mScores", context.serialize(src.getScores()));
    rootObject.add("mCharClass", context.serialize(src.getCharClass(), BaseClass.class));
    rootObject.add("mGender", context.serialize(src.getGender()));
    rootObject.add("mMoney", context.serialize(src.getMoney(), moneyMapType));
    rootObject.add("mAge", context.serialize(src.getAge()));
    rootObject.add("mName", context.serialize(src.getName()));
    System.out.println(getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mInventory", getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mCurrentWeapon", context.serialize(src.getCurrentWeapon()));
    rootObject.add("mHelmet", context.serialize(src.getHelmet()));
    rootObject.add("mBreastplate", context.serialize(src.getBreastplate()));
    rootObject.add("mShield", context.serialize(src.getShield()));
    rootObject.add("mPatron", context.serialize(src.getPatron()));

    JsonElement classJson = context.serialize(characterClass);
    rootObject.add("mCharClass", classJson);

    characterClass.setCharacter(src);
    return rootObject;
}
 
Example 16
Project: nifi-swagger-client   File: FunnelApi.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a funnel (asynchronously)
 * 
 * @param id The funnel 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 getFunnelAsync(String id, final ApiCallback<FunnelEntity> 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 = getFunnelValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<FunnelEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 17
Project: train-simulator   File: SocketSession.java   Source Code and License 5 votes vote down vote up
public String getResponse(String message) {

    /*if (message.equals("start trains")) {
      sim.startTrains();
      return "OK";
    }*/

    SimulationController simulation = SimulationController.getInstance();
    /*if (simulation.isKilled()) {
      simulation = SimulationController.newInstance();
    }*/
    logger.info("message: {}", message);

    try {
      Type stringStringMap = new TypeToken<Map<String, String>>() {
      }.getType();
      Map<String, String> map = gson.fromJson(message, stringStringMap);

      if (map.containsKey("command")) {
        return CommandHelper.processCommand(simulation, map, this) ? "OK" : "FAIL";
      }
      if (map.containsKey("type") && map.get("type").equals("set")) {
        return CommandHelper.processSetCommand(simulation, map) ? "OK" : "FAIL";
      }
    } catch (com.google.gson.JsonSyntaxException ex) {
      // wasn't json
      ex.printStackTrace();
    }

    return "echo: " + message;
  }
 
Example 18
Project: Farmacias   File: PreferencesManagerImp.java   Source Code and License 5 votes vote down vote up
@Override
public HashMap<String, Integer> getColorMap() {
    if(mPrefs.contains(COLOR_MAP_KEY)) {
        String jsonString = mPrefs.getString(COLOR_MAP_KEY, null);
        if(jsonString !=null) {
            java.lang.reflect.Type type = new TypeToken<HashMap<String, Integer>>(){}.getType();
            return  new Gson().fromJson(jsonString,type);
        }
    }
    return null;
}
 
Example 19
Project: GitHub   File: BannerPracticeActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_practice_banner);

    final Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    final RefreshLayout refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);

    mAdapter = new QuickAdapter();
    recyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(mAdapter);
    refreshLayout.autoRefresh();
    refreshLayout.setOnRefreshListener(new OnRefreshListener() {
        @Override
        public void onRefresh(final RefreshLayout refreshlayout) {
            refreshlayout.getLayout().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mAdapter.getItemCount() < 2) {
                        List<Movie> movies = new Gson().fromJson(JSON_MOVIES, new TypeToken<ArrayList<Movie>>() {}.getType());
                        mAdapter.replaceData(movies);
                    }
                    refreshlayout.finishRefresh();
                }
            },2000);
        }
    });

    //添加Header
    View header = LayoutInflater.from(this).inflate(R.layout.listitem_movie_header, recyclerView, false);
    Banner banner = (Banner) header;
    banner.setImageLoader(new GlideImageLoader());
    banner.setImages(BANNER_ITEMS);
    banner.start();
    mAdapter.addHeaderView(banner);

    //状态栏透明和间距处理
    StatusBarUtil.immersive(this);
    StatusBarUtil.setPaddingSmart(this, toolbar);
    StatusBarUtil.setPaddingSmart(this, recyclerView);
    StatusBarUtil.setMargin(this, findViewById(R.id.header));
    StatusBarUtil.setPaddingSmart(this, findViewById(R.id.blurview));
}
 
Example 20
Project: swaggy-jenkins   File: BlueOceanApi.java   Source Code and License 5 votes vote down vote up
/**
 *  (asynchronously)
 * Retrieve SCM details for an organization
 * @param organization Name of the organization (required)
 * @param scm Name of SCM (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 getSCMAsync(String organization, String scm, final ApiCallback<GithubScm> 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 = getSCMValidateBeforeCall(organization, scm, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GithubScm>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 21
Project: nifi-swagger-client   File: AccessApi.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the access configuration for this NiFi (asynchronously)
 * 
 * @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 getLoginConfigAsync(final ApiCallback<AccessConfigurationEntity> 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 = getLoginConfigValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<AccessConfigurationEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 22
Project: GitHub   File: GsonParserFactory.java   Source Code and License 5 votes vote down vote up
@Override
public HashMap<String, String> getStringMap(Object object) {
    try {
        Type type = new TypeToken<HashMap<String, String>>() {
        }.getType();
        return gson.fromJson(gson.toJson(object), type);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}
 
Example 23
Project: happy-news   File: NotificationSettingsActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_settings);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    setTitle(R.string.title_settings_notification);
    notificationListView = (ListView) findViewById(R.id.notificationListView);

    preferences = getApplicationContext().getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

    addNotificationFab = (FloatingActionButton) findViewById(R.id.timePickerFAB);
    addNotificationFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new TimePickerFragment();
            newFragment.show(getFragmentManager(), "timePicker");
        }
    });

    notifications = new ArrayList<>();
    String notificationsGsonString = preferences.getString(getString(R.string.preference_notifications), "");
    Type type = new TypeToken<List<NotificationSetting>>() {
    }.getType();
    if (!notificationsGsonString.equals("")) {
        notifications = new Gson().fromJson(notificationsGsonString, type);
    }
    refreshList();
}
 
Example 24
Project: afp-api-client   File: ClusterApi.java   Source Code and License 5 votes vote down vote up
/**
 * Word cluster (asynchronously)
 * Return the word cluster from a search
 * @param parameters parameters (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 clusterUsingPOST1Async(Parameters parameters, final ApiCallback<ReponseCluster> 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 = clusterUsingPOST1Call(parameters, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ReponseCluster>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 25
Project: ease-volley-wrapper   File: EaseRequest.java   Source Code and License 5 votes vote down vote up
RequestBuilder(TypeToken<EaseResponse<K>> typeToken) {
    method = Request.Method.GET;
    runInBackground = false;
    this.typeToken = typeToken;
    this.shouldCache = -1; // fall back to default
    this.socketTimeout = -1; // fall back to default
}
 
Example 26
Project: Nyris.IMX.Android   File: ObjectProposalTask.java   Source Code and License 5 votes vote down vote up
/**
 * Evaluate the content of response
 * @param content of type Object it could be ErrorResponse or a String
 */
@Override
protected void onPostExecute(Object content) {
    if(callback == null)
        return;
    if(content instanceof ResponseError){
        ResponseError responseError = (ResponseError) content;
        callback.onError(responseError);
    }
    else{
        String strContent = (String) content;
        try {
            Gson gson = new Gson();
            List<ObjectProposal> objectProposals = gson.fromJson(strContent, new TypeToken<List<ObjectProposal>>(){}.getType());
            if(objectProposals != null){
                callback.onObjectExtracted(objectProposals);
            }
            else {
                responseError.setErrorCode(ResponseCode.OBJECT_NOT_FOUND_ERROR);
                responseError.setErrorDescription(context.getText(R.string.error_object_not_found).toString());
                callback.onError(responseError);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            responseError.setErrorCode(ResponseCode.UNKNOWN_ERROR);
            responseError.setErrorDescription(e.getMessage());
            callback.onError(responseError);
        }
    }
}
 
Example 27
Project: letv   File: Gson.java   Source Code and License 5 votes vote down vote up
public <T> TypeAdapter<T> getNextAdapter(Gson gson, TypeAdapterFactory skipPast, TypeToken<T> type) {
    boolean skipPastFound = false;
    for (TypeAdapterFactory factory : gson.factories) {
        if (skipPastFound) {
            TypeAdapter<T> candidate = factory.create(gson, type);
            if (candidate != null) {
                return candidate;
            }
        } else if (factory == skipPast) {
            skipPastFound = true;
        }
    }
    throw new IllegalArgumentException("GSON cannot serialize " + type);
}
 
Example 28
Project: boohee_v5.6   File: Food.java   Source Code and License 5 votes vote down vote up
public static ArrayList<Food> parseFoods(JSONObject res) {
    ArrayList<Food> foods = null;
    try {
        return (ArrayList) new Gson().fromJson(res.optJSONArray("foods").toString(), new TypeToken<ArrayList<Food>>() {
        }.getType());
    } catch (Exception e) {
        e.printStackTrace();
        return foods;
    }
}
 
Example 29
Project: RestClient   File: RestTestInteractorImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void saveRestTest(RestTest test) {
    Settings settings = RestClientApplication.getSettings();
    String value = settings.get(key);
    List<RestTest> result = new ArrayList<>();
    int pos = -1;
    if (null != value) {
        Gson gson = new Gson();
        result = gson.fromJson(value, new TypeToken<List<RestTest>>() {
        }.getType());
        int size = result.size();
        for (int i = 0; i < size; i++) {
            RestTest temp = result.get(i);
            if (temp.getId().equals(test.getId())) {
                pos = i;
                break;
            }
        }

    }
    if (pos != -1) {
        result.set(pos, test);
    } else {
        result.add(0, test);
    }
    settings.put(key, result);
}
 
Example 30
Project: full-javaee-app   File: Geocode.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static String getZipFromLatLong(String latitude, String longitude) {
       String request = "https://maps.googleapis.com/maps/api/geocode/json?";
       String address = "address=";
       String coOrdinates = "latlng=";
	CustomUtilities custom = new CustomUtilities();
	String zip = "";
	String finalRequest = request + coOrdinates + latitude + "," + longitude + "&" + key;

	// To convert resulting JSON into Map
	Gson gson = new Gson();

	// Models expected JSON, very basic
	Type type = new TypeToken<Map<String, Object>>() {
	}.getType();

	// Pulls JSON from api request
	String json = custom.RequestToString(finalRequest);

	// Creates map using Gson
	Map<String, Object> map = gson.fromJson(json, type);
	ArrayList list = ((ArrayList)((LinkedTreeMap)((ArrayList) map.get("results")).get(0)).get("address_components"));
	
	for (Object elt : list) {
		LinkedTreeMap treeElt = (LinkedTreeMap) elt;
		String name = (String) ((ArrayList)treeElt.get("types")).get(0);
		
		if (name.equals("postal_code")) {
			zip = (String) (treeElt.get("short_name"));
			break;
		}
	}
	
	return zip == null ? " " : zip;
}
 
Example 31
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 5 votes vote down vote up
/**
 * Generates a client id. (asynchronously)
 * 
 * @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 generateClientIdAsync(final ApiCallback<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 = generateClientIdValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<String>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 32
Project: logistimo-web-service   File: ReportServiceUtil.java   Source Code and License 5 votes vote down vote up
protected Report constructReport(List<Field> fields, JSONArray row) throws IllegalAccessException {
  Report report = new Report();
  for (int j = 0; j < row.length(); j++) {
    Field field = fields.get(j);
    switch (field.getType().getSimpleName()) {
      case LONG:
        if (StringUtils.isNotBlank(row.getString(j))) {
          field.set(report, row.getLong(j));
        } else {
          field.set(report, 0L);
        }
        break;
      case FLOAT:
        if (StringUtils.isNotBlank(row.getString(j))) {
          field.set(report, new Float(row.getDouble(j)));
        } else {
          field.set(report, 0F);
        }
        break;
      case MAP:
        try {
          field.set(report,
              new Gson().fromJson(row.getString(j), new TypeToken<Map<String, Float>>() {
              }.getType()));
        } catch (Exception e) {
          field.set(report, new HashMap(0));
        }
        break;
      default:
        field.set(report, row.get(j));
    }
  }
  return report;
}
 
Example 33
Project: cryptotrader   File: BitmexContextTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCancelOrders() throws Exception {

    doAnswer(i -> {

        assertEquals(i.getArgumentAt(0, RequestType.class), DELETE);
        assertEquals(i.getArgumentAt(1, String.class), "/api/v1/order");
        assertEquals(i.getArgumentAt(2, Map.class), emptyMap());
        String data = i.getArgumentAt(3, String.class);

        Map<String, Set<String>> map = new Gson().fromJson(data, new TypeToken<Map<String, Set<String>>>() {
        }.getType());
        assertEquals(map.remove("clOrdID"), Sets.newHashSet(null, "uid1"));

        return new Gson().toJson(singleton(singletonMap("clOrdID", "uid1")));

    }).when(target).executePrivate(any(), any(), any(), any());

    CancelInstruction i1 = CancelInstruction.builder().id(null).build();
    CancelInstruction i2 = CancelInstruction.builder().id("uid1").build();

    Key key = Key.builder().instrument("XBTZ17").build();
    Map<CancelInstruction, String> result = target.cancelOrders(key, Sets.newHashSet(i1, null, i2));
    assertEquals(result.size(), 2);
    assertEquals(result.get(i1), null);
    assertEquals(result.get(i2), "uid1");

}
 
Example 34
Project: GitHub   File: RxOperatorExampleActivity.java   Source Code and License 5 votes vote down vote up
/************************************
 * flatMap and filter operator start
 ************************************/

private Observable<List<User>> getAllMyFriendsObservable() {
    return RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllFriends/{userId}")
            .addPathParameter("userId", "1")
            .build()
            .getParseObservable(new TypeToken<List<User>>() {
            });
}
 
Example 35
Project: HLOLI   File: SharedPreManager.java   Source Code and License 5 votes vote down vote up
/**
 * 获取搜索历史
 *
 * @param context
 * @return
 */
public List<String> getHistory(Context context) {
    SharedPreferences sp = context.getSharedPreferences(SP_TAG, Context.MODE_PRIVATE);
    String jsonData = sp.getString(HISTORY, "");
    return gson.fromJson(jsonData, new TypeToken<List<String>>() {
    }.getType());
}
 
Example 36
Project: coner-core-client-java   File: HandicapGroupsApi.java   Source Code and License 5 votes vote down vote up
/**
 * Get all Handicap Group Sets (asynchronously)
 * 
 * @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 getHandicapGroupSetsAsync(final ApiCallback<GetHandicapGroupSetsResponse> 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 = getHandicapGroupSetsValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GetHandicapGroupSetsResponse>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 37
Project: intellij-circleci-integration   File: BuildsModelTest.java   Source Code and License 5 votes vote down vote up
private List<BuildInterface> createMockBuilds() throws IOException {
    String json = IOUtils.toString(
            getClass().getResourceAsStream("/recent-builds.json"),
            Charset.defaultCharset()
    );
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<List<RecentBuild>>() {}.getType());
}
 
Example 38
Project: nifi-swagger-client   File: TenantsApi.java   Source Code and License 5 votes vote down vote up
/**
 * Gets all users (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @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 getUsersAsync(final ApiCallback<UsersEntity> 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 = getUsersValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<UsersEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 39
Project: letv   File: TypeAdapterRuntimeTypeWrapper.java   Source Code and License 5 votes vote down vote up
public void write(JsonWriter out, T value) throws IOException {
    TypeAdapter chosen = this.delegate;
    Type runtimeType = getRuntimeTypeIfMoreSpecific(this.type, value);
    if (runtimeType != this.type) {
        TypeAdapter runtimeTypeAdapter = this.context.getAdapter(TypeToken.get(runtimeType));
        if (!(runtimeTypeAdapter instanceof Adapter)) {
            chosen = runtimeTypeAdapter;
        } else if (this.delegate instanceof Adapter) {
            chosen = runtimeTypeAdapter;
        } else {
            chosen = this.delegate;
        }
    }
    chosen.write(out, value);
}
 
Example 40
Project: customstuff4   File: ItemFilterDeserializerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test_machineInput()
{
    MachineManager.addRecipe(new ResourceLocation("someMachine"), new TestMachineRecipe());
    Map<String, ItemFilter> map = gson.fromJson("{\"filter\": \"machineInput:someMachine\"}", new TypeToken<Map<String, ItemFilter>>() {}.getType());

    ItemFilter filter = map.get("filter");

    assertTrue(filter.accepts(new ItemStack(Items.STICK)));
    assertTrue(filter.accepts(new ItemStack(Items.IRON_INGOT)));
    assertFalse(filter.accepts(new ItemStack(Items.GOLD_INGOT)));
}
 
Example 41
Project: Android-Development   File: StorageUtil.java   Source Code and License 5 votes vote down vote up
public ArrayList<ParcelablePOI> getFavoritePOIs() {
    preferences = context.getSharedPreferences(FAVORITES, Context.MODE_PRIVATE);
    String pois;
    //Get favorites that are previously stored
    if ((pois = preferences.getString("FAVORITES", null)) == null) return null;
    if (pois.equals("")) return null;//no favorites stored yet

    Gson gson = new Gson();
    Type type = new TypeToken<ArrayList<ParcelablePOI>>() {
    }.getType();
    return gson.fromJson(pois, type);
}
 
Example 42
Project: WIFIProbe   File: CustomerKeyMapper.java   Source Code and License 5 votes vote down vote up
@Override
protected void map(Object key, Text value, Context context)
        throws IOException, InterruptedException {

    Logger.println("[map read line]: " + count++);
    if (value.getLength()==0) {
        Logger.println("[map empty line]: empty line");
        return;
    }
    List<ProbeJson> probeJsons = gson.fromJson(
            value.toString(), new TypeToken<List<ProbeJson>>(){}.getType());
    Logger.println("[probes converted]: convert to java list, size =  "+probeJsons.size());

    for (ProbeJson prob:probeJsons) {

        long time = -1L;
        try {
            System.out.println(prob.getTime());
            time = DateFormatter.getMillis(prob.getTime());
        }catch (Exception e) {
            Logger.println("[warn]: time format error!!");
        }

        if (time>=0) {
            for (PhoneJson phoneJson : prob.getData()) {
                Logger.println("[phone data]: one phone data with mac address: " +phoneJson.getMac() );
                Logger.println("[phone data]: one phone data with time: " +phoneJson.getTime() );
                phoneJson.setTime(time);
                phoneAsKey.set(phoneJson.getMac());
                context.write(phoneAsKey, phoneJson);
                Logger.println("[map write to combiner]");
            }
        }

    }
}
 
Example 43
Project: ZhiHuIndex-master   File: GsonTool.java   Source Code and License 5 votes vote down vote up
public static List<User> getuList(String jsonString) {
    List<User> uList = new ArrayList<User>();
    try {
        Gson gson = new Gson();
        Type type = new TypeToken<List<User>>(){}.getType();
        JsonReader jsonReader = new JsonReader(new StringReader(jsonString));
        jsonReader.setLenient(true);
        uList = gson.fromJson(jsonReader, type);
    } catch (JsonSyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return uList;
}
 
Example 44
Project: boohee_v5.6   File: UserConnection.java   Source Code and License 5 votes vote down vote up
public static ArrayList<UserConnection> parseUserConnections(JSONObject object) {
    ArrayList<UserConnection> connections = null;
    try {
        JSONArray connObj = object.getJSONArray("user_connections");
        return (ArrayList) new Gson().fromJson(connObj.toString(), new
                TypeToken<ArrayList<UserConnection>>() {
        }.getType());
    } catch (JSONException e) {
        e.printStackTrace();
        return connections;
    }
}
 
Example 45
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 5 votes vote down vote up
/**
 * Gets status history for a processor (asynchronously)
 * 
 * @param id The processor 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 getProcessorStatusHistoryAsync(String id, final ApiCallback<StatusHistoryEntity> 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 = getProcessorStatusHistoryValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<StatusHistoryEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 46
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 5 votes vote down vote up
/**
 * Gets status history for a remote process group (asynchronously)
 * 
 * @param id The process group 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 getProcessGroupStatusHistoryAsync(String id, final ApiCallback<StatusHistoryEntity> 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 = getProcessGroupStatusHistoryValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<StatusHistoryEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 47
Project: Gather-Platform   File: ResultBundleResolver.java   Source Code and License 5 votes vote down vote up
/**
 * 解析ResultBundle
 *
 * @param json 服务器返回的json数据
 * @param <T>
 * @return
 */
public <T> ResultBundle<T> bundle(String json) {
    ResultBundle<T> resultBundle = null;
    try {
        Type objectType = new TypeToken<ResultBundle<T>>() {
        }.getType();
        resultBundle = gson.fromJson(json, objectType);
    } catch (JsonSyntaxException e) {
        LOG.error("无法解析的返回值信息:" + json);
        e.printStackTrace();
    }
    validate(resultBundle);
    return resultBundle;
}
 
Example 48
Project: CloudNet   File: MobDatabase.java   Source Code and License 5 votes vote down vote up
public Map<UUID, ServerMob> loadAll()
{
    boolean injectable = false;
    Map<UUID, ServerMob> mobMap = database.getDocument("server_selector_mobs").getObject("mobs", new TypeToken<Map<UUID, ServerMob>>(){}.getType());

    for(ServerMob serverMob : mobMap.values())
    {
        if(serverMob.getItemId() == null)
        {
            serverMob.setItemId(138);
            injectable = true;
        }
        if(serverMob.getAutoJoin() == null)
        {
            serverMob.setAutoJoin(false);
            injectable = true;
        }
    }

    if(injectable)
    {
        Document document = database.getDocument("server_selector_mobs");
        document.append("mobs", mobMap);
        database.insert(document);
    }

    return mobMap;
}
 
Example 49
Project: customstuff4   File: EnumPlantTypeDeserializerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception
{
    Map<String, EnumPlantType> map = gson.fromJson("{ \"plant\": \"Crop\" }", new TypeToken<Map<String, EnumPlantType>>() {}.getType());

    EnumPlantType plant = map.get("plant");

    assertSame(EnumPlantType.Crop, plant);
}
 
Example 50
Project: nifi-swagger-client   File: DataTransferApi.java   Source Code and License 5 votes vote down vote up
/**
 * Commit or cancel the specified transaction (asynchronously)
 * 
 * @param responseCode The response code. Available values are CONFIRM_TRANSACTION(12) or CANCEL_TRANSACTION(15). (required)
 * @param checksum A checksum calculated at client side using CRC32 to check flow file content integrity. It must match with the value calculated at server side. (required)
 * @param portId The output port id. (required)
 * @param transactionId The transaction 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 commitOutputPortTransactionAsync(Integer responseCode, String checksum, String portId, String transactionId, final ApiCallback<TransactionResultEntity> 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 = commitOutputPortTransactionValidateBeforeCall(responseCode, checksum, portId, transactionId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<TransactionResultEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 51
Project: nifi-swagger-client   File: FlowfileQueuesApi.java   Source Code and License 5 votes vote down vote up
/**
 * Lists the contents of the queue in this connection. (asynchronously)
 * 
 * @param id The connection 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 createFlowFileListingAsync(String id, final ApiCallback<ListingRequestEntity> 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 = createFlowFileListingValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ListingRequestEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 52
Project: coner-core-client-java   File: ResultsApi.java   Source Code and License 5 votes vote down vote up
/**
 * Get results for a registration at an event (asynchronously)
 * 
 * @param eventId Event ID (required)
 * @param registrationId Registration 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 getEventRegistrationResultsAsync(String eventId, String registrationId, final ApiCallback<GetEventResultsRegistrationResponse> 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 = getEventRegistrationResultsValidateBeforeCall(eventId, registrationId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GetEventResultsRegistrationResponse>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 53
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 5 votes vote down vote up
/**
 * Gets status for a remote process group (asynchronously)
 * 
 * @param id The remote process group id. (required)
 * @param nodewise Whether or not to include the breakdown per node. Optional, defaults to false (optional)
 * @param clusterNodeId The id of the node where to get the status. (optional)
 * @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 getRemoteProcessGroupStatusAsync(String id, Boolean nodewise, String clusterNodeId, final ApiCallback<ProcessorStatusEntity> 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 = getRemoteProcessGroupStatusValidateBeforeCall(id, nodewise, clusterNodeId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ProcessorStatusEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 54
Project: nifi-swagger-client   File: DataTransferApi.java   Source Code and License 5 votes vote down vote up
/**
 * Transfer flow files from the output port (asynchronously)
 * 
 * @param portId The output port id. (required)
 * @param transactionId  (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 transferFlowFilesAsync(String portId, String transactionId, final ApiCallback<StreamingOutput> 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 = transferFlowFilesValidateBeforeCall(portId, transactionId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<StreamingOutput>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 55
Project: boohee_v5.6   File: Coupon.java   Source Code and License 5 votes vote down vote up
public static ArrayList<Coupon> parse(JSONObject res) {
    try {
        return (ArrayList) new Gson().fromJson(res.getString("coupons").toString(), new
                TypeToken<ArrayList<Coupon>>() {
        }.getType());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 56
Project: nifi-swagger-client   File: FlowApi.java   Source Code and License 5 votes vote down vote up
/**
 * Retrieves the types of controller services that this NiFi supports (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @param serviceType If specified, will only return controller services that are compatible with this type of service. (optional)
 * @param serviceBundleGroup If serviceType specified, is the bundle group of the serviceType. (optional)
 * @param serviceBundleArtifact If serviceType specified, is the bundle artifact of the serviceType. (optional)
 * @param serviceBundleVersion If serviceType specified, is the bundle version of the serviceType. (optional)
 * @param bundleGroupFilter If specified, will only return types that are a member of this bundle group. (optional)
 * @param bundleArtifactFilter If specified, will only return types that are a member of this bundle artifact. (optional)
 * @param typeFilter If specified, will only return types whose fully qualified classname matches. (optional)
 * @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 getControllerServiceTypesAsync(String serviceType, String serviceBundleGroup, String serviceBundleArtifact, String serviceBundleVersion, String bundleGroupFilter, String bundleArtifactFilter, String typeFilter, final ApiCallback<ControllerServiceTypesEntity> 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 = getControllerServiceTypesValidateBeforeCall(serviceType, serviceBundleGroup, serviceBundleArtifact, serviceBundleVersion, bundleGroupFilter, bundleArtifactFilter, typeFilter, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ControllerServiceTypesEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example 57
Project: OSchina_resources_android   File: DynamicTabFragment.java   Source Code and License 4 votes vote down vote up
public static TabPickerView.TabPickerDataManager initTabPickerManager() {
    if (mTabPickerDataManager == null) {
        mTabPickerDataManager = new TabPickerView.TabPickerDataManager() {
            @Override
            public List<SubTab> setupActiveDataSet() {
                FileReader reader = null;
                try {
                    File file = AppContext.getInstance().getFileStreamPath("sub_tab_active.json");
                    if (!file.exists()) return null;
                    reader = new FileReader(file);
                    return AppOperator.getGson().fromJson(reader,
                            new TypeToken<ArrayList<SubTab>>() {
                            }.getType());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    StreamUtil.close(reader);
                }
                return null;
            }

            @Override
            public List<SubTab> setupOriginalDataSet() {
                InputStreamReader reader = null;
                try {
                    reader = new InputStreamReader(
                            AppContext.getInstance().getAssets().open("sub_tab_original.json")
                            , "UTF-8");
                    return AppOperator.getGson().<ArrayList<SubTab>>fromJson(reader,
                            new TypeToken<ArrayList<SubTab>>() {
                            }.getType());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    StreamUtil.close(reader);
                }
                return null;
            }

            @Override
            public void restoreActiveDataSet(List<SubTab> mActiveDataSet) {
                OutputStreamWriter writer = null;
                try {
                    writer = new OutputStreamWriter(
                            AppContext.getInstance().openFileOutput(
                                    "sub_tab_active.json", Context.MODE_PRIVATE)
                            , "UTF-8");
                    AppOperator.getGson().toJson(mActiveDataSet, writer);
                    AppContext.set("TabsMask", TDevice.getVersionCode());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    StreamUtil.close(writer);
                }
            }
        };
    }
    return mTabPickerDataManager;
}
 
Example 58
Project: PI-Web-API-Client-Java-Android   File: ElementCategoryApi.java   Source Code and License 4 votes vote down vote up
/**
 * Retrieve an element category. (with HTTP information)
 *
 */
public ApiResponse<PIElementCategory> getWithHttpInfo(String webId, String selectedFields) throws ApiException {
	okhttp3.Call call = getCall(webId, selectedFields,null,null);
	Type localVarReturnType = new TypeToken<PIElementCategory>(){}.getType();
	return apiClient.execute(call, localVarReturnType);
}
 
Example 59
Project: PI-Web-API-Client-Java-Android   File: TableCategoryApi.java   Source Code and License 4 votes vote down vote up
/**
 * Retrieve the security entry associated with the table category with the specified name. (with HTTP information)
 *
 */
public ApiResponse<PISecurityEntry> getSecurityEntryByNameWithHttpInfo(String name, String webId, String selectedFields) throws ApiException {
	okhttp3.Call call = getSecurityEntryByNameCall(name, webId, selectedFields,null,null);
	Type localVarReturnType = new TypeToken<PISecurityEntry>(){}.getType();
	return apiClient.execute(call, localVarReturnType);
}
 
Example 60
Project: PI-Web-API-Client-Java-Android   File: AssetDatabaseApi.java   Source Code and License 4 votes vote down vote up
/**
 * Retrieve an Asset Database. (with HTTP information)
 *
 */
public ApiResponse<PIAssetDatabase> getWithHttpInfo(String webId, String selectedFields) throws ApiException {
	okhttp3.Call call = getCall(webId, selectedFields,null,null);
	Type localVarReturnType = new TypeToken<PIAssetDatabase>(){}.getType();
	return apiClient.execute(call, localVarReturnType);
}