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:club.jmint.mifty.service.MiftyService.java

License:Apache License

public String callProxy(String method, String params, boolean isEncrypt) throws TException {
    //parse parameters and verify signature
    CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")");
    JsonObject ip;
    try {/*from  w  w  w.  j  av a 2  s  .  co m*/
        ip = parseInputParams(params, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }

    //extract all parameters
    HashMap<String, String> inputMap = new HashMap<String, String>();
    Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator();
    Entry<String, JsonElement> en = null;
    String key;
    JsonElement je;
    while (it.hasNext()) {
        en = it.next();
        key = en.getKey();
        je = en.getValue();
        if (je.isJsonArray()) {
            inputMap.put(key, je.getAsJsonArray().toString());
            //System.out.println(je.getAsJsonArray().toString());
        } else if (je.isJsonNull()) {
            inputMap.put(key, je.getAsJsonNull().toString());
            //System.out.println(je.getAsJsonNull().toString());
        } else if (je.isJsonObject()) {
            inputMap.put(key, je.getAsJsonObject().toString());
            //System.out.println(je.getAsJsonObject().toString());
        } else if (je.isJsonPrimitive()) {
            inputMap.put(key, je.getAsJsonPrimitive().getAsString());
            //System.out.println(je.getAsJsonPrimitive().toString());
        } else {
            //unkown type;
        }
    }

    //execute specific method
    Method[] ma = this.getClass().getMethods();
    int idx = 0;
    for (int i = 0; i < ma.length; i++) {
        if (ma[i].getName().equals(method)) {
            idx = i;
            break;
        }
    }
    HashMap<String, String> outputMap = null;
    try {
        Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes());
        outputMap = (HashMap<String, String>) m.invoke(this, inputMap);
        CrossLog.logger.debug("callProxy: " + method + "() executed.");
    } catch (NoSuchMethodException nsm) {
        CrossLog.logger.error("callProxy: " + method + "() not found.");
        CrossLog.printStackTrace(nsm);
        return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(),
                ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo());
    } catch (Exception e) {
        CrossLog.logger.error("callProxy: " + method + "() executed with exception.");
        CrossLog.printStackTrace(e);
        if (e instanceof CrossException) {
            return buildOutputByCrossException((CrossException) e);
        } else {
            return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(),
                    ErrorCode.COMMON_ERR_UNKOWN.getInfo());
        }
    }
    //if got error then return immediately
    String ec = outputMap.get("errorCode");
    String ecInfo = outputMap.get("errorInfo");
    if ((ec != null) && (!ec.isEmpty())) {
        return buildOutputError(Integer.parseInt(ec), ecInfo);
    }

    //build response parameters
    JsonObject op = new JsonObject();
    Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator();
    Entry<String, String> eno = null;
    JsonParser jpo = new JsonParser();
    JsonElement jeo = null;
    while (ito.hasNext()) {
        eno = ito.next();
        try {
            jeo = jpo.parse(eno.getValue());
        } catch (JsonSyntaxException e) {
            //            MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"].");
            //            return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), 
            //                  ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
            //we do assume that it should be a common string
            jeo = new JsonPrimitive(eno.getValue());
        }
        op.add(eno.getKey(), jeo);
    }

    String output = null;
    try {
        output = buildOutputParams(op, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }
    CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")");
    return output;
}

From source file:co.aikar.util.JSONUtil.java

License:MIT License

public static <E> JsonObject mapArrayToObject(Iterable<E> iterable, Function<E, JsonObject> function) {
    JsonObjectBuilder builder = objectBuilder();
    for (E element : iterable) {
        JsonObject obj = function.apply(element);
        if (obj == null) {
            continue;
        }// w w  w. j a v  a  2  s. c om
        for (Entry<String, JsonElement> entry : obj.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
    }
    return builder.build();
}

From source file:co.aurasphere.botmill.kik.util.json.LowerCaseTypeAdapterFactory.java

License:Open Source License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {

        @Override//  w  ww  .java 2 s  . co  m
        public T read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
        }

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        protected void beforeWrite(T source, JsonElement toSerialize) {
        }

        protected void afterRead(JsonElement deserialized) {
            if (deserialized instanceof JsonObject) {
                JsonObject jsonObject = ((JsonObject) deserialized);
                Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    if (entry.getValue() instanceof JsonElement) {
                        if (entry.getKey().equalsIgnoreCase("type")) {
                            String val = jsonObject.get(entry.getKey()).toString();
                            jsonObject.addProperty(entry.getKey(), val.toLowerCase());
                        }
                    } else {
                        afterRead(entry.getValue());
                    }
                }
            }
        }
    };
}

From source file:co.cask.cdap.api.dataset.lib.partitioned.PartitionKeyCodec.java

License:Apache License

@Override
public PartitionKey deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    PartitionKey.Builder builder = PartitionKey.builder();
    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        JsonArray jsonArray = entry.getValue().getAsJsonArray();
        builder.addField(entry.getKey(), deserializeComparable(jsonArray, jsonDeserializationContext));
    }//from   w ww.  ja v  a 2  s  . co  m
    return builder.build();
}

From source file:co.cask.cdap.examples.datacleansing.SimpleSchemaMatcher.java

License:Apache License

/**
 * Determines whether or not this matcher's schema fits a piece of data.
 * A failure to match could arise from any of:
 *  - a non-nullable field of the schema is missing from the data
 *  - a numerical field of the schema has non-numerical characters in it
 *  - the schema has non-simple types//from  w w  w.  j av a2 s.com
 *
 * @param data a JSON string to check if the schema matches it
 * @return true if the schema matches the given data
 */
public boolean matches(String data) {
    // rely on validations in the StructuredRecord's builder
    try {
        JsonObject jsonObject = new JsonParser().parse(data).getAsJsonObject();
        StructuredRecord.Builder builder = StructuredRecord.builder(schema);
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            builder.convertAndSet(entry.getKey(), entry.getValue().getAsString());
        }
        builder.build();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:co.cask.tigon.sql.internal.MetricsRecorder.java

License:Apache License

/**
 * This methods logs the received metrics into the underlying {@link Metrics} object.
 * This method should be invoked every time metrics are received from a SQL Compiler process.
 *
 * @param processName Name of the process which sent these metrics
 * @param metricsData The metrics sent by the process in a JSON format
 *//*  w  w w. jav a 2 s .  c  o  m*/
public void recordMetrics(String processName, JsonObject metricsData) {
    for (Map.Entry<String, JsonElement> entry : metricsData.entrySet()) {
        metrics.count(processName + "." + entry.getKey(), Math.round(entry.getValue().getAsFloat()));
    }
}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

@Override
public Bundleizer createBundleizer(final InputStream inputArg, final BundleFactory factoryArg) {
    return new Bundleizer() {
        private final BundleFactory factory = factoryArg;
        private final JsonParser parser = new JsonParser();
        private final JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(inputArg)));

        {/*w  w  w . j a v  a  2  s .c  o  m*/
            try {
                reader.beginArray();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public Bundle next() throws IOException {
            if (reader.hasNext()) {
                JsonObject nextElement = parser.parse(reader).getAsJsonObject();
                Bundle next = factory.createBundle();
                BundleFormat format = next.getFormat();
                for (Map.Entry<String, JsonElement> entry : nextElement.entrySet()) {
                    next.setValue(format.getField(entry.getKey()), fromGson(entry.getValue()));
                }
                return next;
            } else {
                return null;
            }
        }
    };
}

From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java

License:Apache License

public ValueObject fromGson(JsonElement gson) {
    if (gson.isJsonNull()) {
        return null;
    } else if (gson.isJsonObject()) {
        JsonObject object = gson.getAsJsonObject();
        ValueMap map = ValueFactory.createMap();
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            map.put(entry.getKey(), fromGson(entry.getValue()));
        }//from  w w  w  .  j a va  2s.  c  om
        return map;
    } else if (gson.isJsonArray()) {
        JsonArray gsonArray = gson.getAsJsonArray();
        ValueArray valueArray = ValueFactory.createArray(gsonArray.size());
        for (JsonElement arrayElement : gsonArray) {
            valueArray.add(fromGson(arrayElement));
        }
        return valueArray;
    } else {
        JsonPrimitive primitive = gson.getAsJsonPrimitive();
        if (primitive.isNumber()) {
            return ValueFactory.create(primitive.getAsDouble());
        } else {
            return ValueFactory.create(primitive.getAsString());
        }
    }
}

From source file:com.adeebnqo.Thula.mmssms.Transaction.java

License:Apache License

private String fetchRnrSe(String authToken, Context context) throws ExecutionException, InterruptedException {
    JsonObject userInfo = Ion.with(context).load("https://www.google.com/voice/request/user")
            .setHeader("Authorization", "GoogleLogin auth=" + authToken).asJsonObject().get();

    String rnrse = userInfo.get("r").getAsString();

    try {//from   ww w.  j  a  v  a 2 s  .c om
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Activity.TELEPHONY_SERVICE);
        String number = tm.getLine1Number();
        if (number != null) {
            JsonObject phones = userInfo.getAsJsonObject("phones");
            for (Map.Entry<String, JsonElement> entry : phones.entrySet()) {
                JsonObject phone = entry.getValue().getAsJsonObject();
                if (!PhoneNumberUtils.compare(number, phone.get("phoneNumber").getAsString()))
                    continue;
                if (!phone.get("smsEnabled").getAsBoolean())
                    break;

                Ion.with(context).load("https://www.google.com/voice/settings/editForwardingSms/")
                        .setHeader("Authorization", "GoogleLogin auth=" + authToken)
                        .setBodyParameter("phoneId", entry.getKey()).setBodyParameter("enabled", "0")
                        .setBodyParameter("_rnr_se", rnrse).asJsonObject();
                break;
            }
        }
    } catch (Exception e) {

    }

    // broadcast so you can save it to your shared prefs or something so that it doesn't need to be retrieved every time
    Intent intent = new Intent(VOICE_TOKEN);
    intent.putExtra("_rnr_se", rnrse);
    context.sendBroadcast(intent);

    return rnrse;
}

From source file:com.adobe.acs.commons.json.AbstractJSONObjectVisitor.java

License:Apache License

/**
 * Visit each JSON Object in the JSON Array.
 *
 * @param jsonObject The JSON Array/*from www  .  j av a2  s .co m*/
 */
protected final void traverseJSONObject(final JsonObject jsonObject) {
    if (jsonObject == null) {
        return;
    }

    for (Entry<String, JsonElement> elem : jsonObject.entrySet()) {
        if (elem.getValue().isJsonArray()) {
            accept(elem.getValue().getAsJsonArray());
        } else if (elem.getValue().isJsonObject()) {
            accept(elem.getValue().getAsJsonObject());
        }
    }
}