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:com.dmr.project.controller.TransformerHandler.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww .  ja v  a  2s.  c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    String[] area;
    area = request.getParameterValues("area[]");
    Transformers transformersList = new Transformers();
    ResultSet rs = transformersList.getTransformers(area);
    //String transformer = request.getParameter("transformer");
    //        for(int i=0;i < area.length;i++){
    //            System.out.println("ss" + area[i]);
    //        }

    //            Transformers transformersList = new Transformers();
    //            ResultSet rs = transformersList.getData(area);
    //
    JsonObject jsonResponse = new JsonObject();
    JsonArray data = new JsonArray();
    while (rs.next()) {
        JsonArray row = new JsonArray();
        row.add(new JsonPrimitive(rs.getString("location")));
        data.add(row);
    }
    jsonResponse.add("data", data);

    response.setContentType("application/json");
    try (PrintWriter out = response.getWriter()) {

        out.print(jsonResponse);
        out.flush();
    }

    //            }
    //        response.setContentType("text/html;charset=UTF-8");
    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet NewServlet</title>");
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("Output"+area);
    //            out.println(area.length);
    //
    ////            for (int i = 0; i < area.length ; i++) {
    ////                out.println(area[i]);
    ////            }
    ////            while(rs.next ()){
    ////                String temp = rs.getString("location");
    ////                out.println("Location: "+temp);
    ////            }
    //            
    //            out.println("Output"+rs);
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.drguildo.bm.TagsSerializer.java

License:Open Source License

@Override
public JsonElement serialize(Tags src, Type typeOfSrc, JsonSerializationContext context) {
    JsonArray fuckThisShit = new JsonArray();
    for (String tag : src.toList()) {
        fuckThisShit.add(new JsonPrimitive(tag));
    }/*from w  ww  . j  av  a2 s  .  co  m*/
    return fuckThisShit;
}

From source file:com.dubic.scribbles.admin.controllers.UserController.java

@RequestMapping("/chart")
public @ResponseBody JsonObject usersChart(@RequestParam("m") int month) {
    int sqlMonth = month == -1 ? Util.currentMonth() : month;
    String sql = "select DAY(u.create_dt) as daymonth,count(u.id) as count from users u\n"
            + "where MONTH(u.create_dt)=" + (sqlMonth + 1) + "\n" + "group by DAY(u.create_dt)";
    List<Object[]> users = db.getObjectList(sql, new RowMapper<Object[]>() {
        @Override/*from w w  w.  j a  v a  2 s .c om*/
        public Object[] mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Object[] { rs.getInt("daymonth"), rs.getInt("count") };
        }
    });
    JsonObject resp = new JsonObject();
    JsonArray cats = new JsonArray();
    JsonArray data = new JsonArray();
    for (Object[] o : users) {
        cats.add(new JsonPrimitive((Integer) o[0]));
        data.add(new JsonPrimitive((Integer) o[1]));
    }
    resp.add("categories", cats);
    resp.add("data", data);
    resp.addProperty("month", sqlMonth);

    return resp;
}

From source file:com.eclipsesource.connect.serialization.IdTypeAdapter.java

License:Open Source License

@Override
public JsonElement serialize(Id src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(src.toString());
}

From source file:com.edduarte.argus.keyword.KeywordSerializer.java

License:Apache License

@Override
public JsonElement serialize(final Keyword src, final Type typeOfSrc, final JsonSerializationContext context) {
    return new JsonPrimitive(src.originalInput);
}

From source file:com.edu.mum.hbs.restapi.util.LocalTimeConverter.java

License:Open Source License

/**
 * Gson invokes this call-back method during serialization when it encounters a field of the
 * specified type. <p>//  w  w w  .jav  a2 s  .  c  om
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
 * non-trivial field of the {@code src} object. However, you should never invoke it on the
 * {@code src} object itself since that will cause an infinite loop (Gson will call your
 * call-back method again).
 *
 * @param src the object that needs to be converted to Json.
 * @param typeOfSrc the actual type (fully genericized version) of the source object.
 * @return a JsonElement corresponding to the specified object.
 */
@Override
public JsonElement serialize(LocalTime src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(FORMATTER.format(src));
}

From source file:com.ephemeraldreams.gallyshuttle.data.LocalTimeSerializer.java

License:Apache License

@Override
public JsonElement serialize(LocalTime src, Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(FORMATTER.print(src));
}

From source file:com.etermax.conversations.repository.impl.elasticsearch.mapper.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//w w w.ja v  a  2s. c o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java

License:Apache License

public String serializeAsPacketModel() {

    JsonObject model = new JsonObject();
    model.add("protocols", new JsonArray());

    JsonObject fieldEngine = new JsonObject();
    fieldEngine.add("instructions", new JsonArray());
    fieldEngine.add("global_parameters", new JsonObject());
    model.add("field_engine", fieldEngine);

    Map<String, AddressDataBinding> l3Binds = new HashMap<>();

    l3Binds.put("Ether", macDB);
    boolean isIPv4 = protocolSelection.getIpv4Property().get();
    if (isIPv4) {
        l3Binds.put("IP", ipv4DB);
    }/*  w w w . j a va2 s.c  om*/

    l3Binds.entrySet().stream().forEach(entry -> {
        JsonObject proto = new JsonObject();
        String protoID = entry.getKey();
        proto.add("id", new JsonPrimitive(protoID));

        JsonArray fields = new JsonArray();

        AddressDataBinding binding = entry.getValue();
        String srcMode = entry.getValue().getDestination().getModeProperty().get();
        String dstMode = entry.getValue().getSource().getModeProperty().get();

        if (!MODE_TREX_CONFIG.equals(srcMode)) {
            fields.add(buildProtoField("src", binding.getSource().getAddressProperty().getValue()));
        }

        if (!MODE_TREX_CONFIG.equals(dstMode)) {
            fields.add(buildProtoField("dst", binding.getDestination().getAddressProperty().getValue()));
        }

        if (protoID.equals("Ether") && ethernetDB.getOverrideProperty().get()) {
            fields.add(buildProtoField("type", ethernetDB.getTypeProperty().getValue()));
        }
        proto.add("fields", fields);
        model.getAsJsonArray("protocols").add(proto);
        if (!MODE_FIXED.equals(binding.getSource().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getSource().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "src", binding.getSource()));
        }
        if (!MODE_FIXED.equals(binding.getDestination().getModeProperty().get())
                && !MODE_TREX_CONFIG.equals(binding.getDestination().getModeProperty().get())) {
            fieldEngine.getAsJsonArray("instructions")
                    .addAll(buildVMInstructions(protoID, "dst", binding.getDestination()));
        }

    });

    boolean isVLAN = protocolSelection.getTaggedVlanProperty().get();
    String pktLenName = "pkt_len";
    String frameLenghtType = protocolSelection.getFrameLengthType();
    boolean pktSizeChanged = !frameLenghtType.equals("Fixed");
    if (pktSizeChanged) {
        LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
        String operation = PacketBuilderHelper.getOperationFromType(frameLenghtType);
        Integer minLength = Integer.valueOf(protocolSelection.getMinLength()) - 4;
        Integer maxLength = Integer.valueOf(protocolSelection.getMaxLength()) - 4;

        instructionParam.put("init_value", minLength.toString());
        instructionParam.put("max_value", maxLength.toString());
        instructionParam.put("min_value", minLength.toString());

        instructionParam.put("name", pktLenName);
        instructionParam.put("op", operation);
        instructionParam.put("size", "2");
        instructionParam.put("step", "1");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFlowVar", instructionParam));

        instructionParam.clear();
        instructionParam.put("fv_name", pktLenName);
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmTrimPktSize", instructionParam));

        instructionParam.clear();
        instructionParam.put("add_val", isVLAN ? "-18" : "-14");
        instructionParam.put("is_big", "true");
        instructionParam.put("fv_name", pktLenName);
        instructionParam.put("pkt_offset", isVLAN ? "20" : "16");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmWrFlowVar", instructionParam));
    }

    if (isVLAN) {
        JsonObject dot1QProto = new JsonObject();
        dot1QProto.add("id", new JsonPrimitive("Dot1Q"));
        Map<String, String> fieldsMap = new HashMap<>();

        fieldsMap.put("prio", vlanDB.getPriorityProperty().getValue());
        fieldsMap.put("id", vlanDB.getCfiProperty().getValue());
        fieldsMap.put("vlan", vlanDB.getVIdProperty().getValue());

        dot1QProto.add("fields", buildProtoFieldsFromMap(fieldsMap));

        JsonArray protocols = model.getAsJsonArray("protocols");
        if (protocols.size() == 2) {
            JsonElement ipv4 = protocols.get(1);
            protocols.set(1, dot1QProto);
            protocols.add(ipv4);
        } else {
            model.getAsJsonArray("protocols").add(dot1QProto);
        }

        if (vlanDB.getOverrideTPIdProperty().getValue()) {
            JsonArray etherFields = ((JsonObject) model.getAsJsonArray("protocols").get(0)).get("fields")
                    .getAsJsonArray();
            if (etherFields.size() == 3) {
                etherFields.remove(2);
            }
            etherFields.add(buildProtoField("type", vlanDB.getTpIdProperty().getValue()));
        }
    }

    boolean isTCP = protocolSelection.getTcpProperty().get();
    if (isTCP) {
        JsonObject tcpProto = new JsonObject();
        tcpProto.add("id", new JsonPrimitive("TCP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", tcpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", tcpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("chksum", "0x" + tcpProtocolDB.getChecksumProperty().getValue());
        fieldsMap.put("seq", tcpProtocolDB.getSequenceNumberProperty().getValue());
        fieldsMap.put("urgptr", tcpProtocolDB.getUrgentPointerProperty().getValue());
        fieldsMap.put("ack", tcpProtocolDB.getAckNumberProperty().getValue());

        int tcp_flags = 0;
        if (tcpProtocolDB.getUrgProperty().get()) {
            tcp_flags = tcp_flags | (1 << 5);
        }
        if (tcpProtocolDB.getAckProperty().get()) {
            tcp_flags = tcp_flags | (1 << 4);
        }
        if (tcpProtocolDB.getPshProperty().get()) {
            tcp_flags = tcp_flags | (1 << 3);
        }
        if (tcpProtocolDB.getRstProperty().get()) {
            tcp_flags = tcp_flags | (1 << 2);
        }
        if (tcpProtocolDB.getSynProperty().get()) {
            tcp_flags = tcp_flags | (1 << 1);
        }
        if (tcpProtocolDB.getFinProperty().get()) {
            tcp_flags = tcp_flags | 1;
        }
        fieldsMap.put("flags", String.valueOf(tcp_flags));

        tcpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(tcpProto);
    }

    // Field Engine instructions
    String cache_size = "5000";
    if ("Enable".equals(advancedPropertiesDB.getCacheSizeTypeProperty().getValue())) {
        cache_size = advancedPropertiesDB.getCacheValueProperty().getValue();
    }
    fieldEngine.getAsJsonObject("global_parameters").add("cache_size", new JsonPrimitive(cache_size));

    boolean isUDP = protocolSelection.getUdpProperty().get();
    if (isUDP) {
        JsonObject udpProto = new JsonObject();
        udpProto.add("id", new JsonPrimitive("UDP"));

        Map<String, String> fieldsMap = new HashMap<>();
        fieldsMap.put("sport", udpProtocolDB.getSrcPortProperty().getValue());
        fieldsMap.put("dport", udpProtocolDB.getDstPortProperty().getValue());
        fieldsMap.put("len", udpProtocolDB.getLengthProperty().getValue());

        udpProto.add("fields", buildProtoFieldsFromMap(fieldsMap));
        model.getAsJsonArray("protocols").add(udpProto);

        if (pktSizeChanged) {
            LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>();
            instructionParam.put("add_val", isVLAN ? "-38" : "-34");
            instructionParam.put("is_big", "true");
            instructionParam.put("fv_name", pktLenName);
            instructionParam.put("pkt_offset", isVLAN ? "42" : "38");
            fieldEngine.getAsJsonArray("instructions")
                    .add(buildInstruction("STLVmWrFlowVar", instructionParam));
        }
    }

    if (ipv4DB.hasInstructions() || pktSizeChanged) {
        Map<String, String> flowWrVarParameters = new HashMap<>();
        flowWrVarParameters.put("offset", "IP");
        fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFixIpv4", flowWrVarParameters));
    }

    return model.toString();
}

From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java

License:Apache License

private JsonElement buildInstruction(String instructionId, Map<String, String> parameters) {
    JsonObject instruction = new JsonObject();
    instruction.add("id", new JsonPrimitive(instructionId));

    JsonObject params = new JsonObject();
    parameters.entrySet().stream().forEach(entry -> {
        params.add(entry.getKey(), new JsonPrimitive(entry.getValue()));
    });/*  w  w  w.jav a  2  s  .c  om*/
    instruction.add("parameters", params);
    return instruction;
}