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:ch.ethz.coss.nervous.pulse.WriteJSON.java

License:Open Source License

public static void sendGeoJSON(Socket socket, Object o) {

    try {/*from  w  ww . j  a v a  2 s .  c o m*/
        Scanner in = new Scanner(socket.getInputStream());

        while (!in.nextLine().isEmpty())
            ;

        PrintWriter out = new PrintWriter(socket.getOutputStream());

        Visual reading = (Visual) o;

        JsonObject feature = new JsonObject();
        try {
            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();
            coord.add(new JsonPrimitive(reading.location.latnLong[0]));
            coord.add(new JsonPrimitive(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("lightLevel", "" + ((LightReading) reading).lightVal);
            } else if (reading.type == 1) {
                properties.addProperty("readingType", "" + 1);
                properties.addProperty("noiseLevel", "" + ((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");
            }

            feature.add("properties", properties);

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

        String message = feature.toString();

        out.println("HTTP/1.0 200 OK");
        out.println("Content-Type: text/json");
        out.printf("Content-Length: %d%n", message.length());
        out.println("Access-Control-Allow-Origin: *");
        out.println();
        out.println(message);
        out.flush();

        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ch.jamiete.hilda.admin.commands.AdminAllowCommand.java

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final List<String> strings = new ArrayList<>();

        for (String str : this.hilda.getAllowedServers()) {
            Guild guild = this.hilda.getBot().getGuildById(str);

            if (guild != null) {
                strings.add(this.name(guild));
            }//from w ww.  j  a  v a2 s .c o  m
        }

        if (strings.isEmpty()) {
            this.reply(message, "The whitelist function is not enabled!");
        } else {
            final MessageBuilder mb = new MessageBuilder();
            mb.append("I'm currently allowing ");

            if (strings.size() != this.hilda.getBot().getGuilds().size()) {
                mb.append("only ");
            }

            mb.append(strings.size()).append(strings.size() == 1 ? "server" : "servers").append(": ");
            mb.append(Util.getAsList(strings));
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    if (arguments.length == 0) {
        this.usage(message, "<id.../list>");
    }

    final AllowDirection direction = AllowDirection.valueOf(label.toUpperCase());
    final List<String> ids = new ArrayList<>();
    final List<String> success = new ArrayList<>();
    final List<String> fail = new ArrayList<>();

    for (final String arg : arguments) {
        Guild guild = this.hilda.getBot().getGuildById(arg);

        if (guild == null) {
            fail.add(arg);
        } else {
            ids.add(arg);
            success.add(this.name(guild));
        }
    }

    if (!success.isEmpty()) {
        final Configuration cfg = this.hilda.getConfigurationManager().getConfiguration(this.plugin,
                "allowedservers");
        JsonArray array = cfg.get().getAsJsonArray("servers");

        if (array == null) {
            array = new JsonArray();
        }

        for (final String id : ids) {
            if (direction == AllowDirection.ALLOW) {
                this.hilda.addAllowedServer(id);

                if (!array.contains(new JsonPrimitive(id))) {
                    array.add(id);
                }
            }

            if (direction == AllowDirection.DISALLOW) {
                this.hilda.removeAllowedServer(id);
                array.remove(new JsonPrimitive(id));
            }
        }

        cfg.get().add("servers", array);
        cfg.save();
    }

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, ");

    if (!success.isEmpty()) {
        mb.append("I'm ").append(direction == AllowDirection.ALLOW ? "now" : "no longer").append(" allowing ");
        mb.append(Util.getAsList(success));
    }

    if (!fail.isEmpty()) {
        if (!success.isEmpty()) {
            mb.append(", however ");
        }

        mb.append("I couldn't find any servers matching ");
        mb.append(Util.getAsList(fail));
    }

    mb.append(".");

    mb.buildAll(SplitPolicy.SPACE).forEach(m -> message.getChannel().sendMessage(m).queue());
}

From source file:ch.jamiete.hilda.admin.commands.AdminIgnoreCommand.java

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final List<String> strings = this.hilda.getCommandManager().getIgnoredUsers();

        if (strings.isEmpty()) {
            this.reply(message, "I'm not ignoring any channels!");
        } else {/*from  w  w w. j  a v a  2 s  . com*/
            final MessageBuilder mb = new MessageBuilder();
            mb.append("I'm currently ignoring ");
            mb.append(Util.getAsList(this.getPieces(strings)));
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    if (arguments.length == 0) {
        this.usage(message, "<@user.../id...>");
    }

    final IgnoreDirection direction = IgnoreDirection.valueOf(label.toUpperCase());
    final List<String> ids = new ArrayList<>();

    if (!message.getMentionedUsers().isEmpty()) {
        message.getMentionedUsers().forEach(u -> ids.add(u.getId()));
    }

    for (final String arg : arguments) {
        if (!arg.startsWith("<@")) {
            ids.add(arg);
        }
    }

    final Configuration cfg = this.hilda.getConfigurationManager().getConfiguration(this.plugin,
            "ignoredusers");
    JsonArray array = cfg.get().getAsJsonArray("users");

    if (array == null) {
        array = new JsonArray();
    }

    for (final String id : ids) {
        if (direction == IgnoreDirection.IGNORE) {
            this.hilda.getCommandManager().addIgnoredUser(id);

            if (!array.contains(new JsonPrimitive(id))) {
                array.add(id);
            }
        }

        if (direction == IgnoreDirection.UNIGNORE) {
            this.hilda.getCommandManager().removeIgnoredUser(id);
            array.remove(new JsonPrimitive(id));
        }
    }

    cfg.get().add("users", array);
    cfg.save();

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, I'm ").append(direction == IgnoreDirection.IGNORE ? "now" : "no longer")
            .append(" ignoring ");
    mb.append(Util.getAsList(this.getPieces(ids)));
    mb.append(".");

    mb.buildAll(SplitPolicy.SPACE).forEach(m -> message.getChannel().sendMessage(m).queue());
}

From source file:ch.jamiete.hilda.moderatortools.commands.IgnoreCommand.java

License:Apache License

@Override
public void execute(final Message message, final String[] arguments, final String label) {
    if (arguments.length == 1 && arguments[0].equalsIgnoreCase("list")) {
        final MessageBuilder mb = new MessageBuilder();
        final List<String> strings = this.hilda.getCommandManager().getIgnoredChannels();
        final List<TextChannel> ignored = new ArrayList<TextChannel>();

        for (final String s : strings) {
            final TextChannel c = message.getGuild().getTextChannelById(s);

            if (c != null) {
                ignored.add(c);/*www.  j a  v a 2s  .  c o m*/
            }
        }

        if (ignored.isEmpty()) {
            this.reply(message, "I'm not ignoring any channels!");
        } else {
            mb.append("I'm currently ignoring ");

            for (final TextChannel c : ignored) {
                mb.append(c.getAsMention());
                mb.append(", ");
            }

            mb.replaceLast(", ", "");
            mb.append(".");
            this.reply(message, mb.build());
        }

        return;
    }

    final IgnoreDirection direction = IgnoreDirection.valueOf(label.toUpperCase());
    final List<TextChannel> channels = new ArrayList<TextChannel>();

    if (arguments.length == 0) {
        channels.add(message.getTextChannel());
    }

    if (!message.getMentionedChannels().isEmpty()) {
        channels.addAll(message.getMentionedChannels());
    }

    final Configuration cfg = this.hilda.getConfigurationManager().getConfiguration(this.plugin,
            "ignore-" + message.getGuild().getId());
    JsonArray array = cfg.get().getAsJsonArray("channels");

    if (array == null) {
        array = new JsonArray();
    }

    for (final TextChannel channel : channels) {
        if (direction == IgnoreDirection.IGNORE) {
            this.hilda.getCommandManager().addIgnoredChannel(channel.getId());

            if (!array.contains(new JsonPrimitive(channel.getId()))) {
                array.add(channel.getId());
            }
        }

        if (direction == IgnoreDirection.UNIGNORE) {
            this.hilda.getCommandManager().removeIgnoredChannel(channel.getId());
            array.remove(new JsonPrimitive(channel.getId()));
        }
    }

    cfg.get().add("channels", array);
    cfg.save();

    final MessageBuilder mb = new MessageBuilder();

    mb.append("OK, I'm ").append(direction == IgnoreDirection.IGNORE ? "now" : "no longer")
            .append(" ignoring ");
    mb.append(Util.getChannelsAsString(channels));
    mb.append(".");

    mb.buildAll().forEach(m -> message.getChannel().sendMessage(m).queue());
}

From source file:cl.niclabs.tscrypto.common.datatypes.BigIntegerBase64TypeAdapter.java

License:Open Source License

@Override
public JsonElement serialize(BigInteger src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(new String(Base64.encodeBase64(src.toByteArray())));
}

From source file:classes.analysis.Analysis.java

License:Open Source License

private static Analysis parseAnalysisGalaxyData(String origin, String emsuser, JsonObject analysisData) {
    JsonParser parser = new JsonParser();
    JsonArray provenance = (JsonArray) parser.parse(analysisData.get("provenance").getAsString());

    //STEP 1. Find the associations between the steps (inputs and outputs)
    HashMap<String, JsonElement> outputs = new HashMap<String, JsonElement>();
    JsonObject stepJSONobject;/*from  w  ww.j  a va2  s .  co m*/
    for (JsonElement step_json : provenance) {
        stepJSONobject = step_json.getAsJsonObject();
        for (JsonElement output : stepJSONobject.getAsJsonArray("outputs")) {
            outputs.put(output.getAsJsonObject().get("id").getAsString(), step_json);
        }

        if ("upload1".equalsIgnoreCase(stepJSONobject.get("tool_id").getAsString())) {
            stepJSONobject.remove("step_type");
            stepJSONobject.add("step_type", new JsonPrimitive("external_source"));
        } else {
            stepJSONobject.add("step_type", new JsonPrimitive("processed_data"));
        }
    }
    for (JsonElement step_json : provenance) {
        stepJSONobject = step_json.getAsJsonObject();
        for (JsonElement input : stepJSONobject.getAsJsonArray("inputs")) {
            String id = input.getAsJsonObject().get("id").getAsString();
            if (outputs.containsKey(id)) {
                if (!"external_source"
                        .equalsIgnoreCase(outputs.get(id).getAsJsonObject().get("step_type").getAsString())) {
                    outputs.get(id).getAsJsonObject().remove("step_type");
                    outputs.get(id).getAsJsonObject().add("step_type", new JsonPrimitive("intermediate_data"));
                }

                if (!stepJSONobject.has("used_data")) {
                    stepJSONobject.add("used_data", new JsonArray());
                }
                ((JsonArray) stepJSONobject.get("used_data")).add(new JsonPrimitive(
                        "STxxxx." + outputs.get(id).getAsJsonObject().get("id").getAsString()));
            }
        }
    }

    //STEP 2. Create the instances for the steps
    ArrayList<NonProcessedData> nonProcessedDataList = new ArrayList<NonProcessedData>();
    ArrayList<ProcessedData> processedDataList = new ArrayList<ProcessedData>();
    for (JsonElement step_json : provenance) {
        stepJSONobject = step_json.getAsJsonObject();
        if ("external_source".equalsIgnoreCase(stepJSONobject.get("step_type").getAsString())) {
            nonProcessedDataList.add(ExternalData.parseStepGalaxyData(stepJSONobject, analysisData, emsuser));
        } else if ("intermediate_data".equalsIgnoreCase(stepJSONobject.get("step_type").getAsString())) {
            nonProcessedDataList
                    .add(IntermediateData.parseStepGalaxyData(stepJSONobject, analysisData, emsuser));
        } else if ("processed_data".equalsIgnoreCase(stepJSONobject.get("step_type").getAsString())) {
            processedDataList.add(ProcessedData.parseStepGalaxyData(stepJSONobject, analysisData, emsuser));
        } else {
            throw new InstantiationError("Unknown step type");
        }
    }

    Collections.sort(nonProcessedDataList);
    Collections.sort(processedDataList);

    //STEP 3. Create the instance of analysis
    Analysis analysis = new Analysis();
    analysis.setAnalysisName(analysisData.get("ems_analysis_name").getAsString());
    analysis.setAnalysisType("Galaxy workflow");
    analysis.setNonProcessedData(nonProcessedDataList.toArray(new NonProcessedData[] {}));
    analysis.setProcessedData(processedDataList.toArray(new ProcessedData[] {}));
    analysis.setTags(new String[] { "imported" });
    analysis.setStatus("pending");

    return analysis;
}

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;//from ww w. java  2  s.  c  o m
    try {
        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:cn.edu.zjnu.acm.judge.util.excel.ExcelUtil.java

License:Apache License

private static JsonElement parseAsJsonElement(Cell cell, FormulaEvaluator evaluator) {
    switch (cell.getCellType()) {
    case NUMERIC:
        if (HSSFDateUtil.isCellDateFormatted(cell)) {
            return new JsonPrimitive(DateFormatterHolder.FORMATTER.format(cell.getDateCellValue().toInstant()));
        } else {//  ww w.  j  a va 2s. c  o m
            return new JsonPrimitive(cell.getNumericCellValue());
        }
    case STRING:
        return new JsonPrimitive(cell.getStringCellValue());
    case FORMULA:
        CellValue cellValue = evaluator.evaluate(cell);
        switch (cellValue.getCellType()) {
        case NUMERIC:
            return new JsonPrimitive(cellValue.getNumberValue());
        case STRING:
            return new JsonPrimitive(cellValue.getStringValue());
        case BLANK:
            return new JsonPrimitive("");
        case BOOLEAN:
            return new JsonPrimitive(cellValue.getBooleanValue());
        case ERROR:
        default:
            return null;
        }
    case BLANK:
        return new JsonPrimitive("");
    case BOOLEAN:
        return new JsonPrimitive(cell.getBooleanCellValue());
    case ERROR:
    default:
        return null;
    }
}

From source file:cn.teamlab.wg.framework.struts2.json.JsonSerializerBuilder.java

License:Apache License

public static GsonBuilder builder() {
    return new GsonBuilder() //
            .disableHtmlEscaping().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override//  ww  w  .  j a  va2  s  . co m
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }
            }).registerTypeAdapter(Date.class, new DateTypeAdapter())
            .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {

                @Override
                public JsonElement serialize(DateTime arg0, Type arg1, JsonSerializationContext arg2) {
                    return new JsonPrimitive(arg0.toString(DateFormatter.SDF_YMDHMS6));
                }
            });
}

From source file:co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler.java

License:Apache License

/**
 *
 * @param externalAuthenticationURIs the list that should be populated with discovered with
 *                                   external auth servers URIs
 * @throws Exception//from   w w w. j  a va2 s. c  o m
 */
private void stopWatchWait(JsonArray externalAuthenticationURIs) throws Exception {
    boolean done = false;
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.start();
    String protocol;
    int port;
    if (configuration.getBoolean(Constants.Security.SSL_ENABLED)) {
        protocol = "https";
        port = configuration.getInt(Constants.Security.AuthenticationServer.SSL_PORT);
    } else {
        protocol = "http";
        port = configuration.getInt(Constants.Security.AUTH_SERVER_BIND_PORT);
    }

    do {
        for (Discoverable d : discoverables) {
            String url = String.format("%s://%s:%d/%s", protocol, d.getSocketAddress().getHostName(), port,
                    GrantAccessToken.Paths.GET_TOKEN);
            externalAuthenticationURIs.add(new JsonPrimitive(url));
            done = true;
        }
        if (!done) {
            TimeUnit.MILLISECONDS.sleep(200);
        }
    } while (!done && stopwatch.elapsedTime(TimeUnit.SECONDS) < 2L);
}