Java Code Examples for com.google.gson.Gson

The following are top voted examples for showing how to use com.google.gson.Gson. 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: weixin_api   File: MpUserApi.java   Source Code and License 12 votes vote down vote up
/**
 * 创建用户标签
 * 
 * @param name
 * @return
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public TagsCreateResp apiTagsCreate(String name)
		throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
	MpAccessToken token = mpApi.apiToken();
	String path = String.format("/tags/create?access_token=%s", token.getAccessToken());
	TreeMap<String, Object> tag = new TreeMap<String, Object>();
	tag.put("name", name);

	TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
	reqMap.put("tag", tag);
	String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
	TagsCreateResp resp = new Gson().fromJson(respText, TagsCreateResp.class);
	if (mpApi.log.isInfoEnabled()) {
		mpApi.log.info(String.format("apiTagsCreate %s", new Gson().toJson(resp)));
	}
	return resp;
}
 
Example 2
Project: GitHub   File: MainActivity.java   Source Code and License 7 votes vote down vote up
private void performSerializeTests() {
    mBarChart.clear();
    mBarChart.setSections(new String[] {"Serialize 60 items", "Serialize 20 items", "Serialize 7 items", "Serialize 2 items"});

    Gson gson = new Gson();
    ObjectMapper objectMapper = new ObjectMapper();
    Moshi moshi = new Moshi.Builder().build();
    List<Serializer> serializers = new ArrayList<>();
    for (Response response : mResponsesToSerialize) {
        for (int iteration = 0; iteration < ITERATIONS; iteration++) {
            serializers.add(new GsonSerializer(mSerializeListener, response, gson));
            serializers.add(new JacksonDatabindSerializer(mSerializeListener, response, objectMapper));
            serializers.add(new LoganSquareSerializer(mSerializeListener, response));
            serializers.add(new MoshiSerializer(mSerializeListener, response, moshi));
        }
    }

    for (Serializer serializer : serializers) {
        serializer.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
    }
}
 
Example 3
Project: microbit   File: BluetoothUtils.java   Source Code and License 7 votes vote down vote up
public static BluetoothDevice getPairedDeviceMicroBit(Context context) {
    SharedPreferences pairedDevicePref = context.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
            Context.MODE_MULTI_PROCESS);
    if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
        String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
        Gson gson = new Gson();
        sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
        //Check if the microbit is still paired with our mobile
        BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
                .BLUETOOTH_SERVICE)).getAdapter();
        if(mBluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice bt : pairedDevices) {
                if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
                    return bt;
                }
            }
        }
    }
    return null;
}
 
Example 4
Project: GCSApp   File: IntroducePresenter.java   Source Code and License 6 votes vote down vote up
public void getData() {
        LoginData loginData = (LoginData) aCache.getAsObject(ACacheKey.CURRENT_ACCOUNT);
        addSubscription(apiStores.GetCsgData(loginData.getToken(), 1, 3), new ApiCallback<BaseModel<JsonArray>>(delegate.getActivity()) {
            @Override
            public void onSuccess(BaseModel<JsonArray> model) {
//                ToastUtil.showToast("请求成功" + model.getData().toString(), delegate.getActivity());
//                delegate.setData(model.getData());
                F.e(model.getData().toString());
                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                ArrayList<CSGDynamic> datas = gson.fromJson(model.getData(), new TypeToken<ArrayList<CSGDynamic>>() {
                }.getType());
                delegate.setData(datas);

            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.showToast(msg, delegate.getActivity());
            }

            @Override
            public void onFinish() {
            }
        });
    }
 
Example 5
Project: Jerkoff   File: GraphAdapterBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDeserializationWithMultipleTypes() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    new GraphAdapterBuilder().addType(Company.class).addType(Employee.class)
            .registerOn(gsonBuilder);
    Gson gson = gsonBuilder.create();

    String json = "{'0x1':{'name':'Google','employees':['0x2','0x3']},"
            + "'0x2':{'name':'Jesse','company':'0x1'},"
            + "'0x3':{'name':'Joel','company':'0x1'}}";
    Company company = gson.fromJson(json, Company.class);
    assertEquals("Google", company.name);
    Employee jesse = company.employees.get(0);
    assertEquals("Jesse", jesse.name);
    assertEquals(company, jesse.company);
    Employee joel = company.employees.get(1);
    assertEquals("Joel", joel.name);
    assertEquals(company, joel.company);
}
 
Example 6
Project: DYB   File: DMController.java   Source Code and License 6 votes vote down vote up
@PostMapping("/add")
@ResponseBody
public String danMuAdd() {
    Map<String, String> user = new HashMap<>();
    DanMu danMu = new DanMu();
    String userName = DMClient.getName();
    String userText = DMClient.getText();
    danMu.setName(userName);
    danMu.setText(userText);

    if(userName == null)
        return null;
    if (userName.equals(preName)) {
        return null;
    }
    preName = userName;
    dmRepository.save(danMu);
    Gson gson = new Gson();
    user.put("name", userName);
    user.put("text", userText);
    String gsonStr = gson.toJson(user);
    return gsonStr;
}
 
Example 7
Project: Forge   File: FileManager.java   Source Code and License 6 votes vote down vote up
/**
 * Replaces an existing Forge account in the storage
 *
 * @param context calling context
 * @param account the Forge account to replace the original with
 * @return the account added to the storage, if it's a failure returns null
 */
public static ForgeAccount replace(Context context, ForgeAccount account) {
    // Initialise GSON
    Gson gson = new Gson();
    // Get the already saved Forge accounts
    HashMap<UUID, ForgeAccount> accounts = FileManager.load(context);
    // Replace the account with the matching UUID with the new account details
    accounts.put(account.getId(), account);
    // Convert the list of Forge Accounts to a JSON string
    String jsonString = gson.toJson(new ArrayList<>(accounts.values()));
    // Internal save
    FileOutputStream outputStream;
    try {
        // Save the JSON to the file
        outputStream = context.openFileOutput(context.getString(R.string.filename_forge_accounts), Context.MODE_PRIVATE);
        outputStream.write(jsonString.getBytes());
        outputStream.close();
        return account;
    } catch (Exception e) {
        // If there is an error, log it
        Log.e(Forge.ERROR_LOG, e.getMessage());
        return null;
    }
}
 
Example 8
Project: Slide-RSS   File: HttpUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Gets a JsonObject by calling apiUrl and parsing the JSON response String. This method accepts
 * a Map that can contain custom headers to include in the request.
 *
 * @param client     The OkHTTP client to use to make the request
 * @param gson       The GSON instance to use to parse the response String
 * @param apiUrl     The URL to call to get the response from
 * @param headersMap The headers to include in the request. Can be null to not add any headers
 * @return A JsonObject representation of the API response, null when there was an error or
 * Exception thrown by the HTTP call
 */
public static JsonObject getJsonObject(final OkHttpClient client, final Gson gson,
        final String apiUrl, @Nullable final Map<String, String> headersMap) {
    if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null;
    Request.Builder builder = new Request.Builder().url(apiUrl);

    if (headersMap != null && headersMap.size() > 0) {
        // Add headers to the request if headers are available
        for (Map.Entry<String, String> entry : headersMap.entrySet()) {
            builder.addHeader(entry.getKey(), entry.getValue());
        }
    }

    Request request = builder.build();
    try {
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        ResponseBody responseBody = response.body();
        String json = responseBody.string();
        responseBody.close();
        return gson.fromJson(json, JsonObject.class);
    } catch (JsonSyntaxException | IOException e) {
        LogUtil.e(e, "Error " + apiUrl);
    }
    return null;
}
 
Example 9
Project: OfflineSampleApp   File: RemoteCommentService.java   Source Code and License 6 votes vote down vote up
public RemoteCommentService() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create();

        retrofit = new Retrofit.Builder()
                .client(httpClient)
                .baseUrl(BuildConfig.API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
 
Example 10
Project: Trackr   File: MainMenuActivity.java   Source Code and License 6 votes vote down vote up
public void loadProfileInformation() {


        NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
        View header = navigationView.getHeaderView(0);
        textView_profile_id = (TextView) header.findViewById(R.id.textViewProfileId);
        textView_profile_name = (TextView) header.findViewById(R.id.textViewProfileName);
        textView_profile_phone = (TextView) header.findViewById(R.id.textViewProfilePhone);

        Gson gson = new Gson();
        String json = sharedPreferencesProfileInformation.getString("currentUser", "");
        currentUser = gson.fromJson(json, User.class);

        textView_profile_id.setText(String.valueOf(currentUser.getId()));
        textView_profile_name.setText(currentUser.getFname() + " " + currentUser.getLname());
        textView_profile_phone.setText(currentUser.getPhone());

    }
 
Example 11
Project: TextReader   File: RxUtil.java   Source Code and License 6 votes vote down vote up
public static <T> Observable rxCreateDiskObservable(final String key, final Class<T> clazz) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            LogUtils.d("get data from disk: key==" + key);
            String json = ACache.get(ReaderApplication.getsInstance()).getAsString(key);
            LogUtils.d("get data from disk finish , json==" + json);
            if (!TextUtils.isEmpty(json)) {
                subscriber.onNext(json);
            }
            subscriber.onCompleted();
        }
    })
            .map(new Func1<String, T>() {
                @Override
                public T call(String s) {
                    return new Gson().fromJson(s, clazz);
                }
            })
            .subscribeOn(Schedulers.io());
}
 
Example 12
Project: nifi-config   File: ExtractProcessorServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void extractEmptyBranchTest() throws ApiException, IOException, URISyntaxException {
    List<String> branch = Arrays.asList("root", "elt1");
    File temp = File.createTempFile("tempfile", ".tmp");

    ProcessGroupFlowEntity response = TestUtils.createProcessGroupFlowEntity("idComponent", "nameComponent");

    when(processGroupServiceMock.changeDirectory(branch)).thenReturn(Optional.of(response));
    when(flowapiMock.getControllerServicesFromGroup("idComponent")).thenReturn(new ControllerServicesEntity());

    extractService.extractByBranch(branch, temp.getAbsolutePath());

    //evaluate response
    Gson gson = new Gson();
    try (Reader reader = new InputStreamReader(new FileInputStream(temp), "UTF-8")) {
        GroupProcessorsEntity result = gson.fromJson(reader, GroupProcessorsEntity.class);
        assertTrue(result.getProcessors().isEmpty());
        assertTrue(result.getGroupProcessorsEntity().isEmpty());
        assertEquals("nameComponent", result.getName());
    }


}
 
Example 13
Project: DaiGo   File: Order.java   Source Code and License 6 votes vote down vote up
@Override
public void convertJSON(String json) {
    Gson gson = new Gson();
    OrderDAO order = gson.fromJson(json, OrderDAO.class);
    this.orderId = order.getOrderId();
    this.orderSender = order.getOrderSender();
    this.orderReceiver = order.getOrderReceiver();
    this.acceptTime = order.getAcceptTime();
    this.title = order.getTitle();
    this.publicDetails = order.getPublicDetails();
    this.privateDetails = order.getPrivateDetails();
    this.requestTime = order.getRequestTime();
    this.orderState = order.getOrderState();
    this.price = order.getPrice();
    this.contact = order.getContact();
    this.completeTime = order.getCompleteTime();
}
 
Example 14
Project: subreddify-android   File: PollerModule.java   Source Code and License 6 votes vote down vote up
@Provides
public RedditResource provideRedditResource() {
    Type redditPostListType = new TypeToken<List<RedditPost>>() {}.getType();

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(redditPostListType, new RedditPostsDeserializer())
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://www.reddit.com/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    return retrofit.create(RedditResource.class);
}
 
Example 15
Project: Roblox4j   File: BasicRobloxian.java   Source Code and License 6 votes vote down vote up
@Override
public Badge[] getBadges() throws Exception {
    List<Badge> badges = new ArrayList<>();
    String url = "https://www.roblox" +
            ".com/users/inventory/list-json?assetTypeId=21&cursor=&itemsPerPage=100" +
            "&pageNumber=1&sortOrder=Desc&userId=" + this.getUserId();
    BadgesResponse response = new Gson().fromJson(Jsoup.connect(url).ignoreContentType(true)
            .get().body().text(), BadgesResponse.class);
    for (BadgesResponse.BadgesData.PlayerBadgeData item : response.Data.Items) {
        badges.add(new Badge(item.Item.AssetId, item.Item.Name));
    }
    // next page
    if (response.Data.nextPageCursor != null) {
        badges.addAll(recursiveBadgeRetrieve(response));
    }
    return badges.toArray(new Badge[badges.size()]);
}
 
Example 16
Project: Quicksend   File: TemplateStorage.java   Source Code and License 6 votes vote down vote up
public List<Template> getAll(Context context) {
    SharedPreferences settings;
    List<Template> templates;

    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

    if (settings.contains(DATA)) {
        String json = settings.getString(DATA, null);
        Gson gson = new Gson();
        Template[] templates1 = gson.fromJson(json, Template[].class);

        templates = Arrays.asList(templates1);
    } else {
        return null;
    }

    return templates;
}
 
Example 17
Project: starcraft-2-build-player   File: JsonBuildService.java   Source Code and License 6 votes vote down vote up
/**
 * Parses a JSON input stream, returning a list of Build objects.
 */
public static ArrayList<Build> readBuildsFromJsonInputStream(InputStream input) throws IOException, JsonSyntaxException {
    Gson gson = new GsonBuilder()
            .setDateFormat(DbAdapter.DATE_FORMAT.toPattern())	// use ISO-8601 date format
            .create();
    String bufferString = "";
    int size = input.available();
    byte[] buffer = new byte[size];
    input.read(buffer);
    input.close();
    bufferString = new String(buffer);

    Build[] builds = gson.fromJson(bufferString, Build[].class);
    ArrayList<Build> result = new ArrayList<Build>(Arrays.asList(builds));
    return result;
}
 
Example 18
Project: sbc-qsystem   File: NetCommander.java   Source Code and License 6 votes vote down vote up
/**
 * Получение недельной таблици с данными для предварительной записи.
 *
 * @param netProperty netProperty параметры соединения с сервером.
 * @param serviceId услуга, в которую пытаемся встать.
 * @param date первый день недели за которую нужны данные.
 * @param advancedCustomer ID авторизованного кастомера
 * @return класс с параметрами и списком времен
 */
public static RpcGetGridOfWeek.GridAndParams getGridOfWeek(INetProperty netProperty,
    long serviceId, Date date, long advancedCustomer) {
    QLog.l().logger().info("Получить таблицу");
    // загрузим ответ
    final CmdParams params = new CmdParams();
    params.serviceId = serviceId;
    params.date = date.getTime();
    params.customerId = advancedCustomer;
    final String res;
    try {
        res = send(netProperty, Uses.TASK_GET_GRID_OF_WEEK, params);
    } catch (QException e) {// вывод исключений
        throw new ClientException(Locales.locMes("command_error2"), e);
    }
    final Gson gson = GsonPool.getInstance().borrowGson();
    final RpcGetGridOfWeek rpc;
    try {
        rpc = gson.fromJson(res, RpcGetGridOfWeek.class);
    } catch (JsonSyntaxException ex) {
        throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
    } finally {
        GsonPool.getInstance().returnGson(gson);
    }
    return rpc.getResult();
}
 
Example 19
Project: Android-Router   File: ValueParserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void check_Json_Map() throws ValueParseException {
    A a = ObjGenerator.getA();
    String json = new Gson().toJson(a);

    Object parse = ValueParser.parse(json, Map.class.getCanonicalName());
    assertTrue(parse instanceof Map);
}
 
Example 20
Project: spark-cassandra-poc   File: SparkFileLoaderUtils.java   Source Code and License 5 votes vote down vote up
private JavaRDD<VideoViewEvent> prepareVideoRDD(String localFilePath, SparkContext sparkContext) {
	JavaRDD<VideoViewEvent> videoEventRDD = sparkContext.textFile(localFilePath, 2).toJavaRDD()
			.map(new Function<String, VideoViewEvent>() {
				private static final long serialVersionUID = 1L;

				@Override
				public VideoViewEvent call(String line) throws Exception {
					return new Gson().fromJson(line, VideoViewEvent.class);
				}
			});
	return videoEventRDD;
}
 
Example 21
Project: full-javaee-app   File: Candidates.java   Source Code and License 5 votes vote down vote up
public void setAccountOrigin(AccountOrigin accountOrigin) {
    if (accountOrigin != null) {
        Gson gson = new Gson();
        String json = gson.toJson(accountOrigin);
        setAccountOrigin(json);
    }
}
 
Example 22
Project: mapbox-events-android   File: TelemetryClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void sendsTheCorrectBodyPostingAnEvent() throws Exception {
  Context mockedContext = mock(Context.class, RETURNS_DEEP_STUBS);
  MapboxTelemetry.applicationContext = mockedContext;
  TelemetryClient telemetryClient = obtainATelemetryClient("anyAccessToken", "anyUserAgent");
  List<Event> theEvent = obtainAnEvent();
  Callback mockedCallback = mock(Callback.class);
  enqueueMockResponse();

  telemetryClient.sendEvents(theEvent, mockedCallback);

  ArrayList<Event> events = new ArrayList<>(1);
  events.add(theEvent.get(0));
  assertRequestBodyEquals(new Gson().toJson(events));
}
 
Example 23
Project: daf-cacher   File: ApiServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPlotList() throws IOException {
    final HttpResponse response = Request.Get("http://localhost:4567/plot/")
            .execute()
            .returnResponse();
    assertTrue(response.getStatusLine().getStatusCode() == 200);
    final String body = EntityUtils.toString(response.getEntity());


    final Gson gson = new GsonBuilder().create();
    List<HTTPClient.Card> cards = gson.fromJson(body, new TypeToken<List<HTTPClient.Card>>() {
    }.getType());
    assertTrue(!cards.isEmpty());
}
 
Example 24
Project: GoalsAndHabits   File: MainActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Saves the habits and profile to local storage, as well
 * as attempting to save the data to the elasticsearch server.
 */
private void saveData(){
    if (habits.size()>0) {
        ElasticSearchController.AddHabitsTask addHabitsTask
                = new ElasticSearchController.AddHabitsTask();
        Habit[] habitArr = habits.toArray(new Habit[habits.size()]);
        addHabitsTask.execute(habitArr);
    }
    if (profile != null) {
        ElasticSearchController.UpdateProfileTask updateProfileTask
                = new ElasticSearchController.UpdateProfileTask();
        updateProfileTask.execute(profile);
    }
    //Save to local storage:
    try {
        FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));

        Gson gson = new Gson();
        gson.toJson(habits, out);
        out.newLine();
        out.write("profile");
        out.newLine();
        gson.toJson(profile, out);
        out.flush();
        fos.close();
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
 
Example 25
Project: SocEltech   File: ListStringConverter.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> convertToEntityProperty(String databaseValue) {
	if (databaseValue == null) {
		return null;
	} else {
		return new Gson().fromJson(databaseValue, new TypeToken<List<String>>() {}.getType());
	}
}
 
Example 26
Project: bullet-core   File: FieldTypeAdapterFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDeserializationFail() {
    Gson gson = getGSON(getFactory(t -> t.getAsJsonObject().get("bar").getAsString(),
                                   asList("typeA", "A"),
                                   asList("typeB", "B")));
    Base deserialized = gson.fromJson(makeJSON(1, "garbage", "a"), Base.class);
    Assert.assertNull(deserialized);
}
 
Example 27
Project: SlotNSlot_Android   File: StorageUtil.java   Source Code and License 5 votes vote down vote up
public static void save(String identifier, String key, Object object) {
    Gson gson = new Gson();
    SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = pref.edit();
    editor.putString(key, gson.toJson(object));
    editor.apply();
}
 
Example 28
Project: https-github.com-hyb1996-NoRootScriptDroid   File: UpdateChecker.java   Source Code and License 5 votes vote down vote up
private UpdateInfo parse(String json) {
    Gson gson = new Gson();
    Type type = new TypeToken<UpdateInfo>() {
    }.getType();
    UpdateInfo result = gson.fromJson(json, type);
    Log.i(LOG_TAG, result.toString());
    return result;
}
 
Example 29
Project: Parallator   File: MainConfig.java   Source Code and License 5 votes vote down vote up
public static MainConfig getMainConfig() {
    File workingDirectory = new File(System.getProperty("user.dir"));
    File file = new File(workingDirectory, ".config");
    String text = Helper.getTextFromFile(file, Helper.UTF_8);
    if (text == null) {
        MainConfig config = new MainConfig();
        config.save();
        return config;
    }
    return new Gson().fromJson(text, MainConfig.class);
}
 
Example 30
Project: DeepImagePreview-Project   File: TextClassifierTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGivenSampleDataWhenPredictThenCorrectResultReturned() throws Exception {

    // Load test data
    Type type = new TypeToken<ArrayList<FoodTestEntry>>() {
    }.getType();
    Resources resources = InstrumentationRegistry.getContext().getResources();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resources.getAssets().open("sample_classifier_test_data.json")));
    ArrayList<FoodTestEntry> foodTestEntries = new Gson().fromJson(bufferedReader, type);

    int failed = 0;

    // Predict and test
    for (FoodTestEntry foodTestEntry : foodTestEntries) {
        String textToPredict = foodTestEntry.getText();
        boolean isPredictionCorrect = mCut.isFoodRelated(textToPredict) == foodTestEntry.isFood();

        if (isPredictionCorrect) {
            System.out.println("SUCCESS Predicted [" + textToPredict + "] correctly!");
        } else {
            failed++;
            System.out.println("FAILED Predicted [" + textToPredict + "], expecting [" + foodTestEntry.isFood() + "] but was [" + mCut
                    .isFoodRelated(textToPredict) + "]");
        }
    }

    if (failed > 0) {

        int totalTestSize = foodTestEntries.size();
        float failedPerc = (float) failed * totalTestSize / 100f;

        fail(failed + " out of " + totalTestSize + " failed [" + failedPerc + "%]");
    }
}
 
Example 31
Project: xifan   File: SettingsActivity.java   Source Code and License 5 votes vote down vote up
private void checkUpdate() {
    FIR.checkForUpdateInFIR(Constants.Fir.FIR_TOKEN, new VersionCheckCallback() {
        @Override
        public void onSuccess(String versionJson) {
            AppVersionInfoRes appVersionInfo =
                    new Gson().fromJson(versionJson, AppVersionInfoRes.class);
            String firVersion = appVersionInfo.getVersionShort().replaceAll("[.]", "");
            String currentVersion = BuildConfig.VERSION_NAME.replaceAll("[.]", "");
            if (Integer.parseInt(firVersion) > Integer.parseInt(currentVersion)) {
                showAppUpdateDialog(appVersionInfo);
            } else {
                UIUtils.showOkDialog(getActivity(), getString(R.string.title_check_upate),
                        getString(R.string.text_not_need_update));
            }
        }

        @Override
        public void onFail(Exception exception) {
            UIUtils.showToast(getActivity(), getString(R.string.text_check_update_fail));
        }

        @Override
        public void onStart() {
            UIUtils.showToast(getActivity(), getString(R.string.text_checking_update));
        }

        @Override
        public void onFinish() {
        }
    });
}
 
Example 32
Project: BIMplatform   File: JsonGeometryQueryAction.java   Source Code and License 5 votes vote down vote up
public void sendGeometryParam(Double zoom, Vector3f middle) {
	if (webSocketSession == null || !webSocketSession.isOpen()) {
		return;
	}
	ResultUtil result = new ResultUtil();
	result.setKeyValue("zoom", zoom);
	result.setKeyValue("middle", middle);
	result.setSuccess(true);
	Gson gson = new Gson();
	String jsonStr = gson.toJson(result.getResult());
	TextMessage message = new TextMessage(jsonStr);
	try {
		webSocketSession.sendMessage(message);
	} catch (Exception e) {
		try {
			webSocketSession.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		e.printStackTrace();
	} 
}
 
Example 33
Project: Mvp-Retrofit-Rxjava-Rxbus   File: HttpService.java   Source Code and License 5 votes vote down vote up
public static void requsetTest(){
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://www.cfycp.com/")
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// 添加RxJava2的适配器支持
            .build();
    Api api =  retrofit.create(Api.class);
    api.getText()
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<AllBankListBean>>() {
                @Override
                public void onSubscribe(Subscription s) {
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(List<AllBankListBean> acticleBean) {
                    Log.i("HttpService",acticleBean.get(0).getReturnCode());
                }

                @Override
                public void onError(Throwable t) {
                    Log.e("HttpService",t.getMessage());
                }

                @Override
                public void onComplete() {
                    Log.e("HttpService","onComplete");
                }
            });
}
 
Example 34
Project: NoRiskNoFun   File: AssetLoaderMapTests.java   Source Code and License 5 votes vote down vote up
@Test
public void loadingMapWithoutVerticesGivesNull() {

    // given
    AssetLoaderMap target = new AssetLoaderMap();
    GameMap map = createGameMap();

    // when
    map.vertices.clear();
    Asset obtained = target.load(new ByteArrayInputStream(new Gson().toJson(map).getBytes()));

    // then
    assertThat(obtained, is(nullValue()));
}
 
Example 35
Project: react-native-android-library-humaniq-api   File: WalletMockWebTest.java   Source Code and License 5 votes vote down vote up
@Test public void testGetBalance() throws IOException, InterruptedException {
  server = new MockWebServer();
  server.enqueue(new MockResponse().setBody("{"
      + "    \"success\": true,"
      + "    \"data\": {"
      + "        \"token\": {"
      + "            \"currency\": \"HMQ\","
      + "            \"amount\": 190.6"
      + "        },"
      + "        \"default\": {"
      + "            \"currency\": \"USD\","
      + "            \"amount\": 27.7323"
      + "        },"
      + "        \"local\": {"
      + "            \"currency\": \"SOS\","
      + "            \"amount\": 15141.841623783"
      + "        }"
      + "    }"
      + "}"));

  URL url = server.url("/").url();
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestProperty("Accept-Language", "en-US");
  InputStream in = connection.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
  Balance balance = new Gson().fromJson(reader.readLine(), Balance.class);

  assertTrue(balance != null);

  RecordedRequest request = server.takeRequest();
  assertEquals("GET / HTTP/1.1", request.getRequestLine());
  assertEquals("en-US", request.getHeader("Accept-Language"));
  //System.out.println(server.takeRequest().);
}
 
Example 36
Project: retrofit2-synchronous-adapter   File: SynchronousGsonConverterFactoryTest.java   Source Code and License 5 votes vote down vote up
@Before public void setUp() {
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(AnInterface.class, new AnInterfaceAdapter())
      .setLenient()
      .create();
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(GsonConverterFactory.create(gson))
      .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter
      .build();
  service = retrofit.create(Service.class);
}
 
Example 37
Project: scmt-server   File: DeskClient.java   Source Code and License 5 votes vote down vote up
private Gson createGson() {
    return new GsonBuilder()
            .registerTypeAdapter(Date.class, new ISO8601DateAdapter())
            .registerTypeAdapter(CaseLock.class, CaseLock.TYPE_ADAPTER)
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();
}
 
Example 38
Project: Byter   File: PerformanceTimer.java   Source Code and License 5 votes vote down vote up
/**
 * Write the evaluated data to a file.
 * @param outFile file to write to
 * @param map evaluated map with data from measurements.
 */
public void writeEvaluationToFile(final File outFile, final Map<String, Float> map){
    final GsonBuilder gsonBuilder = new GsonBuilder();
    //register bigDecimal typer for no scientific value printing
    gsonBuilder.registerTypeAdapter(Float.class,  new JsonSerializer<Float>() {
        @Override
        public JsonElement serialize(final Float src, final Type typeOfSrc, final JsonSerializationContext context) {
            try{
                final BigDecimal bigValue = BigDecimal.valueOf(src);
                return new JsonPrimitive(bigValue.toPlainString());
            }catch (final NumberFormatException nfe){
                log.log(Level.INFO,map.toString());
                log.log(Level.WARNING, "NumberFormatException during serialize. Number: " + src);
                return new JsonPrimitive(src);
            }
        }
    });
    final Gson gson = gsonBuilder.setPrettyPrinting().create();
    final String json = gson.toJson(map);
    //write file to disc
    try(
        final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile))
    ){
        outputStream.write(json.getBytes());
        outputStream.flush();
    } catch (IOException e) {
        log.log(Level.WARNING,"IO Exception writing evaluation to disc",e);
    }
}
 
Example 39
Project: YouTube-Thumbnail-View   File: OembedVideoInfoDownloader.java   Source Code and License 5 votes vote down vote up
@Override
@NonNull
public VideoInfo download(@NonNull String url, int minThumbnailWidth) throws IOException {
   final String encodedUrl = URLEncoder.encode(url, "UTF-8");
   final String ombedUrl = "http://www.youtube.com/oembed?url=" + encodedUrl + "&format=json";

   final OkHttpClient client = new OkHttpClient();
   final Request request = new Request.Builder()
         .url(ombedUrl)
         .build();

   final Response response = client.newCall(request).execute();
   try {
      if (!response.isSuccessful()) {
         throw new IOException("Unexpected code " + response);
      }


      final Gson gson = new Gson();
      final OembedResponse result = gson.fromJson(response.body().charStream(), OembedResponse.class);

      if (result.title == null && result.thumbnail_url == null) {
         throw new IOException("Invalid youtube oembed response.");
      }

      return new VideoInfo(result.title, result.thumbnail_url, 0);
   }
   finally {
      response.close();
   }
}
 
Example 40
Project: TalentZzzz   File: Config.java   Source Code and License 5 votes vote down vote up
public static void load() {
    File yml = new File(Talent.instance.getDataFolder(), "config.yml");
    if (!yml.exists())
        Talent.instance.saveResource("config.yml", true);
    try {
        Map map = (Map) new Yaml().load(Files.toString(yml, Charset.forName("utf-8")));
        instance = new Gson().fromJson(new Gson().toJson(map), Config.class);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 41
Project: li-android-sdk-core   File: LiAuthRestClient.java   Source Code and License 5 votes vote down vote up
/**
 * Makes Sync call to fetch fresh Access token from Refresh Token.
 * @param refreshTokenRequest {@link LiRefreshTokenRequest}
 * @return LiBaseResponse {@link LiBaseResponse}
 * @throws LiRestResponseException {@link LiRestResponseException}
 */
public LiBaseResponse refreshTokenSync(@NonNull Context context, @NonNull final LiRefreshTokenRequest refreshTokenRequest) throws LiRestResponseException {

    Gson gson = new Gson();

    Request.Builder builder = new Request.Builder()
            .url(HttpUrl.get(URI.create(String.valueOf(refreshTokenRequest.getUri()))))
            .method(LiBaseRestRequest.RestMethod.POST.name(), RequestBody.create(MediaType.parse("application/json; charset=utf-8"), gson.toJson(refreshTokenRequest)));
    addLSIRequestHeaders(context, builder);
    builder.addHeader("client-id", refreshTokenRequest.getClientId());
    Request request = builder.build();

    OkHttpClient client = getOkHttpClient();

    Response response = null;

    try {
        response = getCall(request, client).execute();
        if (response != null) {
            if (response.code() == LiCoreSDKConstants.HTTP_CODE_SUCCESSFUL && response.body() != null) {
                return getLiBaseResponseFromResponse(response);
            } else {
                throw new LiRestResponseException(response.code(), "Error refreshTokenSync", response.code());
            }
        } else {
            throw new LiRestResponseException(LiCoreSDKConstants.HTTP_CODE_SERVER_ERROR,
                    "Error refreshTokenSync", LiCoreSDKConstants.HTTP_CODE_SERVER_ERROR);
        }
    } catch (Exception e) {
        Log.e("LiAuthRestClient", "Error making rest call", e);
        throw LiRestResponseException.networkError(e.getMessage());
    }
}
 
Example 42
Project: pagerank   File: PageRank.java   Source Code and License 5 votes vote down vote up
/**
 * 初始化,将球队信息和比赛结果读取到内存
 */

private void init(){
    try {
        BufferedReader teamReader = new BufferedReader(new FileReader(new File(this.teamInfopath)));
        Gson gson = new Gson();
        JsonArray jsonArray = gson.fromJson(teamReader.readLine(), JsonArray.class);
        teamReader.close();

        this.teamMap = new HashMap<String, TeamItem>();
        for (JsonElement jsonElement : jsonArray){
            TeamItem teamItem = new TeamItem();
            teamItem.setName(jsonElement.getAsJsonObject().get("team").getAsString());
            this.teamMap.put(teamItem.getName(), teamItem);
        }

        BufferedReader matchReader = new BufferedReader(new FileReader(new File(this.matchResultPath)));
        String line = "";

        this.matchResultList = new ArrayList<MatchResult>();
        while ((line = matchReader.readLine()) != null){
            MatchResult matchResult = new MatchResult(line);
            this.matchResultList.add(matchResult);
        }
        matchReader.close();
    }catch (IOException e){
        System.out.println("读取失败");
        System.exit(1);
    }

}
 
Example 43
Project: okuki   File: NetworkModule.java   Source Code and License 5 votes vote down vote up
public NetworkModule() {
    final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
    final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
    bind(OkHttpClient.class).toInstance(client);

    final Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();
    bind(Gson.class).toInstance(gson);

}
 
Example 44
Project: xmall   File: QiniuUtil.java   Source Code and License 5 votes vote down vote up
public static String qiniuUpload(String filePath){

        //构造一个带指定Zone对象的配置类 zone2华南
        Configuration cfg = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager(cfg);

        String localFilePath = filePath;
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return origin+putRet.key;
        }catch(QiniuException ex){
            Response r = ex.response;
            log.warn(r.toString());
            try {
                log.warn(r.bodyString());
                return r.bodyString();
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return null;
    }
 
Example 45
Project: boohee_v5.6   File: Milestone.java   Source Code and License 5 votes vote down vote up
public static ArrayList<Milestone> parseLists(JSONObject object) {
    if (!object.has("achieved_milestones")) {
        return null;
    }
    return (ArrayList) new Gson().fromJson(object.optString("achieved_milestones"), new
            TypeToken<ArrayList<Milestone>>() {
    }.getType());
}
 
Example 46
Project: Hub   File: WellManager.java   Source Code and License 5 votes vote down vote up
public void finalizePearlCrafting(Player player, UUID craftingPearlUUID)
{
    Jedis jedis = SamaGamesAPI.get().getBungeeResource();

    if (jedis == null)
        return;

    CraftingPearl craftingPearl = null;

    if (jedis.exists("crafting-pearls:" + player.getUniqueId().toString() + ":" + craftingPearlUUID.toString()))
        craftingPearl = new Gson().fromJson(jedis.get("crafting-pearls:" + player.getUniqueId().toString() + ":" + craftingPearlUUID.toString()), CraftingPearl.class);

    if (craftingPearl == null)
    {
        jedis.close();
        return;
    }

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, 7);

    Pearl craftedPearl = new Pearl(craftingPearl.getUUID(), craftingPearl.getStars(), calendar.getTime().getTime());
    this.addPearlToPlayer(player, craftedPearl);

    jedis.del("crafting-pearls:" + player.getUniqueId().toString() + ":" + craftingPearlUUID.toString());

    jedis.close();

    this.hub.getInteractionManager().getGraouManager().update(player);
}
 
Example 47
Project: xlight_android_native   File: EventsDelegate.java   Source Code and License 5 votes vote down vote up
private EventReader(ParticleEventHandler handler, ExecutorService executor, Gson gson,
                    Uri uri, SseEventSourceFactory factory) {
    this.handler = handler;
    this.executor = executor;
    this.gson = gson;
    try {
        sseEventSource = factory.createEventSource(URI.create(uri.toString()));
    } catch (URISyntaxException e) {
        // I don't like throwing exceptions in constructors, but this URI shouldn't be in
        // the wrong format...
        throw new RuntimeException(e);
    }
}
 
Example 48
Project: sctalk   File: MixMessage.java   Source Code and License 5 votes vote down vote up
public static MixMessage parseFromDB(MessageEntity entity) throws JSONException {
    if(entity.getDisplayType() != DBConstant.SHOW_MIX_TEXT){
        throw new RuntimeException("#MixMessage# parseFromDB,not SHOW_MIX_TEXT");
    }
    Gson gson = new GsonBuilder().create();
    MixMessage mixMessage = new MixMessage(entity);
    List<MessageEntity> msgList = new ArrayList<>();
    JSONArray jsonArray = new JSONArray(entity.getContent());

    for (int i = 0, length = jsonArray.length(); i < length; i++) {
        JSONObject jsonOb = (JSONObject) jsonArray.opt(i);
        int displayType = jsonOb.getInt("displayType");
        String jsonMessage = jsonOb.toString();
        switch (displayType){
            case DBConstant.SHOW_ORIGIN_TEXT_TYPE:{
                TextMessage textMessage = gson.fromJson(jsonMessage,TextMessage.class);
                textMessage.setSessionKey(entity.getSessionKey());
                msgList.add(textMessage);
            }break;

            case DBConstant.SHOW_IMAGE_TYPE:
                ImageMessage imageMessage = gson.fromJson(jsonMessage,ImageMessage.class);
                imageMessage.setSessionKey(entity.getSessionKey());
                msgList.add(imageMessage);
                break;
        }
    }
    mixMessage.setMsgList(msgList);
    return mixMessage;
}
 
Example 49
Project: data-mediator   File: GsonSinceUntilAnnotationsExample.java   Source Code and License 5 votes vote down vote up
private static void testList() {
    TestGsonBean tl = newTestGsonBean();

    Gson gson = new Gson();
    String json = gson.toJson(tl);
    GsonTest.log(json);

    TestGsonBean bean = gson.fromJson(json, TestGsonBean.class);
    GsonTest.log(bean);
    //========================= above ok ========================
}
 
Example 50
Project: my-spring-boot-project   File: OAuth2Filter.java   Source Code and License 5 votes vote down vote up
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    //获取请求token,如果token不存在,直接返回401
    String token = getRequestToken((HttpServletRequest) request);
    if (StringUtils.isBlank(token)) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String json = new Gson().toJson(Result.error(HttpStatus.SC_UNAUTHORIZED, "invalid token"));
        httpResponse.getWriter().print(json);

        return false;
    }

    return executeLogin(request, response);
}
 
Example 51
Project: ImageClassify   File: ImageUploadController.java   Source Code and License 5 votes vote down vote up
/**
 * 管理员获取志愿者上传的贡献压缩包
 * 
 * @param start
 * @param page_num
 * @param response
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/admin/getcontributeuploadziplist", method = RequestMethod.POST)
public void getUploadZipListByUserList(@RequestParam("start") String start,
		@RequestParam("page_num") String page_num, HttpServletResponse response, HttpServletRequest request)
		throws IOException {
	// 设置编码格式
	response.setCharacterEncoding("UTF-8");
	request.setCharacterEncoding("UTF-8");

	String json = "";
	Gson gson = new Gson();
	PrintWriter out = response.getWriter();
	SplitObject<ContributeImgListOfAll> splitObject = new SplitObject<ContributeImgListOfAll>();
	List<ContributeImgListOfAll> cImgs = new ArrayList<ContributeImgListOfAll>();
	// 分页查询志愿者上传贡献的压缩包列表
	cImgs = contributeService.getContributeOfAllByUser(new Integer(start).intValue(),
			new Integer(page_num).intValue());
	splitObject.setList(cImgs);
	// 计算数据的页数
	int num = contributeService.getAmountContributeOfAllByUser();
	if (num % Constant.DEVI_NUM == 0) {
		splitObject.setPages_num(num / Constant.DEVI_NUM);
	} else {
		splitObject.setPages_num(num / Constant.DEVI_NUM + 1);
	}

	// 查询有记录
	Message<SplitObject<ContributeImgListOfAll>> message = new Message<SplitObject<ContributeImgListOfAll>>("200",
			"", splitObject);
	json = gson.toJson(message);
	out.print(json);
}
 
Example 52
Project: FacetExtract   File: TxtToObject.java   Source Code and License 5 votes vote down vote up
public static void writeObjToTxt(Topic topic, String txtPath) {
	Gson gson = new GsonBuilder().setPrettyPrinting().create();
	try {
		FileUtils.write(new File(txtPath), gson.toJson(topic), "utf-8");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 53
Project: EMC-Marketplace-Mod   File: API.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an array of all mods
 * 
 * @return
 */
public static Mod[] fetchMods() {
	try {
		Mod[] mods = new Gson().fromJson(fetchEndpoint(Types.ListProducts, null), Mod[].class);
		for (Mod mod : mods) {
			mod.init();
		}
		return mods;
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return new Mod[0];
}
 
Example 54
Project: jaer   File: TimestampCalibrator.java   Source Code and License 5 votes vote down vote up
public void doLoadCalibration() {
        JFileChooser c = new JFileChooser(lastCalibrationFile);
        c.setDialogTitle("choose timestamp calibration JSON file");
//        c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int ret = c.showOpenDialog(chip.getAeViewer().getFilterFrame());
        if (ret != JFileChooser.APPROVE_OPTION) {
            return;
        }
        lastCalibrationFile = c.getSelectedFile().getPath();
        putString("lastCalibrationFile", lastCalibrationFile);
        String fn = c.getSelectedFile().getPath();
        if (!fn.toLowerCase().endsWith(JSON_EXT)) {
            fn = fn + JSON_EXT;
        }
        try (Reader reader = new FileReader(fn)) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            TimestampCalibration tsc = gson.fromJson(reader, TimestampCalibration.class);
            log.info("read calibration from " + fn +"\n "+tsc.toString());
            if (!(chip.getAeViewer().getPlayMode() == PlayMode.LIVE) || chip.getHardwareInterface() == null) {
                JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Device not running live or no hardware interface, cannot check if calibration is valid for this device");
                return;
            }
            setPpmTimestampTooFastError(tsc.ppmTimestampTooFastError);
            USBInterface usbInterface = (USBInterface) chip.getHardwareInterface();
            if (usbInterface.getVID() != tsc.vid
                    || usbInterface.getPID() != tsc.pid
                    || usbInterface.getDID() != tsc.did) {
                JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Current device VID/PID/DID does not match that in saved calibration");
            }

        } catch (Exception e) {
            log.warning(e.toString());

        }

    }
 
Example 55
Project: coinpaymentsnet-java-api   File: CoinPaymentsAPI.java   Source Code and License 5 votes vote down vote up
/**
 * Calls the API
 * 
 * @param cmd
 * @return the answer from the
 */
public JsonObject call(String cmd)
{

	// Copy the current map to
	Map<String, String> req = new HashMap<>();
	req.putAll(params);
	params.clear();

	// Set the API command and required fields
	req.put("version", "1");
	req.put("cmd", cmd);
	req.put("key", this.public_key);
	req.put("format", "json");

	try {
		// Generate the query string
		String post_data = urlEncodeUTF8(req);

		// Calculate the HMAC
		String hmac = HmacUtils.hmacSha512Hex(this.private_key, post_data);
		URL obj = new URL("https://www.coinpayments.net/api.php");
		HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

		// Set the request headers
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", "Mozilla/5.0");
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
		con.setRequestProperty("HMAC", hmac);

		// Send post request
		con.setDoOutput(true);
		DataOutputStream wr = new DataOutputStream(con.getOutputStream());
		wr.writeBytes(post_data);
		wr.flush();
		wr.close();

		// Wait for the resüonse code
		int responseCode = con.getResponseCode();
		logger.debug("Sending 'POST' request to URL : https://www.coinpayments.net/api.php");
		logger.debug("Post parameters : " + post_data);
		logger.debug("Response Code : " + responseCode);

		// Read the full response
		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// Parse the JSON response with GSON
		JsonParser jsonParser = new JsonParser();
		JsonElement jsonTree = jsonParser.parse(response.toString());
		JsonObject jsonObject = jsonTree.getAsJsonObject();

		// If there is an error - throw an Exception
		if (jsonObject.get("error").getAsString().equals("ok") == false) {
			throw new IllegalStateException(jsonObject.get("error").getAsString());
		}

		// Otherwise return the result object
		Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
		String prettyJson = gson.toJson(jsonObject);
		logger.debug(prettyJson);

		return jsonObject.getAsJsonObject("result");
	}
	catch (Exception e) {
		logger.error("Exception occured: " + e.getMessage());
		throw new CoinpaymentsApiCallException(e.getMessage());
	}
}
 
Example 56
Project: DAPNETApp   File: PostCallActivity.java   Source Code and License 5 votes vote down vote up
private void saveData(CallSignResource[] input){
    SharedPreferences sharedPref = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = sharedPref.edit();
    Gson gson = new Gson();
    String json = gson.toJson(input);
    prefsEditor.putString("callsigns", json);
    prefsEditor.apply();
}
 
Example 57
Project: Webcheckers   File: PostValidateMoveRouteTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test that PostValidateMove will return Message object with proper information when move is valid
 */
@Test
public void valid_move_test() {
    // Arrange the test scenario: The session holds player
    Player player = PlayerLobby.getPlayer("player");
    when(session.attribute(PostSigninRoute.PLAYER_KEY)).thenReturn(player);
    // There is a valid move to check
    when(request.body()).thenReturn("{\"start\":{\"row\":5,\"cell\":2},\"end\":{\"row\":4,\"cell\":3}}");
    final Response response = mock(Response.class);

    gson = new Gson();
    // Invoke the test
    Message message = gson.fromJson((String) CuT.handle(request, response), Message.class);

    // Analyze the results:
    // type is a non-null Type
    final Message.Type type = message.getType();
    assertNotNull(type);
    assertTrue(type instanceof Message.Type);
    // text is a non-null String
    final String text = message.getText();
    assertNotNull(text);
    assertTrue(text instanceof String);
    // model contains all necessary View-Model data
    assertEquals(Message.Type.info, type);
    assertEquals("Valid move", text);
}
 
Example 58
Project: MyRepository   File: JsonUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 把一个map变成json字符串
 * @param map
 * @return
 */
public static String parseMapToJson(Map<?, ?> map) {
    try {
        Gson gson = new Gson();
        return gson.toJson(map);
    } catch (Exception e) {
        LogUtils.e("JSON解析错误:", e.getMessage());
        e.printStackTrace();
    }
    return null;
}
 
Example 59
Project: odoo-work   File: TypeAdapters.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Class<? super T> rawType = typeToken.getRawType();
  if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) {
    return null;
  }
  if (!rawType.isEnum()) {
    rawType = rawType.getSuperclass(); // handle anonymous subclasses
  }
  return (TypeAdapter<T>) new EnumTypeAdapter(rawType);
}
 
Example 60
Project: mapbox-navigation-android   File: RouteStepProgressTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws IOException {
  Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(DirectionsAdapterFactory.create()).create();
  String body = loadJsonFixture(PRECISION_6);
  response = gson.fromJson(body, DirectionsResponse.class);
  route = response.routes().get(0);
  firstStep = route.legs().get(0).steps().get(0);
  firstLeg = route.legs().get(0);
}