Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

In this page you can find the example usage for com.google.gson JsonParser JsonParser.

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json.JsonMapperImpl.java

License:Apache License

@Override
public <K> K deserialize(String serializedObject, Class<K> targetClass) {
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = (JsonObject) parser.parse(serializedObject);
    K object = ReflectionUtil.createInstance(targetClass);
    ObjectNavigator objectNavigator = new ObjectNavigatorImpl(typeAdapterFactory);
    Visitor visitor = new JsonDeserializationVisitor(jsonObject, object);
    objectNavigator.navigate(object, visitor);
    return object;
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseListTypeAdapter.java

License:Apache License

@Override
public List<?> deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonListTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseMapTypeAdapter.java

License:Apache License

@Override
public Map<?, ?> deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonMapTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseTypeParameterTypeAdapter.java

License:Apache License

@Override
public Object deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonMapTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}

From source file:at.pcgamingfreaks.UUIDConverter.java

License:Open Source License

private static String getOnlineUUID(@NotNull String name, @Nullable Date at) {
    if ((at == null || at.after(new Date(new Date().getTime() - 1000L * 24 * 3600 * 30)))
            && UUID_CACHE.containsKey(name)) {
        return UUID_CACHE.get(name);
    }/*from w w  w.  j ava 2s.c  o m*/
    String uuid = null;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(new URL("https://api.mojang.com/users/profiles/minecraft/" + name
                    + ((at != null) ? "?at=" + at.getTime() : "")).openStream()))) {
        uuid = (((JsonObject) new JsonParser().parse(in)).get("id")).getAsString();
        if (uuid != null && (at == null || at.after(new Date(new Date().getTime() - 1000L * 24 * 3600 * 30)))) {
            UUID_CACHE.put(name, uuid);
        }
    } catch (MalformedURLException e) // There is something going wrong!
    {
        System.out.println("Failed to get uuid cause of a malformed url!\n Name: \"" + name + "\" Date: "
                + ((at != null) ? "?at=" + at.getTime() : "null"));
        e.printStackTrace();
    } catch (IOException e) {
        System.out
                .println("Looks like there is a problem with the connection with mojang. Please retry later.");
        if (e.getMessage().contains("HTTP response code: 429")) //TODO: more reliable detection
        {
            System.out.println("You have reached the request limit of the mojang api! Please retry later!");
        }
        e.printStackTrace();
    } catch (Exception e) {
        if (at == null) // We can't resolve the uuid for the player
        {
            System.out.println("Unable to get UUID for: " + name + "!");
        } else if (at.getTime() == 0) // If it's not his first name maybe it's his current name
        {
            System.out.println(
                    "Unable to get UUID for: " + name + " at " + at.getTime() + "! Trying without date!");
            uuid = getOnlineUUID(name, null);
        } else // If we cant get the player with the date he was here last time it's likely that it is his first name
        {
            System.out.println("Unable to get UUID for: " + name + " at " + at.getTime() + "! Trying at=0!");
            uuid = getOnlineUUID(name, new Date(0));
        }
        //e.printStackTrace();
    }
    return uuid;
}

From source file:at.storm.bolt.JsonBolt.java

License:Apache License

@SuppressWarnings("rawtypes")
public void prepare(Map config, TopologyContext context) {
    // Optional set logging
    if (config.get(CONF_LOGGING) != null) {
        m_logging = (Boolean) config.get(CONF_LOGGING);
    } else {//from  w  ww  .j a v a2s . com
        m_logging = false;
    }

    jsonParser = new JsonParser();

}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

public static void main(String[] args) {
    try {//from  w w w.ja  v a 2  s.  c om
        ImportExport ie = new ImportExport(args);
        File io = new File(ie.file);
        if (ie.export) {
            BufferedWriter out = new BufferedWriter(new FileWriter(io, false));
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonParser jp = new JsonParser();
            JsonElement je = jp.parse(ie.export());
            out.write(gson.toJson(je));
            out.close();
        } else {
            BufferedReader in = new BufferedReader(new FileReader(io));
            ie.imPort(new JsonParser().parse(in).getAsJsonObject());
            in.close();
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

License:Mozilla Public License

private JsonObject get(String action, URIBuilder builder) throws IOException {
    builder.setScheme("http") // buycraft, fix your https cert
            .setHost("api.buycraft.net").setPath("/v4").setParameter("action", action)
            .setParameter("secret", DatatypeConverter.printHexBinary(client.getApiKey()))
            .setParameter("playersOnline", onlinePlayers);
    HttpGet get;/*from  w ww .  ja  va  2s . c  om*/
    try {
        get = new HttpGet(builder.build());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();
    try (InputStream stream = entity.getContent()) {
        // can't be bothered to parse HTTP encoding, UTF-8 should do the job
        Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
        return new JsonParser().parse(reader).getAsJsonObject();
    }
}

From source file:at.yawk.buycraft.web.HttpWebApi.java

License:Mozilla Public License

@Override
public void registerCoupon(Coupon coupon) throws IOException, CouponException {
    List<NameValuePair> reqPairs = new ArrayList<>();

    String csrf = loadCouponCsrf();
    reqPairs.add(new BasicNameValuePair("csrf", csrf));

    if (coupon.getBasketTypes().contains(BasketType.SINGLE)) {
        if (coupon.getBasketTypes().contains(BasketType.SUBSCRIPTION)) {
            reqPairs.add(new BasicNameValuePair("basket_type", "both"));
        } else {//from w  w  w. j  ava2  s  .  c  om
            reqPairs.add(new BasicNameValuePair("basket_type", "subscription"));
        }
    } else {
        // without basket type would be invalid, should be checked in CouponBuilder
        reqPairs.add(new BasicNameValuePair("basket_type", "single"));
    }
    reqPairs.add(new BasicNameValuePair("code", coupon.getCode()));
    switch (coupon.getDiscountType()) {
    case AMOUNT:
        reqPairs.add(new BasicNameValuePair("discount_type", "value"));
        reqPairs.add(
                new BasicNameValuePair("discount_amount", String.format("%.2f", coupon.getDiscountAmount())));
        reqPairs.add(new BasicNameValuePair("discount_percentage", "0"));
        break;
    case PERCENTAGE:
        reqPairs.add(new BasicNameValuePair("discount_type", "percentage"));
        reqPairs.add(new BasicNameValuePair("discount_amount", "0.00"));
        reqPairs.add(new BasicNameValuePair("discount_percentage",
                Double.toString(coupon.getDiscountFraction() * 100)));
        break;
    }

    switch (coupon.getExpiryType()) {
    case NEVER:
        reqPairs.add(new BasicNameValuePair("expire_type", "never"));
        reqPairs.add(new BasicNameValuePair("expire_limit", "0"));
        reqPairs.add(new BasicNameValuePair("expire_timestamp", LocalDate.now().format(DATE_FORMATTER)));
        break;
    case DATE:
        reqPairs.add(new BasicNameValuePair("expire_type", "timestamp"));
        reqPairs.add(new BasicNameValuePair("expire_timestamp", coupon.getExpiryDate().format(DATE_FORMATTER)));
        reqPairs.add(new BasicNameValuePair("expire_limit", "0"));
        break;
    case REDEEM_COUNT:
        reqPairs.add(new BasicNameValuePair("expire_type", "limit"));
        reqPairs.add(new BasicNameValuePair("expire_limit", Integer.toString(coupon.getExpiryRedeemCount())));
        reqPairs.add(new BasicNameValuePair("expire_timestamp", LocalDate.now().format(DATE_FORMATTER)));
        break;
    }

    reqPairs.add(new BasicNameValuePair("minimum", String.format("%.2f", coupon.getMinimumBasketValue())));
    reqPairs.add(new BasicNameValuePair("start_time", coupon.getStartDate().format(DATE_FORMATTER)));
    reqPairs.add(new BasicNameValuePair("user_limit", Integer.toString(coupon.getMaximumUserUses())));

    switch (coupon.getEffectType()) {
    case CART:
        reqPairs.add(new BasicNameValuePair("type", "cart"));
        break;
    case CATEGORIES:
        for (int category : coupon.getCategoryIds()) {
            reqPairs.add(new BasicNameValuePair("categories[]", Integer.toString(category)));
        }
        reqPairs.add(new BasicNameValuePair("type", "category"));
        break;
    case PACKAGES:
        for (int packageId : coupon.getPackages()) {
            reqPairs.add(new BasicNameValuePair("packages[]", Integer.toString(packageId)));
        }
        reqPairs.add(new BasicNameValuePair("type", "package"));
        break;
    }

    HttpPost request = new HttpPost("https://server.buycraft.net/coupons/add");
    request.addHeader("X-Requested-With", "XMLHttpRequest");
    request.setEntity(new UrlEncodedFormEntity(reqPairs));
    HttpResponse response = client.execute(request);

    HttpEntity entity = response.getEntity();
    Header encoding = entity.getContentEncoding();
    JsonObject json = new JsonParser()
            .parse(new InputStreamReader(entity.getContent(), encoding == null ? "UTF-8" : encoding.getValue()))
            .getAsJsonObject();

    if (json.get("type").getAsString().equals("error")) {
        throw new CouponException(json.get("message").toString());
    }
}

From source file:at.yawk.votifier.VotifierKeyPair.java

License:Mozilla Public License

public static VotifierKeyPair read(Reader reader) throws Exception {
    return read(new JsonParser().parse(reader).getAsJsonObject());
}