Example usage for com.google.gson JsonPrimitive JsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive(Character c) 

Source Link

Document

Create a primitive containing a character.

Usage

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive parseNBT(NBTTagByteArray nbtArray) {
    JsonArray jsonArray = new JsonArray();
    for (int i : nbtArray.func_150292_c())
        jsonArray.add(new JsonPrimitive(i));
    return new JsonPrimitive(NBTTypes[nbtArray.getId()] + jsonArray.toString());
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonElement fixNulls(JsonElement element) {
    if (element.isJsonNull())
        return new JsonPrimitive("");
    if (element.isJsonObject())
        return fixNulls(element.getAsJsonObject());
    if (element.isJsonArray())
        return fixNulls(element.getAsJsonArray());
    if (element.isJsonPrimitive())
        return fixNulls(element.getAsJsonPrimitive());
    return null;/*w  ww .ja  va 2 s.  c  o m*/
}

From source file:ccm.pay2spawn.util.JsonNBTHelper.java

License:Open Source License

public static JsonPrimitive fixNulls(JsonPrimitive primitive) {
    if (primitive.isBoolean())
        return new JsonPrimitive(primitive.getAsBoolean());
    if (primitive.isNumber())
        return new JsonPrimitive(primitive.getAsNumber());
    if (primitive.isString())
        return new JsonPrimitive(primitive.getAsString());
    return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive();
}

From source file:cf.brforgers.bot.handlers.BotIntercommns.java

License:LGPL

private static void transaction(User bot, String msg) {
    if (msg.length() < (IC_CALL.length() + 1) || !msg.startsWith(IC_CALL))
        return;//  www.j  a  v  a  2  s . c o m
    msg = msg.substring(IC_CALL.length());

    char opcode = msg.charAt(0);

    if (opcode == SUPPORTS_IC) {
        pm(bot, IC_CALL + SUPPORTED);
        return;
    }

    if (opcode == TRANSACTION) {
        if (msg.length() < 2)
            return;
        msg = msg.substring(1);
        opcode = msg.charAt(0);

        if (opcode == TRANSACTION_CHECK) {
            msg = msg.substring(2);
            int oldHash = Statistics.parseInt(msg, 0);
            if (oldHash != self.toString().hashCode()) {
                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_UPDATE);
            }
            return;
        }

        if (opcode == TRANSACTION_GET) {
            msg = msg.substring(2);

            if (msg.equals("p")) {
                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$p=" + self.p);
            }

            if (msg.equals("cmds")) {
                boolean first = true;
                JsonArray array = new JsonArray();
                String state = array.toString();

                for (int i = 0; i < self.cmds.size(); i++) {
                    state = array.toString();
                    array.add(new JsonPrimitive(self.cmds.get(i)));

                    if (array.toString().length() > 1900) {
                        pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$cmds" + (first ? "=" : "+")
                                + state);
                        first = false;
                        array = new JsonArray();
                        array.add(new JsonPrimitive(self.cmds.get(i)));
                    }
                }

                pm(bot, IC_CALL + TRANSACTION + TRANSACTION_SET + "$cmds" + (first ? "=" : "+") + state);
                return;
            }

            return;
        }

        if (opcode == TRANSACTION_SET) {
            msg = msg.substring(2);
            if (msg.startsWith("p")) {
                get(bot).p = Statistics.parseInt(msg.substring(2), 0);
                return;
            }

            if (msg.startsWith("cmds")) {
                msg = msg.substring("cmds".length());
                opcode = msg.charAt(0);
                msg = msg.substring(1);
                JsonArray array = new JsonParser().parse(msg).getAsJsonArray();

                if (opcode == '=') {
                    get(bot).cmds.clear();
                }

                if (opcode == '-') {
                    get(bot).cmds.removeIf(s -> StreamSupport.stream(array.spliterator(), false)
                            .anyMatch(j -> s.equals(j.getAsString()))); //I Know, it's lazy.
                }

                if (opcode == '=' || opcode == '+') {
                    get(bot).cmds.addAll(StreamSupport.stream(array.spliterator(), false)
                            .map(JsonElement::getAsString).collect(Collectors.toList()));
                }

                return;
            }
            return;
        }

        if (opcode == TRANSACTION_UPDATE) {
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_GET + "$p");
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_GET + "$cmds");
            return;
        }

        return;
    }

    if (msg.startsWith(SUPPORTED)) {
        if (Character.toLowerCase(msg.charAt(1)) == 'y') {
            pm(bot, IC_CALL + TRANSACTION + TRANSACTION_CHECK + TRANSACTION_VALUE
                    + get(bot).toString().hashCode());
        }
    }
}

From source file:ch.eitchnet.csvrestendpoint.marshaller.CsvDataToHeaderJsonMarshaller.java

License:Apache License

@Override
public JsonObject marshall(CSVParser csvParser) {

    JsonObject root = new JsonObject();
    root.addProperty("msg", "-");

    JsonArray data = new JsonArray();

    Set<Entry<String, Integer>> header = csvParser.getHeaderMap().entrySet();
    for (Entry<String, Integer> entry : header) {
        data.add(new JsonPrimitive(entry.getKey()));
    }/*  ww w  .jav a2s . c o m*/

    root.add("data", data);

    return root;
}

From source file:ch.eitchnet.csvrestendpoint.marshaller.CsvNamesToJsonMarshaller.java

License:Apache License

public JsonObject marshall(List<String> names) {

    JsonObject root = new JsonObject();
    root.addProperty("msg", "-");

    JsonArray data = new JsonArray();

    for (String name : names) {
        data.add(new JsonPrimitive(name));
    }//  www . ja va2  s . c om

    root.add("data", data);

    return root;
}

From source file:ch.epfl.leb.sass.models.fluorophores.internal.DefaultFluorophore.java

License:Open Source License

@Override
public JsonElement serialize(DefaultFluorophore src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add("id", new JsonPrimitive(src.getId()));
    result.add("x", new JsonPrimitive(src.x));
    result.add("y", new JsonPrimitive(src.y));
    result.add("z", new JsonPrimitive(src.z));
    result.add("currentState", new JsonPrimitive(src.getCurrentState()));
    result.add("maxPhotonsPerFrame", new JsonPrimitive(src.getSignal()));
    result.add("bleached", new JsonPrimitive(src.isBleached()));
    result.add("emitting", new JsonPrimitive(src.isOn()));
    result.add("onTime", new JsonPrimitive(src.getOnTimeThisFrame()));
    result.add("photonsEmittedLastFrame", new JsonPrimitive(src.getPhotonsThisFrame()));
    return result;
}

From source file:ch.epfl.leb.sass.models.fluorophores.internal.PhysicalFluorophore.java

License:Open Source License

@Override
public JsonElement serialize(PhysicalFluorophore src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add("id", new JsonPrimitive(src.getId()));
    result.add("x", new JsonPrimitive(src.x));
    result.add("y", new JsonPrimitive(src.y));
    result.add("z", new JsonPrimitive(src.z));
    result.add("currentState", new JsonPrimitive(src.getCurrentState()));
    result.add("maxPhotonsPerFrame", new JsonPrimitive(src.getSignal()));
    result.add("bleached", new JsonPrimitive(src.isBleached()));
    result.add("emitting", new JsonPrimitive(src.isOn()));
    result.add("onTime", new JsonPrimitive(src.getOnTimeThisFrame()));
    result.add("photonsEmittedLastFrame", new JsonPrimitive(src.getPhotonsThisFrame()));
    return result;
}

From source file:ch.ethz.coss.nervous.pulse.sql.SqlRequestWorker.java

License:Open Source License

@Override
public void run() {
    try {//  ww  w .  j a  v a 2  s .c o m

        JsonObject feature = null;
        JsonArray features = null;
        JsonObject featureCollection = null;

        try {

            /***** SQL get ********/
            // Fetch data
            PreparedStatement datastmt = sqlse.getSensorValuesFetchStatement(connection, ptmRequest.readingType,
                    ptmRequest.startTime, ptmRequest.endTime);
            ResultSet rs = datastmt.executeQuery();
            featureCollection = new JsonObject();
            features = new JsonArray();
            // System.out.println("SQL query result size =
            // "+rs.getFetchSize());
            long currentTimeMillis = System.currentTimeMillis();
            while (rs.next()) {
                long volatility = rs.getLong("Volatility");
                long recordTime = rs.getLong("RecordTime");

                //               System.out.println("Volatility = " + volatility);
                //               System.out.println("currentTimeMillis = " + currentTimeMillis);
                //               System.out.println("left time = " + (currentTimeMillis - (recordTime + (volatility * 1000))));
                if (volatility != -1)
                    if (volatility == 0 || currentTimeMillis > (recordTime + (volatility * 1000))) {
                        //                  System.out.println("Continue");
                        continue;
                    }

                String lat = rs.getString("lat");
                String lon = rs.getString("lon");

                feature = new JsonObject();
                feature.addProperty("type", "Feature");
                JsonObject point = new JsonObject();
                point.addProperty("type", "Point");
                JsonArray coord = new JsonArray();
                coord.add(new JsonPrimitive(lat));
                coord.add(new JsonPrimitive(lon));
                point.add("coordinates", coord);
                feature.add("geometry", point);

                JsonObject properties = new JsonObject();

                properties.addProperty("volatility", volatility);
                if (ptmRequest.readingType == 0) {
                    String luxVal = rs.getString("Light");
                    // System.out.println("Reading instance of light");
                    properties.addProperty("readingType", "" + 0);
                    properties.addProperty("level", luxVal);
                } else if (ptmRequest.readingType == 1) {
                    String soundVal = rs.getString("Decibel");
                    properties.addProperty("readingType", "" + 1);
                    properties.addProperty("level", soundVal);
                } else if (ptmRequest.readingType == 2) {
                    String message = rs.getString("Message");
                    message = message.trim();
                    properties.addProperty("readingType", "" + 2);

                    if (message.length() <= 0) {
                        message = "***Empty Message***";
                        continue;
                    }

                    properties.addProperty("message", message);

                } else {
                    // System.out.println("Reading instance not known");
                }

                feature.add("properties", properties);
                features.add(feature);

                // if((features.getAsJsonArray()).size() >= 60000){
                // featureCollection.add("features", features);
                // pSocketServer.sendToSocket(ptmRequest.webSocket,
                // ptmRequest.requestID, featureCollection.toString(),
                // false);
                // featureCollection = new JsonObject();
                // featureCollection = new JsonObject();
                // features = new JsonArray();
                // try {
                // Thread.sleep(10);
                // } catch (Exception e) {
                // // TODO Auto-generated catch block
                // e.printStackTrace();
                // }
                // break;
                // }
            }

            featureCollection.add("features", features);
            // System.out.println("Feature collection +
            // "+featureCollection.toString());
            pSocketServer.sendToSocket(ptmRequest.webSocket, ptmRequest.requestID, featureCollection.toString(),
                    true);

            /*************/

        } catch (JsonParseException e) {
            System.out.println("can't save json object: " + e.toString());
        }

    } catch (Exception e) {
        e.printStackTrace();
        Log.getInstance().append(Log.FLAG_WARNING, "Generic error");
    } finally {
        cleanup();
    }
}

From source file:ch.ethz.coss.nervous.pulse.sql.SqlUploadWorker.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override//  w w  w .j av a  2 s.c o  m
public void run() {
    // InputStream is;
    DataInputStream in = null;

    try {
        in = new DataInputStream(socket.getInputStream());
        boolean connected = true;
        while (connected) {
            connected &= !socket.isClosed();
            Visual reading = null;
            JsonObject featureCollection = new JsonObject();
            JsonArray features = new JsonArray();
            JsonObject feature = null;
            try {
                // String json = in.readUTF();

                // StringBuffer json = new StringBuffer();
                // String tmp;
                String json = null;
                try {
                    // while ((tmp = in.read()) != null) {
                    // json.append(tmp);
                    // }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte buffer[] = new byte[1024];
                    for (int s; (s = in.read(buffer)) != -1;) {
                        baos.write(buffer, 0, s);
                    }
                    byte result[] = baos.toByteArray();
                    json = new String(result);

                    // use inputLine.toString(); here it would have whole
                    // source
                    in.close();
                } catch (MalformedURLException me) {
                    System.out.println("MalformedURLException: " + me);
                } catch (IOException ioe) {
                    System.out.println("IOException: " + ioe);
                }
                System.out.println("JSON STRING = " + json);
                System.out.println("JSON Length = " + json.length());

                if (json.length() <= 0)
                    continue;
                reading = new JSONDeserializer<Visual>().deserialize(json, Visual.class);
                feature = new JsonObject();

                feature.addProperty("type", "Feature");
                // JsonArray featureList = new JsonArray();
                // iterate through your list
                // for (ListElement obj : list) {
                // {"geometry": {"type": "Point", "coordinates":
                // [-94.149, 36.33]}
                JsonObject point = new JsonObject();
                point.addProperty("type", "Point");
                // construct a JSONArray from a string; can also use an
                // array or list
                JsonArray coord = new JsonArray();
                if (reading == null || reading.location == null)
                    continue;
                else if (reading.location.latnLong[0] == 0 && reading.location.latnLong[1] == 0)
                    continue;

                coord.add(new JsonPrimitive(new String("" + reading.location.latnLong[0])));
                coord.add(new JsonPrimitive(new String("" + reading.location.latnLong[1])));

                point.add("coordinates", coord);
                feature.add("geometry", point);

                JsonObject properties = new JsonObject();
                if (reading.type == 0) {
                    // System.out.println("Reading instance of light");
                    properties.addProperty("readingType", "" + 0);
                    properties.addProperty("level", "" + ((LightReading) reading).lightVal);
                } else if (reading.type == 1) {
                    properties.addProperty("readingType", "" + 1);
                    properties.addProperty("level", "" + ((NoiseReading) reading).soundVal);
                } else if (reading.type == 2) {
                    properties.addProperty("readingType", "" + 2);
                    properties.addProperty("message", "" + ((TextVisual) reading).textMsg);
                } else {
                    // System.out.println("Reading instance not known");
                }
                properties.addProperty("recordTime", reading.timestamp);
                properties.addProperty("volatility", reading.volatility);
                feature.add("properties", properties);
                features.add(feature);
                featureCollection.add("features", features);

                if (reading.volatility != 0) {
                    /***** SQL insert ********/
                    // Insert data
                    System.out.println("before uploading SQL - reading uuid = " + reading.uuid);
                    System.out.println("Reading volatility = " + reading.volatility);
                    PreparedStatement datastmt = sqlse.getSensorInsertStatement(connection, reading.type);
                    if (datastmt != null) {
                        // System.out.println("datastmt - " +
                        // datastmt.toString());
                        List<Integer> types = sqlse.getArgumentExpectation((long) reading.type);
                        datastmt.setString(1, reading.uuid);
                        if (reading.type == 0) {
                            datastmt.setLong(2, reading.timestamp);
                            datastmt.setLong(3, reading.volatility);
                            datastmt.setDouble(4, ((LightReading) reading).lightVal);
                            datastmt.setDouble(5, reading.location.latnLong[0]);
                            datastmt.setDouble(6, reading.location.latnLong[1]);
                        } else if (reading.type == 1) {
                            datastmt.setLong(2, reading.timestamp);
                            datastmt.setLong(3, reading.volatility);
                            datastmt.setDouble(4, ((NoiseReading) reading).soundVal);
                            datastmt.setDouble(5, reading.location.latnLong[0]);
                            datastmt.setDouble(6, reading.location.latnLong[1]);
                        } else if (reading.type == 2) {
                            datastmt.setLong(2, reading.timestamp);
                            datastmt.setLong(3, reading.volatility);
                            datastmt.setString(4, ((TextVisual) reading).textMsg);
                            datastmt.setDouble(5, reading.location.latnLong[0]);
                            datastmt.setDouble(6, reading.location.latnLong[1]);
                        }
                        // System.out.println("datastmt after populating - "
                        // + datastmt.toString());

                        datastmt.addBatch();
                        datastmt.executeBatch();
                        datastmt.close();
                    }
                    /*************/

                }

            } catch (JsonParseException e) {
                System.out.println("can't save json object: " + e.toString());
            }
            // output the result
            // System.out.println("featureCollection=" +
            // featureCollection.toString());

            String message = featureCollection.toString();
            pSocketServer.sendToAll(message);

        }

    } catch (EOFException e) {
        e.printStackTrace();
        Log.getInstance().append(Log.FLAG_WARNING, "EOFException occurred, but ignored it for now.");
    } catch (IOException e) {
        e.printStackTrace();
        Log.getInstance().append(Log.FLAG_WARNING, "Opening data stream from socket failed");
    } catch (Exception e) {
        e.printStackTrace();
        Log.getInstance().append(Log.FLAG_WARNING, "Generic error");
    } finally {
        cleanup();
        try {
            in.close();
            in = null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ;
        }
    }
}