Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:com.samsung.sjs.JSEnvironment.java

License:Apache License

public void parseDecl(JsonObject decl) {
    String name = decl.getAsJsonPrimitive("name").getAsString();
    if (decl.getAsJsonPrimitive("intrinsic") != null) {
        assert (decl.getAsJsonPrimitive("intrinsic").getAsBoolean());
        parseIntrinsic(name, decl.getAsJsonObject("type"));
    } else {/* w w w  .  jav a  2s  .co m*/
        Type t = parseType(decl.getAsJsonObject("type"));
        put(name, t);
        if (t instanceof ConstructorType) {
            namedTypes.put(name, (ObjectType) ((ConstructorType) t).returnType());
        }
    }
}

From source file:com.samsung.sjs.JSEnvironment.java

License:Apache License

public Type parseType(JsonObject ty) {
    assert (ty != null);
    String typefamily = ty.getAsJsonPrimitive("typefamily").getAsString();
    switch (typefamily) {
    case "string":
        return Types.mkString();
    case "int":
        return Types.mkInt();
    case "double":
        return Types.mkFloat();
    case "void":
        return Types.mkVoid();
    case "bool":
        return Types.mkBool();
    case "array":
        Type etype = parseType(ty.getAsJsonObject("elemtype"));
        return Types.mkArray(etype);
    case "map":
        Type mtype = parseType(ty.getAsJsonObject("elemtype"));
        return Types.mkMap(mtype);
    case "constructor":
    case "function":
    case "method":
        final Type ret = parseType(ty.getAsJsonObject("return"));
        final List<String> names = new LinkedList<String>();
        final List<Type> types = new LinkedList<Type>();
        for (JsonElement e : ty.getAsJsonArray("args")) {
            JsonObject eo = e.getAsJsonObject();
            names.add(eo.getAsJsonPrimitive("name").getAsString());
            types.add(parseType(eo.getAsJsonObject("type")));
        }//from   w ww  . j  av  a 2  s .  co  m
        if (typefamily.equals("function")) {
            return Types.mkFunc(ret, types, names);
        } else if (typefamily.equals("constructor")) {
            return Types.mkCtor(types, names, ret, null);
        } else {
            // method
            assert (typefamily.equals("method"));
            return Types.mkMethod(Types.mkAny(), ret, names, types); // TODO: Why does AttachedMethodType have a receiver?
        }
    case "object":
        final List<Property> props = new LinkedList<Property>();
        for (JsonElement e : ty.getAsJsonArray("members")) {
            JsonObject eo = e.getAsJsonObject();
            props.add(parseProp(eo));
        }
        ObjectType o = Types.mkObject(props);
        if (ty.has("typename")) {
            namedTypes.put(ty.getAsJsonPrimitive("typename").getAsString(), o);
        }
        return o;

    case "intersection":
        List<Type> mems = new LinkedList<>();
        for (JsonElement e : ty.getAsJsonArray("members")) {
            JsonObject eo = e.getAsJsonObject();
            mems.add(parseType(eo));
        }
        return new IntersectionType(mems);
    case "typevariable":
        int x = ty.getAsJsonPrimitive("id").getAsInt();
        return new TypeVariable(x);
    case "name":
        String name = ty.getAsJsonPrimitive("name").getAsString();
        return new NamedObjectType(name, this);
    default:
        throw new IllegalArgumentException(typefamily);
    }
}

From source file:com.samsung.sjs.JSEnvironment.java

License:Apache License

public Property parseProp(JsonObject p) {
    String name = p.getAsJsonPrimitive("name").getAsString();
    return Types.mkProperty(name, parseType(p.getAsJsonObject("type")));
}

From source file:com.SatanicSpider.Serialization.BodySerializer.java

public Body deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    try {/*w w  w  .j  a v a 2 s.  c o m*/
        JsonPrimitive jsonP = jsonObject.getAsJsonPrimitive("json");
        String jsonS = jsonP.getAsString();
        //Thsi is going to fuck up on other threads ...
        Body b = PhysicsManager.JSONifier.j2b2Body(PhysicsManager.PhysWorld, new JSONObject(jsonS));
    } catch (Exception ex) {
        System.err.println("Unknown Exception");
        ex.printStackTrace();
    }
    return null;
}

From source file:com.SatanicSpider.Serialization.EntitySerializer.java

public Entity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    try {// w  w  w . j a  v a2s  . c  o  m
        JsonPrimitive jsonP = jsonObject.getAsJsonPrimitive("json");
        String jsonS = jsonP.getAsString();
        //Thsi is going to fuck up on other threads ...
        //Entity b = PhysicsManager.JSONifier.j2b2Body(PhysicsManager.PhysWorld, new JSONObject(jsonS));
    } catch (Exception ex) {
        System.err.println("Unknown Exception");
        ex.printStackTrace();
    }
    return null;
}

From source file:com.seleritycorp.context.ContextApiDemoMain.java

License:Apache License

/**
 * Resolves the query to entities, dumps information about them, and yields the entity ids. 
 * /* ww  w . j a  v a2s  .c  o  m*/
 * <p/>Queries DDS for entities that match the query command line argument. If the command line
 * arguments requested exact matching, exact matching is requested from DDS, otherwise partial
 * matching is performed.
 * 
 * </p>Only up to {@link #MAX_ENTITIES} are fetched from DDS. 
 *
 * @return the entity ids of the entities for the query
 * @throws Exception, if any error occurs
 */
private Iterable<String> resolveQueryEntityIds() throws Exception {
    List<String> entityIds = new LinkedList<>();

    if (query != null && !query.isEmpty()) {
        String entityQueryMode = exactMatching ? "EXACT_MATCH" : "PARTIAL_MATCH";
        JsonArray results = queryUtils.queryEntities(query, entityQueryMode, MAX_ENTITIES);

        printUtils.println("Query for '" + query + "' will look for those entities:");
        for (JsonElement resultElement : results) {
            JsonObject result = resultElement.getAsJsonObject();
            String id = result.getAsJsonPrimitive("entityID").getAsString();

            printUtils.print("* " + id);
            printUtils.printEntityDetails(result);

            entityIds.add(id);
        }
    }

    return entityIds;
}

From source file:com.seleritycorp.context.ContextApiDemoMain.java

License:Apache License

/**
 * Performs intitial query, performs update endlessly, and prints new content items.
 * //from w  ww .  j ava2s .  com
 * @throws Exception, if any errors occur
 */
private void queryWithUpdates() throws Exception {
    // First, we resolve the query to entity ids.
    Iterable<String> entityIds = resolveQueryEntityIds();

    int batchSize = 10; // requesting only up to 10 items per query
    Deque<String> seenContentIds = new LinkedList<>(); // Used to filter seen items from updates
    JsonArray recommendations; // Will hold the recommended content items of the last query
    boolean isInitial = true; // Whether or not to perform an INITIAL or UPDATE query.
    while (true) {
        // Perform the query
        recommendations = queryUtils.queryRecommendations(queryType, isInitial, batchSize, contributions,
                entityIds);
        isInitial = false; // From now on, all queries are UPDATES

        // Filter down to unseen recommendations    
        List<JsonObject> unseenRecommendations = new ArrayList<>(recommendations.size());
        for (JsonElement recommendationElement : recommendations) {
            JsonObject recommendation = recommendationElement.getAsJsonObject();
            String contentId = recommendation.getAsJsonPrimitive("contentID").getAsString();
            if (contentId != null) {
                if (!seenContentIds.contains(contentId)) {
                    // Recommendation has not yet been seen
                    unseenRecommendations.add(recommendation);

                    // And we remember that we saw that content item.
                    seenContentIds.addFirst(contentId);

                    // To avoid keeping too many items in memory, we prune old items. 
                    if (seenContentIds.size() > 2 * batchSize) {
                        seenContentIds.removeLast();
                    }
                }
            }
        }

        printUtils.println("Received " + recommendations.size() + " recommendations. "
                + unseenRecommendations.size() + " of those have not yet been seen.");

        // Printing unseen recommendations
        for (JsonObject recommendation : unseenRecommendations) {
            printUtils.printRecommendation(recommendation);
        }

        if (!live) {
            // Backing-off a bit before the next query to avoid hammering servers.
            pauseBeforeUpdate();
        }
    }
}

From source file:com.simiacryptus.mindseye.lang.Tensor.java

License:Apache License

/**
 * From json tensor./*from   ww  w  . j  ava2s .com*/
 *
 * @param json      the json
 * @param resources the resources
 * @return the tensor
 */
@Nullable
public static Tensor fromJson(@Nullable final JsonElement json, @Nullable Map<CharSequence, byte[]> resources) {
    if (null == json)
        return null;
    if (json.isJsonArray()) {
        final JsonArray array = json.getAsJsonArray();
        final int size = array.size();
        if (array.get(0).isJsonPrimitive()) {
            final double[] doubles = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).mapToDouble(element -> {
                return element.getAsDouble();
            }).toArray();
            @Nonnull
            Tensor tensor = new Tensor(doubles);
            assert tensor.isValid();
            return tensor;
        } else {
            final List<Tensor> elements = IntStream.range(0, size).mapToObj(i -> {
                return array.get(i);
            }).map(element -> {
                return Tensor.fromJson(element, resources);
            }).collect(Collectors.toList());
            @Nonnull
            final int[] dimensions = elements.get(0).getDimensions();
            if (!elements.stream().allMatch(t -> Arrays.equals(dimensions, t.getDimensions()))) {
                throw new IllegalArgumentException();
            }
            @Nonnull
            final int[] newDdimensions = Arrays.copyOf(dimensions, dimensions.length + 1);
            newDdimensions[dimensions.length] = size;
            @Nonnull
            final Tensor tensor = new Tensor(newDdimensions);
            @Nullable
            final double[] data = tensor.getData();
            for (int i = 0; i < size; i++) {
                @Nullable
                final double[] e = elements.get(i).getData();
                System.arraycopy(e, 0, data, i * e.length, e.length);
            }
            for (@Nonnull
            Tensor t : elements) {
                t.freeRef();
            }
            assert tensor.isValid();
            return tensor;
        }
    } else if (json.isJsonObject()) {
        JsonObject jsonObject = json.getAsJsonObject();
        @Nonnull
        int[] dims = fromJsonArray(jsonObject.getAsJsonArray("length"));
        @Nonnull
        Tensor tensor = new Tensor(dims);
        SerialPrecision precision = SerialPrecision
                .valueOf(jsonObject.getAsJsonPrimitive("precision").getAsString());
        JsonElement base64 = jsonObject.get("base64");
        if (null == base64) {
            if (null == resources)
                throw new IllegalArgumentException("No Data Resources");
            CharSequence resourceId = jsonObject.getAsJsonPrimitive("resource").getAsString();
            tensor.setBytes(resources.get(resourceId), precision);
        } else {
            tensor.setBytes(Base64.getDecoder().decode(base64.getAsString()), precision);
        }
        assert tensor.isValid();
        JsonElement id = jsonObject.get("id");
        if (null != id) {
            tensor.setId(UUID.fromString(id.getAsString()));
        }
        return tensor;
    } else {
        @Nonnull
        Tensor tensor = new Tensor(json.getAsJsonPrimitive().getAsDouble());
        assert tensor.isValid();
        return tensor;
    }
}

From source file:com.simiacryptus.mindseye.layers.cudnn.ActivationLayer.java

License:Apache License

/**
 * Instantiates a new Activation key.//from   w  ww . j a va  2 s  .c  om
 *
 * @param json the json
 */
protected ActivationLayer(@Nonnull final JsonObject json) {
    super(json);
    mode = json.getAsJsonPrimitive("mode").getAsInt();
    setAlpha(json.getAsJsonPrimitive("alpha").getAsDouble());
    precision = Precision.valueOf(json.get("precision").getAsString());
}

From source file:com.simiacryptus.mindseye.layers.cudnn.conv.FullyConnectedLayer.java

License:Apache License

/**
 * Instantiates a new Img eval key.//from w  w w  .j  av a  2s .c  o  m
 *
 * @param json the json
 * @param rs   the rs
 */
protected FullyConnectedLayer(@Nonnull final JsonObject json, Map<CharSequence, byte[]> rs) {
    super(json);
    outputDims = JsonUtil.getIntArray(json.getAsJsonArray("outputDims"));
    inputDims = JsonUtil.getIntArray(json.getAsJsonArray("inputDims"));
    @Nullable
    final Tensor data = Tensor.fromJson(json.get("weights"), rs);
    weights = data;
    this.precision = Precision.valueOf(json.getAsJsonPrimitive("precision").getAsString());
}