Example usage for com.google.gson JsonObject entrySet

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

Introduction

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

Prototype

public Set<Map.Entry<String, JsonElement>> entrySet() 

Source Link

Document

Returns a set of members of this object.

Usage

From source file:com.samsung.sjs.constraintsolver.OperatorModel.java

License:Apache License

public OperatorModel() {
    Reader reader = new InputStreamReader(OperatorModel.class.getResourceAsStream("/operators.json"));

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(reader);
    if (element.isJsonArray()) {
        JsonArray jsa = element.getAsJsonArray();
        for (Iterator<JsonElement> it = jsa.iterator(); it.hasNext();) {
            JsonElement operatorEntry = it.next();
            if (operatorEntry.isJsonObject()) {
                JsonObject jso = operatorEntry.getAsJsonObject();
                for (Entry<String, JsonElement> entry : jso.entrySet()) {
                    String operatorName = entry.getKey();
                    JsonElement value = entry.getValue();
                    if (value.isJsonArray()) {
                        JsonArray elements = value.getAsJsonArray();
                        for (Iterator<JsonElement> it2 = elements.iterator(); it2.hasNext();) {
                            JsonElement element2 = it2.next();
                            if (element2.isJsonObject()) {
                                JsonObject object = element2.getAsJsonObject();
                                JsonElement jsonElement = object.get("operand");
                                if (jsonElement != null) {
                                    String op = jsonElement.getAsString();
                                    String result = object.get("result").getAsString();
                                    String prefix = object.get("isprefix").getAsString();
                                    boolean isPrefix;
                                    if (prefix.equals("true")) {
                                        isPrefix = true;
                                    } else if (prefix.equals("false")) {
                                        isPrefix = false;
                                    } else {
                                        throw new Error(
                                                "unrecognized value for prefix status of unary operator: "
                                                        + prefix);
                                    }/*w w w.  ja  v  a2 s.  c om*/
                                    if (!unaryOperatorMap.containsKey(operatorName)) {
                                        unaryOperatorMap.put(operatorName, new ArrayList<UnOpTypeCase>());
                                    }
                                    List<UnOpTypeCase> cases = unaryOperatorMap.get(operatorName);
                                    cases.add(new UnOpTypeCase(toType(op), toType(result), isPrefix));
                                } else {
                                    String left = object.get("left").getAsString();
                                    String right = object.get("right").getAsString();
                                    String result = object.get("result").getAsString();
                                    if (!infixOperatorMap.containsKey(operatorName)) {
                                        infixOperatorMap.put(operatorName, new ArrayList<InfixOpTypeCase>());
                                    }
                                    List<InfixOpTypeCase> cases = infixOperatorMap.get(operatorName);
                                    cases.add(new InfixOpTypeCase(toType(left), toType(right), toType(result)));
                                }
                            }
                        }
                    }
                }
            } else {
                throw new Error("JsonObject expected");
            }
        }
    } else {
        throw new Error("JsonArray expected");
    }
}

From source file:com.sangupta.rni.RPCReceivingServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String uri = extractUri(request);

    // check for rni header
    final String methodParams = request.getHeader(RniUtils.REQUEST_HEADER_FOR_PARAMS);
    if (methodParams == null) {
        LOGGER.debug("No RNI header present: {}", uri);
        response.sendError(HttpStatusCode.BAD_REQUEST);
        return;//w ww . j a v a2 s  .co  m
    }

    // extract method name
    Map<String, MappedInvocationMethod> map = END_POINTS.get(uri);
    if (map == null) {
        LOGGER.debug("End point not mapped to any instance: {}", uri);
        response.sendError(HttpStatusCode.NOT_FOUND);
        return;
    }

    // find the right method to be invoked
    MappedInvocationMethod mappedMethod = map.get(methodParams);
    if (mappedMethod == null) {
        LOGGER.debug("End point not initialized to any instance: {}", uri);
        response.sendError(HttpStatusCode.INTERNAL_SERVER_ERROR);
        return;
    }

    final int numArguments = RniUtils.count(methodParams, ',') + 1;
    final String[] classArray = methodParams.split(",");

    // find number and type of arguments that have been sent in the payload
    byte[] bytes = IOUtils.toByteArray(request.getInputStream());
    String json = new String(bytes, Charsets.UTF_8);

    // parse the body
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(json);
    JsonObject jsonObject = jsonElement.getAsJsonObject();

    // make a call to this method
    Set<Entry<String, JsonElement>> set = jsonObject.entrySet();
    Object[] args = new Object[set.size()];
    Class<?>[] params = new Class[set.size()];

    for (int index = 0; index < numArguments; index++) {
        JsonElement element = jsonObject.get("param-" + index);

        Class<?> clazz = null;
        try {
            clazz = Class.forName(classArray[index]);
        } catch (ClassNotFoundException e) {
            response.sendError(HttpStatusCode.INTERNAL_SERVER_ERROR);
            return;
        }

        params[index] = clazz;
        args[index++] = GsonUtils.getGson().fromJson(element, clazz);
    }

    // invoke the method
    try {
        Object result = mappedMethod.method.invoke(mappedMethod.instance, args);

        if (result == null) {
            response.setStatus(HttpStatusCode.NO_CONTENT);
            return;
        }

        ResponseUtils.sendResponse(response, GsonUtils.getGson().toJson(result), HttpMimeType.JSON);
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
        response.sendError(HttpStatusCode.INTERNAL_SERVER_ERROR);
        return;
    }
}

From source file:com.sat.common.SDdetails.java

License:Open Source License

private static void prObject(JsonElement jelement) {
    //   System.out.println("------------------------Start Object---------------------------");
    if (jelement.isJsonObject()) {
        JsonObject jj = jelement.getAsJsonObject();
        for (Entry<String, JsonElement> a : jj.entrySet()) {
            if (a.getValue().isJsonObject()) {
                JsonElement jelement1 = a.getValue();
                String s = "  sat  " + a.getKey() + " :" + a.getValue().toString();
                // System.out.println(s);
                // htmlfile.print(s);
                prObject(jelement1);/*from  w w  w. j  a v a 2  s  .  co m*/
            } else if (a.getValue().isJsonArray()) {
                prArray(a.getValue());
            } else {
                String s = a.getKey() + " : " + a.getValue().toString();

                if (s.startsWith("status"))
                    sathish = sathish + "</tr> <tr>";
                if (s.startsWith("id") || s.startsWith("status") || s.startsWith("address")) {
                    //System.out.println(s);
                    sathish = sathish + "                 <td>" + s.replaceAll(" ", "") + "</td>";
                    //htmlfile.println(s);
                }
            }

        }
    }
    //System.out.println("------------------------End Object---------------------------");
}

From source file:com.savoirtech.json.processor.JsonComparisonProcessor.java

License:Apache License

/**
 * Walk all of the fields within the JSON objects given, comparing each.
 *//*from   w w w.  j a va 2  s. c o m*/
private JsonComparatorResult walkJsonObjectFields(String pathToObject, JsonObject templateObj,
        JsonObject actualObj) {

    boolean match = true;
    String errorMessage = null;
    String errorPath = null;

    //
    // Make sure the set of fields in both objects match.  If not, there's no need to continue to
    //  perform a deep comparison.
    //

    if (this.jsonObjectFieldSetsMatch(templateObj, actualObj)) {
        //
        // Iterate over all of the fields in the objects and compare each.
        //
        Iterator<Map.Entry<String, JsonElement>> entryIterator = actualObj.entrySet().iterator();

        while ((match) && (entryIterator.hasNext())) {
            Map.Entry<String, JsonElement> entry = entryIterator.next();

            String fieldPath = pathToObject + "['" + entry.getKey() + "']";

            JsonElement templateFieldEle = templateObj.get(entry.getKey());

            // Perform a deep comparison of the field values.
            JsonComparatorResult fieldResult = this.walkAndCompare(fieldPath, templateFieldEle,
                    entry.getValue());

            match = fieldResult.isMatch();
            errorMessage = fieldResult.getErrorMessage();
            errorPath = fieldResult.getErrorPath();
        }
    } else {
        match = false;
        errorMessage = "object field sets do not match: path='" + pathToObject + "'";
        errorPath = pathToObject;
    }

    return new JsonComparatorResult(true, match, errorMessage, errorPath);
}

From source file:com.savoirtech.json.processor.JsonComparisonProcessor.java

License:Apache License

/**
 * Determine whether the set of field names in the two given JSON objects are the same.
 *///  ww  w. ja  va2  s  .  co m
private boolean jsonObjectFieldSetsMatch(JsonObject first, JsonObject second) {
    Set<String> firstFieldNames = first.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toSet());

    Set<String> secondFieldNames = second.entrySet().stream().map(Map.Entry::getKey)
            .collect(Collectors.toSet());

    return (firstFieldNames.equals(secondFieldNames));
}

From source file:com.sbhstimetable.sbhs_timetable_android.backend.json.TimetableJson.java

License:Open Source License

public TimetableJson(JsonObject o) {
    this.json = o;

    JsonObject subj = o.get("subjInfo").getAsJsonObject();
    Set<Map.Entry<String, JsonElement>> entries = subj.entrySet();

    for (Map.Entry<String, JsonElement> i : entries) {
        subjs.put(i.getKey(), new SubjectInfo(i.getValue().getAsJsonObject()));
    }//  w w  w  . j  av a2s.c o  m

    JsonObject days = o.get("days").getAsJsonObject();
    for (int i = 1; i < 16; i++) {

        this.days[i - 1] = new Day(i, days.get(i + "").getAsJsonObject(), this);
        this.dayNameToNum.put(this.days[i - 1].getDayName(), i);
    }
}

From source file:com.seleritycorp.common.base.config.ConfigUtils.java

License:Apache License

/**
 * Adds a JSON object to a Config.//from ww w. j a  v a  2 s . co m
 * 
 * @param object The object to add
 * @param config The config instance to add the object to
 * @param key The key in the config space
 */
private static void loadJson(JsonObject object, ConfigImpl config, String key) {
    for (Entry<String, JsonElement> entry : object.entrySet()) {
        String newKey = addToKey(key, entry.getKey());
        loadJson(entry.getValue(), config, newKey);
    }
}

From source file:com.simiacryptus.mindseye.network.DAGNetwork.java

License:Apache License

/**
 * Instantiates a new Dag network./*from  w  ww .  ja v  a2s.  co  m*/
 *
 * @param json the json
 * @param rs   the rs
 */
protected DAGNetwork(@Nonnull final JsonObject json, Map<CharSequence, byte[]> rs) {
    super(json);
    for (@Nonnull
    final JsonElement item : json.getAsJsonArray("inputs")) {
        @Nonnull
        final UUID key = UUID.fromString(item.getAsString());
        inputHandles.add(key);
        InputNode replaced = inputNodes.put(key, new InputNode(this, key));
        if (null != replaced)
            replaced.freeRef();
    }
    final JsonObject jsonNodes = json.getAsJsonObject("nodes");
    final JsonObject jsonLayers = json.getAsJsonObject("layers");
    final JsonObject jsonLinks = json.getAsJsonObject("links");
    final JsonObject jsonLabels = json.getAsJsonObject("labels");
    @Nonnull
    final Map<UUID, Layer> source_layersByNodeId = new HashMap<>();
    @Nonnull
    final Map<UUID, Layer> source_layersByLayerId = new HashMap<>();
    for (@Nonnull
    final Entry<String, JsonElement> e : jsonLayers.entrySet()) {
        @Nonnull
        Layer value = Layer.fromJson(e.getValue().getAsJsonObject(), rs);
        source_layersByLayerId.put(UUID.fromString(e.getKey()), value);
    }
    for (@Nonnull
    final Entry<String, JsonElement> e : jsonNodes.entrySet()) {
        @Nonnull
        final UUID nodeId = UUID.fromString(e.getKey());
        @Nonnull
        final UUID layerId = UUID.fromString(e.getValue().getAsString());
        final Layer layer = source_layersByLayerId.get(layerId);
        assert null != layer;
        source_layersByNodeId.put(nodeId, layer);
    }
    @Nonnull
    final LinkedHashMap<CharSequence, UUID> labels = new LinkedHashMap<>();
    for (@Nonnull
    final Entry<String, JsonElement> e : jsonLabels.entrySet()) {
        labels.put(e.getKey(), UUID.fromString(e.getValue().getAsString()));
    }
    @Nonnull
    final Map<UUID, List<UUID>> deserializedLinks = new HashMap<>();
    for (@Nonnull
    final Entry<String, JsonElement> e : jsonLinks.entrySet()) {
        @Nonnull
        final ArrayList<UUID> linkList = new ArrayList<>();
        for (@Nonnull
        final JsonElement linkItem : e.getValue().getAsJsonArray()) {
            linkList.add(UUID.fromString(linkItem.getAsString()));
        }
        deserializedLinks.put(UUID.fromString(e.getKey()), linkList);
    }
    for (final UUID key : labels.values()) {
        initLinks(deserializedLinks, source_layersByNodeId, key);
    }
    for (final UUID key : source_layersByNodeId.keySet()) {
        initLinks(deserializedLinks, source_layersByNodeId, key);
    }
    @Nonnull
    final UUID head = UUID.fromString(json.getAsJsonPrimitive("head").getAsString());
    initLinks(deserializedLinks, source_layersByNodeId, head);
    source_layersByLayerId.values().forEach(x -> x.freeRef());
    this.labels.putAll(labels);
    assertConsistent();
}

From source file:com.simonellistonball.nifi.processors.OpenScoringProcessor.OpenScoringProcessor.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//from   w  w w  . j  a v  a 2 s .  com
    if (flowFile == null) {
        return;
    }

    if (id.get() == null) {
        try {
            this.id.set(postModel(context.getProperty(OPENSCORING_URL).getValue(),
                    context.getProperty(PMML).getValue()));
        } catch (IOException e) {
            getLogger().error("Failure to post model", e);
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, FAILURE_MODEL);
        }
    }

    final String openScoringUrl = context.getProperty(OPENSCORING_URL).getValue();

    try {
        final boolean isCsv = flowFile.getAttribute("mime.type") == "text/csv";

        StringBuilder urlBuilder = new StringBuilder(openScoringUrl).append("/model/").append(id);
        if (isCsv) {
            urlBuilder.append("/csv");
        }
        final PostMethod post = new PostMethod(urlBuilder.toString());

        final String contentType;
        if (isCsv) {
            contentType = "text/plain";
        } else {
            contentType = "application/json";
        }
        post.setRequestHeader("Content-Type", contentType);

        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream in) throws IOException {
                post.setRequestEntity(new InputStreamRequestEntity(in, contentType));
            }
        });

        httpClient.executeMethod(post);
        if (isCsv) {
            // add the results to the input
            flowFile = session.write(flowFile, new OutputStreamCallback() {
                @Override
                public void process(OutputStream out) throws IOException {
                    IOUtils.copy(post.getResponseBodyAsStream(), out);
                }
            });
            session.transfer(flowFile, SUCCESS);
        } else {
            JsonParser parser = new JsonParser();
            JsonElement parsed = parser
                    .parse(new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8")));

            JsonObject newAttributes = parsed.getAsJsonObject().getAsJsonObject("result");
            final Map<String, String> attributes = new HashMap<String, String>(newAttributes.size());

            for (Entry<String, JsonElement> attribute : newAttributes.entrySet()) {
                if (!attribute.getValue().isJsonNull()) {
                    attributes.put(attribute.getKey(), attribute.getValue().getAsString());
                }
            }

            if (!attributes.isEmpty()) {
                flowFile = session.putAllAttributes(flowFile, attributes);
            }
            session.transfer(flowFile, SUCCESS);
        }
    } catch (Exception e) {
        getLogger().error("Failure to score model", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, FAILURE);
    }

}

From source file:com.sixt.service.framework.protobuf.ProtobufUtil.java

License:Apache License

/**
 * Converts a JSON object to a protobuf message
 *
 * @param builder the proto message type builder
 * @param input   the JSON object to convert
 *//*from w w w.ja  v  a 2s . c o m*/
public static Message fromJson(Message.Builder builder, JsonObject input) throws Exception {
    Descriptors.Descriptor descriptor = builder.getDescriptorForType();
    for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
        String protoName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
        Descriptors.FieldDescriptor field = descriptor.findFieldByName(protoName);
        if (field == null) {
            throw new Exception("Can't find descriptor for field " + protoName);
        }
        if (field.isRepeated()) {
            if (!entry.getValue().isJsonArray()) {
                // fail
            }
            JsonArray array = entry.getValue().getAsJsonArray();
            for (JsonElement item : array) {
                builder.addRepeatedField(field, parseField(field, item, builder));
            }
        } else {
            builder.setField(field, parseField(field, entry.getValue(), builder));
        }
    }
    return builder.build();
}