@Override public JsonElement serialize( WrappedStack wrappedStack, Type type, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gsonWrappedStack = new Gson(); jsonWrappedStack.addProperty("className", wrappedStack.className); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, ItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof EnergyStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, EnergyStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, FluidStack.class)); } return jsonWrappedStack; }
@Override public JsonElement serialize( OutputDataRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (cellRaw.png != null) { jsonObject.addProperty("image/png", cellRaw.png); } if (cellRaw.html != null) { final JsonElement html = gson.toJsonTree(cellRaw.html); jsonObject.add("text/html", html); } if (cellRaw.svg != null) { final JsonElement svg = gson.toJsonTree(cellRaw.svg); jsonObject.add("image/svg+xml", svg); } if (cellRaw.jpeg != null) { final JsonElement jpeg = gson.toJsonTree(cellRaw.jpeg); jsonObject.add("image/jpeg", jpeg); } if (cellRaw.latex != null) { final JsonElement latex = gson.toJsonTree(cellRaw.latex); jsonObject.add("text/latex", latex); } if (cellRaw.text != null) { final JsonElement text = gson.toJsonTree(cellRaw.text); jsonObject.add("text/plain", text); } return jsonObject; }
@Test public void testEntityMarshall() throws Exception { Entity entity = Entity.builder() .content(sampleContent1()) .attribute( Attribute.builder("testId3") .value(StringExp.of("aaa")) .value(StringExp.of("bbbb")) .value(StringExp.of("cccc")) .build()) .attribute( Attribute.builder("testId4") .value(StringExp.of("zzzz")) .value(StringExp.of("aaaa")) .value(StringExp.of("cccc")) .build()) .build(); Category a = Category.builder() .category(Categories.SUBJECT_ACCESS) .entity( Entity.builder() .attribute(Attribute.builder("testId1").value(EntityExp.of(entity)).build()) .build()) .build(); JsonElement o = json.toJsonTree(a); Category b = json.fromJson(o, Category.class); assertEquals(a, b); }
@Override public void updateCommand(String deviceId, DeviceCommand command) throws HiveException { if (command == null) { throw new HiveClientException("Command cannot be null!", BAD_REQUEST.getStatusCode()); } if (command.getId() == null) { throw new HiveClientException("Command id cannot be null!", BAD_REQUEST.getStatusCode()); } logger.debug( "DeviceCommand: update requested for device id {] and command: id {}, flags {}, status {}, " + " result {}", deviceId, command.getId(), command.getFlags(), command.getStatus(), command.getResult()); JsonObject request = new JsonObject(); request.addProperty("action", "command/update"); request.addProperty("deviceGuid", deviceId); request.addProperty("commandId", command.getId()); Gson gson = GsonFactory.createGson(COMMAND_UPDATE_FROM_DEVICE); request.add("command", gson.toJsonTree(command)); websocketAgent.getWebsocketConnector().sendMessage(request); logger.debug( "DeviceCommand: update request proceed successfully for device id {] and command: id {}, " + "flags {}, status {}, result {}", deviceId, command.getId(), command.getFlags(), command.getStatus(), command.getResult()); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { SubjectDAO subdao = new SubjectDAO(); DatastreamDAO dstreamDao = new DatastreamDAO(); List<JsonSubject> jsubList = new ArrayList<JsonSubject>(); List<Subject> subList = new ArrayList<Subject>(); String loginID = "leoncool"; if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) { loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid); } UserDAO userDao = new UserDAO(); if (!userDao.existLogin(loginID)) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null); return; } if (request.getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects) != null && request .getParameter(AllConstants.api_entryPoints.request_api_onlyParentSubjects) .equalsIgnoreCase(AllConstants.api_entryPoints.request_api_true)) { subList = subdao.findOnlyParentSubjectsByLoginID(loginID); } else { subList = subdao.findSubjectsByLoginID(loginID); } DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil(); for (Subject sub : subList) { if (sub.getVisibleSet() != null && sub.getVisibleSet().equalsIgnoreCase(AllConstants.ProgramConts.visibleSet_PUBLIC)) { jsubList.add(dbtoJUtil.convert_a_Subject(sub)); } } System.out.println(jsubList.size()); Gson gson = new Gson(); JsonElement je = gson.toJsonTree(jsubList); JsonObject jo = new JsonObject(); jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed); jo.add("subject_list", je); JsonWriter jwriter = new JsonWriter(response.getWriter()); // if (request.getParameter("callback") != null) { // System.out.println("using callback"); // out.print(request.getParameter("callback")+"("+ gson.toJson(jo) + ");"); // } else { // gson.toJson(jo, jwriter); // jwriter.close(); // } gson.toJson(jo, jwriter); jwriter.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { out.close(); } }
/** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. * * <p> * * <p>In the implementation of this call-back method, you should consider invoking {@link * com.google.gson.JsonSerializationContext#serialize(Object, java.lang.reflect.Type)} method to * create JsonElements for any non-trivial field of the {@code wrappedStack} object. However, you * should never invoke it on the {@code wrappedStack} object itself since that will cause an * infinite loop (Gson will call your call-back method again). * * @param wrappedStack the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @param context * @return a JsonElement corresponding to the specified object. */ @Override public JsonElement serialize( WrappedStack wrappedStack, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gson = new Gson(); jsonWrappedStack.addProperty("type", wrappedStack.objectType); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { JsonItemStack jsonItemStack = new JsonItemStack(); jsonItemStack.itemName = Item.itemRegistry.getNameForObject(((ItemStack) wrappedStack.wrappedStack).getItem()); jsonItemStack.itemDamage = ((ItemStack) wrappedStack.wrappedStack).getItemDamage(); if (((ItemStack) wrappedStack.wrappedStack).stackTagCompound != null) { jsonItemStack.itemNBTTagCompound = ((ItemStack) wrappedStack.wrappedStack).stackTagCompound; } jsonWrappedStack.add( "objectData", JsonItemStack.jsonSerializer.toJsonTree(jsonItemStack, JsonItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "objectData", gson.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { JsonFluidStack jsonFluidStack = new JsonFluidStack((FluidStack) wrappedStack.wrappedStack); jsonWrappedStack.add( "objectData", JsonFluidStack.jsonSerializer.toJsonTree(jsonFluidStack, JsonFluidStack.class)); } return jsonWrappedStack; }
/** * Calls the Algorithmia API for a given input. Attempts to automatically serialize the input to * JSON. * * @param input algorithm input, will automatically be converted into JSON * @return algorithm result (AlgoSuccess or AlgoFailure) * @throws APIException if there is a problem communication with the Algorithmia API. */ public AlgoResponse pipe(Object input) throws APIException { if (input instanceof String) { return pipeRequest((String) input, ContentType.Text); } else if (input instanceof byte[]) { return pipeBinaryRequest((byte[]) input); } else { return pipeRequest(gson.toJsonTree(input).toString(), ContentType.Json); } }
public static synchronized JsonElement toJsonTree(Object obj) { JsonElement jsonString = null; try { jsonString = gson.toJsonTree(obj); } catch (Exception e) { _logger.error("An Exception occured while get JSON Element from any Object : ", e); } return jsonString; }
@Override public JsonElement serialize( Pair<Long, Long> src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) { JsonArray array = new JsonArray(); if (src.first() != null) { array.add(s_gson.toJsonTree(src.first())); } else { array.add(new JsonNull()); } if (src.second() != null) { array.add(s_gson.toJsonTree(src.second())); } else { array.add(new JsonNull()); } return array; }
@Override public JsonElement serialize( IpnbCellRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("cell_type", cellRaw.cell_type); if ("code".equals(cellRaw.cell_type)) { final Integer count = cellRaw.execution_count; if (count == null) { jsonObject.add("execution_count", JsonNull.INSTANCE); } else { jsonObject.addProperty("execution_count", count); } } if (cellRaw.metadata != null) { final JsonElement metadata = gson.toJsonTree(cellRaw.metadata); jsonObject.add("metadata", metadata); } if (cellRaw.level != null) { jsonObject.addProperty("level", cellRaw.level); } if (cellRaw.outputs != null) { final JsonElement outputs = gson.toJsonTree(cellRaw.outputs); jsonObject.add("outputs", outputs); } if (cellRaw.source != null) { final JsonElement source = gson.toJsonTree(cellRaw.source); jsonObject.add("source", source); } if (cellRaw.input != null) { final JsonElement input = gson.toJsonTree(cellRaw.input); jsonObject.add("input", input); } if (cellRaw.language != null) { jsonObject.addProperty("language", cellRaw.language); } if (cellRaw.prompt_number != null) { jsonObject.addProperty("prompt_number", cellRaw.prompt_number); } return jsonObject; }
public static void main(String args[]) { Gson gson = new Gson(); DataMarketDAO dmDao = new DataMarketDAO(); DataMarket dm = dmDao.getDataMarketByID(1); dm.setDatastream(null); JsonObject jo = new JsonObject(); jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed); JsonElement jelement = gson.toJsonTree(dm); jo.add("data_market", jelement); System.out.println(gson.toJson(jo)); }
@Override public JsonElement serialize( IpnbFileRaw fileRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (fileRaw.worksheets != null) { final JsonElement worksheets = gson.toJsonTree(fileRaw.worksheets); jsonObject.add("worksheets", worksheets); } if (fileRaw.cells != null) { final JsonElement cells = gson.toJsonTree(fileRaw.cells); jsonObject.add("cells", cells); } final JsonElement metadata = gson.toJsonTree(fileRaw.metadata); jsonObject.add("metadata", metadata); jsonObject.addProperty("nbformat", fileRaw.nbformat); jsonObject.addProperty("nbformat_minor", fileRaw.nbformat_minor); return jsonObject; }
/** * Generate a JSON that reflects the generated Ball Draw object. It makes a regular serialization * of the object vars and adds an extra field, which is ball draw size. Ball draw size is * generated from the list size and is injected on the final JSON. * * @param pool Pool max value of the ball draw * @param selection Number of values of the ball draw * @param drawAlgorithm Algorithm of the ball draw * @return - JSON of the generated ball draw, as string. */ private JsonElement generateJson( int pool, int selection, BallDrawAlgorithmInterface.DrawAlgorithm drawAlgorithm) { ManualBallDraw manualGenerator = new ManualBallDraw(); BallDraw newDraw = manualGenerator.getBallDraw(pool, selection, drawAlgorithm); Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss zzz").create(); JsonElement jsonElement = gson.toJsonTree(newDraw); jsonElement.getAsJsonObject().addProperty("size", newDraw.getDraw().size()); return jsonElement; }
@Override public JsonElement serialize( WrappedStack wrappedStack, Type type, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gsonWrappedStack = new Gson(); jsonWrappedStack.addProperty("className", wrappedStack.className); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { JsonItemStack jsonItemStack = new JsonItemStack(); jsonItemStack.itemID = ((ItemStack) wrappedStack.wrappedStack).itemID; jsonItemStack.itemDamage = ((ItemStack) wrappedStack.wrappedStack).getItemDamage(); jsonItemStack.stackSize = ((ItemStack) wrappedStack.wrappedStack).stackSize; if (((ItemStack) wrappedStack.wrappedStack).stackTagCompound != null) { try { jsonItemStack.compressedStackTagCompound = CompressedStreamTools.compress( ((ItemStack) wrappedStack.wrappedStack).stackTagCompound); } catch (IOException e) { e.printStackTrace(); } } jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(jsonItemStack, JsonItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof EnergyStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, EnergyStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, FluidStack.class)); } return jsonWrappedStack; }
@SuppressLint("WorldReadableFiles") /** Writes selected course(s) to json. */ public void write(String major, String campus, String term, String course, String section) { TrackedCourse in = new TrackedCourse(major, campus, term, course, section); Gson gson = new Gson(); JsonElement json = gson.toJsonTree(in); try { File file = new File(getFilesDir(), "RUTracker.json"); // String contextA=getApplicationContext().getFilesDir().getAbsolutePath(); Testing file // directory output RandomAccessFile raf = new RandomAccessFile( new File(getApplicationContext().getFilesDir(), "RUTracker.json"), "rw"); if (raf.length() == 0) { raf.writeBytes("[" + json.toString() + "]"); } else { raf.setLength(file.length() - 1); raf.seek(file.length()); raf.writeBytes("," + json.toString() + "]"); } raf.close(); /* FileOutputStream fos= openFileOutput("tracker.json", Context.MODE_APPEND | Context.MODE_WORLD_READABLE); fos.write(json.toString().getBytes()); fos.close(); */ /* Writes to sd card. Not usable on all devices due to varying file structures. String storageState = Environment.getExternalStorageState(); if (storageState.equals(Environment.MEDIA_MOUNTED)) { //Properly format json table File file = new File(getExternalFilesDir(null), "RUTracker.json"); RandomAccessFile raf = new RandomAccessFile(file,"rw"); raf.close(); } */ } catch (Exception e) { e.printStackTrace(); } }
@Override public JsonElement serialize( List<PortConfig> src, Type typeOfSrc, JsonSerializationContext context) { if (src.size() == 0) { return new JsonNull(); } JsonArray array = new JsonArray(); for (PortConfig pc : src) { array.add(s_gson.toJsonTree(pc)); } return array; }
protected JsonObject parseData( Cursor cursor, String[] projection, Map<String, CursorCell<?>> projectionMap) { JsonObject data = new JsonObject(); for (String key : projection) { CursorCell<?> cursorCell = projectionMap.get(key); if (cursorCell != null) { Object value = cursorCell.getData(cursor, key); if (value != null) { data.add(key, gson.toJsonTree(value)); } } } return data; }
private void kirimDataAjaxViewDetail(HttpServletResponse res, String iD) { try { // kirim data ajax Gson gson = new Gson(); daoMasterKaryawan dMp = new daoMasterKaryawan(); JsonElement jE = gson.toJsonTree(dMp.tampilDetilDataKaryawan(iD)); // JsonArray jA = jE.getAsJsonArray(); JsonObject jO = new JsonObject(); jO.add("detailview", jE); res.setContentType("application/json"); res.getWriter().print(jO); } catch (IOException ex) { Logger.getLogger(payrollData.class.getName()).log(Level.SEVERE, null, ex); } }
@Override protected ModelInterpreter<T> getModelInterpreter(T model) { Gson gson = new Gson(); JsonObject jsonObject = gson.toJsonTree(model).getAsJsonObject(); return propertyName -> { String value = ""; JsonElement propertyValue = jsonObject.get(propertyName); if (propertyValue != null) { value = propertyValue.getAsString(); } return value; }; }
/** * Compares the mapping fixture <-> object, ignoring NULL fields This is useful to prevent issues * with entities such as "Image" in which width and height are not always present, and they result * in null values in the Image object * * @param fixture The JSON to test against * @param model The object to be serialized */ private <T> void compareJSONWithoutNulls(String fixture, T model) { JsonParser parser = new JsonParser(); // Parsing fixture twice gets rid of nulls JsonElement fixtureJsonElement = parser.parse(fixture); String fixtureWithoutNulls = mGson.toJson(fixtureJsonElement); fixtureJsonElement = parser.parse(fixtureWithoutNulls); JsonElement modelJsonElement = mGson.toJsonTree(model); // We compare JsonElements from fixture // with the one created from model. If they're different // it means the model is borked assertEquals(fixtureJsonElement, modelJsonElement); }
@Override public DeviceCommand insertCommand( String guid, DeviceCommand command, HiveMessageHandler<DeviceCommand> commandUpdatesHandler) throws HiveException { if (command == null) { throw new HiveClientException("Command cannot be null!", BAD_REQUEST.getStatusCode()); } logger.debug( "DeviceCommand: insert requested for device id {] and command: command {}, parameters {}, " + "lifetime {}, flags {}", guid, command.getCommand(), command.getParameters(), command.getLifetime(), command.getFlags()); JsonObject request = new JsonObject(); request.addProperty("action", "command/insert"); request.addProperty("deviceGuid", guid); Gson gson = GsonFactory.createGson(COMMAND_FROM_CLIENT); request.add("command", gson.toJsonTree(command)); DeviceCommand toReturn = websocketAgent .getWebsocketConnector() .sendMessage(request, "command", DeviceCommand.class, COMMAND_TO_CLIENT); if (commandUpdatesHandler != null) { websocketAgent.addCommandUpdateSubscription(toReturn.getId(), guid, commandUpdatesHandler); } logger.debug( "DeviceCommand: insert request proceed successfully for device id {] and command: command {}, " + "parameters {}, lifetime {}, flags {}. Result command id {}, timestamp {}, userId {}", guid, command.getCommand(), command.getParameters(), command.getLifetime(), command.getFlags(), toReturn.getId(), toReturn.getTimestamp(), toReturn.getUserId()); return toReturn; }
/** {@inheritDoc} */ public void writeTo( Object object, Class<?> type, Type genericType, java.lang.annotation.Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { JsonRootElement jsonRootElement = object.getClass().getAnnotation(JsonRootElement.class); final OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8); try { if (jsonRootElement.value().length() > 0) { // System.out.println(">>> " + object); JsonElement element = gson.toJsonTree(object); JsonObject json = new JsonObject(); json.add(jsonRootElement.value(), element); // System.out.println(">>> " + json); writer.write(json.toString()); } else { gson.toJson(object, genericType, writer); } } finally { writer.close(); } /* try { final Type jsonType; if (type.equals(genericType)) { jsonType = type; } else { jsonType = genericType; } new Gson().toJson(object, jsonType, writer); } finally { writer.close(); } */ }
@Override public void writeTo( T entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Gson gson = createGson(annotations); JsonElement jsonElement = gson.toJsonTree(entity); Writer writer = null; try { writer = new OutputStreamWriter(entityStream, Charset.forName(UTF8)); gson.toJson(jsonElement, writer); } finally { if (writer != null) { writer.flush(); } } }
private static JsonElement dumpConfig(Table<String, String, IConfigPropertyHolder> properties) { JsonObject result = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().create(); for (Map.Entry<String, Map<String, IConfigPropertyHolder>> category : properties.rowMap().entrySet()) { JsonObject categoryNode = new JsonObject(); for (Map.Entry<String, IConfigPropertyHolder> property : category.getValue().entrySet()) { JsonObject propertyNode = new JsonObject(); IConfigPropertyHolder propertyHolder = property.getValue(); final String comment = propertyHolder.comment(); if (!Strings.isNullOrEmpty(comment)) propertyNode.addProperty(COMMENT_TAG, comment); try { Object value = propertyHolder.getValue(); JsonElement serialized = gson.toJsonTree(value); propertyNode.add(VALUE_TAG, serialized); } catch (Exception e) { Log.warn( e, "Failed to serialize property %s:%s", propertyHolder.category(), propertyHolder.name()); } categoryNode.add(property.getKey(), propertyNode); } result.add(category.getKey(), categoryNode); } return result; }
@Override public JsonElement serialize( CellOutputRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (cellRaw.ename != null) { jsonObject.addProperty("ename", cellRaw.ename); } if (cellRaw.name != null) { jsonObject.addProperty("name", cellRaw.name); } if (cellRaw.evalue != null) { jsonObject.addProperty("evalue", cellRaw.evalue); } if (cellRaw.data != null) { final JsonElement data = gson.toJsonTree(cellRaw.data); jsonObject.add("data", data); } if (cellRaw.execution_count != null) { jsonObject.addProperty("execution_count", cellRaw.execution_count); } if (cellRaw.png != null) { jsonObject.addProperty("png", cellRaw.png); } if (cellRaw.stream != null) { jsonObject.addProperty("stream", cellRaw.stream); } if (cellRaw.jpeg != null) { jsonObject.addProperty("jpeg", cellRaw.jpeg); } if (cellRaw.html != null) { final JsonElement html = gson.toJsonTree(cellRaw.html); jsonObject.add("html", html); } if (cellRaw.latex != null) { final JsonElement latex = gson.toJsonTree(cellRaw.latex); jsonObject.add("latex", latex); } if (cellRaw.svg != null) { final JsonElement svg = gson.toJsonTree(cellRaw.svg); jsonObject.add("svg", svg); } if (cellRaw.prompt_number != null) { jsonObject.addProperty("prompt_number", cellRaw.prompt_number); } if (cellRaw.traceback != null) { final JsonElement traceback = gson.toJsonTree(cellRaw.traceback); jsonObject.add("traceback", traceback); } if (cellRaw.metadata != null) { final JsonElement metadata = gson.toJsonTree(cellRaw.metadata); jsonObject.add("metadata", metadata); } if (cellRaw.output_type != null) { jsonObject.addProperty("output_type", cellRaw.output_type); } if (cellRaw.text != null) { final JsonElement text = gson.toJsonTree(cellRaw.text); jsonObject.add("text", text); } return jsonObject; }
/** Serializes the MultiLongWatermark into a JsonElement. */ @Override public JsonElement toJson() { return GSON.toJsonTree(this); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); // PrintWriter out = response.getWriter(); OutputStream outStream = null; try { long start = 0; long end = 0; String blockid = null; try { if (request.getParameter(AllConstants.api_entryPoints.request_api_start) != null) { start = Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_start)); } if (request.getParameter(AllConstants.api_entryPoints.request_api_end) != null) { end = Long.parseLong(request.getParameter(AllConstants.api_entryPoints.request_api_end)); } if (request.getParameter(AllConstants.api_entryPoints.request_api_blockid) != null) { blockid = request.getParameter(AllConstants.api_entryPoints.request_api_blockid); if (blockid.length() < 5) {} } } catch (Exception ex) { ex.printStackTrace(); } String loginID = "leoncool"; if (request.getParameter(AllConstants.api_entryPoints.request_api_loginid) != null) { loginID = request.getParameter(AllConstants.api_entryPoints.request_api_loginid); } UserDAO userDao = new UserDAO(); if (!userDao.existLogin(loginID)) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Unauthorized_Access, null, null); return; } SubjectDAO subjDao = new SubjectDAO(); Subject subject = (Subject) subjDao.findHealthSubject(loginID); // Retreive if (subject == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.SYSTEM_ERROR_NO_DEFAULT_HEALTH_SUBJECT, null, null); return; } String streamID = ServerUtil.getHealthStreamID(ServletPath(request)); DatastreamDAO dstreamDao = new DatastreamDAO(); DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil(); Datastream datastream = dstreamDao.getDatastream(streamID, true, false); if (blockid != null && dstreamDao.getDatastreamBlock(blockid) == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_Datablock_ID, null, blockid); return; } if (datastream == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Unknown_StreamID, null, streamID); return; } HashMap<String, String> mapUnits = new HashMap<String, String>(); HashMap<String, String> allUnits = new HashMap<String, String>(); if (request.getParameter(AllConstants.api_entryPoints.request_api_unit_id) != null && request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).length() > 0) { String[] unitids = request.getParameter(AllConstants.api_entryPoints.request_api_unit_id).split(","); System.out.println("unitids:size:" + unitids.length); allUnits = dbtoJUtil.ToDatastreamUnitsMap(datastream); System.out.println("units size:" + datastream.getDatastreamUnitsList().size()); for (String id : unitids) { if (id.length() < 3) { // error return; } else { if (allUnits.get(id) == null) { // error System.out.println("cannot find id" + id + ""); return; } else { mapUnits.put(id, id); } } } } System.out.println("mapUnits.size():" + mapUnits.size() + ", " + mapUnits); Gson gson = new Gson(); int debug = 1; if (debug == 1) { System.out.println("debuging.....going to hbase"); HBaseDatapointDAO diDao = new HBaseDatapointDAO(); System.out.println("datastreamID:" + datastream.getStreamId()); HBaseDataImport hbaseexport = null; try { hbaseexport = diDao.exportDatapoints(streamID, start, end, blockid, mapUnits, null, null); } catch (ErrorCodeException ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Internal_Fault, null, null); return; } catch (Throwable ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Internal_Fault, null, null); return; } if (hbaseexport != null) { hbaseexport.setUnits_list( dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list()); } else { hbaseexport = new HBaseDataImport(); hbaseexport.setBlock_id(blockid); hbaseexport.setData_points(new ArrayList<JsonDataPoints>()); hbaseexport.setDatastream_id(streamID); hbaseexport.setUnits_list( dbtoJUtil.convertDatastream(datastream, mapUnits).getUnits_list()); // hbaseexport.setDeviceid(streamID); } outStream = null; boolean iftoZip = true; String encodings = request.getHeader("Accept-Encoding"); if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) { // Go with GZIP response.setHeader("Content-Encoding", "gzip"); outStream = new GZIPOutputStream(response.getOutputStream()); } else { outStream = response.getOutputStream(); } response.setHeader("Vary", "Accept-Encoding"); Date timerStart = new Date(); JsonElement je = gson.toJsonTree(hbaseexport); JsonObject jo = new JsonObject(); jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed); jo.add("datapoints_list", je); OutputStreamWriter osWriter = new OutputStreamWriter(outStream); JsonWriter jwriter = new JsonWriter(osWriter); String callbackStr = null; if (request.getParameter(AllConstants.api_entryPoints.requset_api_callback) != null) { callbackStr = request.getParameter(AllConstants.api_entryPoints.requset_api_callback); osWriter.append(callbackStr + "("); } gson.toJson(jo, jwriter); if (callbackStr != null) { osWriter.append(");"); } jwriter.close(); Date timerEnd = new Date(); System.out.println( "Json Time takes:" + (timerEnd.getTime() - timerStart.getTime()) / (1000.00) + "seconds"); osWriter.close(); outStream.close(); } else { String encodings = request.getHeader("Accept-Encoding"); boolean iftoZip = true; if (encodings != null && encodings.indexOf("gzip") != -1 && iftoZip == true) { // Go with GZIP response.setHeader("Content-Encoding", "gzip"); outStream = new GZIPOutputStream(response.getOutputStream()); } else { outStream = response.getOutputStream(); } response.setHeader("Vary", "Accept-Encoding"); File inputFile = new File("E:/IC_Dropbox/Dropbox/java/healthbook/sample_data/download.txt"); // File inputFile = new // File("F:/Dropbox/Dropbox/java/healthbook/sample_data/download.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); String inputLine; while ((inputLine = reader.readLine()) != null) { outStream.write(inputLine.getBytes()); // out.print(inputLine); } outStream.close(); } } catch (Exception ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Internal_Fault, null, null); return; } finally { System.out.println("running finally"); // out.close(); if (outStream != null) { outStream.close(); } } }
/* limitBawah dan limitAtas difungsikan pada query limit x,x */ private void kirimDataAjax( HttpServletResponse response, int LimitBawah, int LimitAtas, com.ari.prasetiyo.domain.domainMasterPelamarAll dMA) { try { Gson gson = new Gson(); /* Membuat Paging */ String sql; int jumlahRow = 0; /* pagging end */ /* Data table */ daoPayrollData dao = new daoPayrollData(); JsonElement element = null; com.ari.prasetiyo.dao.daoQueryAll daoQueryAll = new com.ari.prasetiyo.dao.daoQueryAll(); // logika convert status pelamar dengan value null / 4 menjadi kosong ('') if (dMA.getfStatPlmr() == null || dMA.getfStatPlmr().equals("null") || dMA.getfStatPlmr().equals("4")) { dMA.setfStatPlmr(""); } // filter jika period, date, dan status pelamar ada // 4 = filter status pelamar untuk data all // 5 = filter status pelamar untuk data all juga // ( !dMA.getfStatPlmr().equals("4") && !dMA.getfStatPlmr().equals("null") ; if (dMA.isLanjut() && dMA.getfPeriodeCreate1() != null) { sql = " select count(dg.id_gaji) as id " + "from data_gaji dg inner join payroll_master_karyawan mk on dg.id_karyawan = mk.id_karyawan inner join payroll_master_karyawan_detail mkd on mk.id_karyawan = mkd.id_karyawan " + "where mk.id_karyawan like ? and mk.status_karyawan like ? and mk.nama like ? and mkd.jabatan like ? " + "and mkd.area like ? and mkd.sts_pegawai like ? " + "and date_format(dg.tanggal_created, '%Y-%m') = date_format(?, '%Y-%m')"; jumlahRow = daoQueryAll.jumlahRow(sql, dMA, "filterPresensiAbsensi"); } // filter jika tanpa date else if (dMA.isLanjut() && dMA.getfPeriodeCreate1() == null) { sql = " select count(dg.id_gaji) as id " + "from data_gaji dg inner join payroll_master_karyawan mk on dg.id_karyawan = mk.id_karyawan inner join payroll_master_karyawan_detail mkd on mk.id_karyawan = mkd.id_karyawan " + "where mk.id_karyawan like ? and mk.status_karyawan like ? and mk.nama like ? and mkd.jabatan like ? " + "and mkd.area like ? and mkd.sts_pegawai like ? "; jumlahRow = daoQueryAll.jumlahRow(sql, dMA, "filterKaryawan"); } // data new gaji else if (dMA.getfPilihan().equals("22")) { sql = "select count(mk.id_karyawan) as id from payroll_master_karyawan mk " + "inner join presensi_absensi pa on date_format(pa.tanggal_dibuat, '%Y-%m') = date_format(now(), '%Y-%m') and mk.id_karyawan = pa.id_karyawan "; jumlahRow = daoQueryAll.jumlahRow(sql, dMA, "filterPresensiAbsensi"); element = gson.toJsonTree( dao.tampilDataNew(LimitBawah, LimitAtas, dMA), new TypeToken<List<domainPresensiAbsensi>>() {}.getType()); } else { sql = "select count(id_karyawan) as id from data_gaji where date_format(tanggal_created, '%Y-%m') = date_format(now(), '%Y-%m')"; jumlahRow = daoQueryAll.jumlahRow(sql, dMA, "filterPresensiAbsensi"); // element = gson.toJsonTree(dao.tampilData(LimitBawah, LimitAtas, dMA), new // TypeToken<List<domainPresensiAbsensi>>() {}.getType()); } // bukan data new if (!dMA.getfPilihan().equals("22")) { element = gson.toJsonTree( dao.tampilData(LimitBawah, LimitAtas, dMA), new TypeToken<List<domainPresensiAbsensi>>() {}.getType()); } // kirim data dalam format JSON // String PagingData = "[{'jumlahRow':'"+ jumlahRow + "'}]"; JsonElement PagingData = gson.toJsonTree(jumlahRow); // jika hanya satu data saja yang akan dikirim jsonArray langsung // response.getWriter().print(jsonArray); JsonArray jsonArray = element.getAsJsonArray(); JsonObject myObj = new JsonObject(); // data yang akan ditampilkan di aplikasi myObj.add("dataTable", jsonArray); // jumlah row pada database myObj.add("dataIndependent", PagingData); // out.println(myObj.toString()); response.setContentType("application/json"); response.getWriter().print(myObj); // response.getWriter().print(PagingData); } catch (IOException ex) { Logger.getLogger(payrollData.class.getName()).log(Level.SEVERE, null, ex); } }
/** * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("action") != null) { List<Personas> personas = new ArrayList<>(); String action = (String) request.getParameter("action"); Gson gson = new Gson(); response.setContentType("application/json"); switch (action) { case "administrador": try { // Fetch Data from User Table String a = "Administrador"; personas = crud.getPersonas(a); // Convert Java Object to Json JsonElement element = gson.toJsonTree(personas, new TypeToken<List<Personas>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); String listData = jsonArray.toString(); // Return Json in the format required by jTable plugin listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}"; response.getWriter().print(listData); } catch (ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getMessage() + "}"; response.getWriter().print(error); ex.printStackTrace(); } break; case "dueno": try { // Fetch Data from User Table String a = "Propietario"; personas = crud.getPersonas(a); // Convert Java Object to Json JsonElement element = gson.toJsonTree(personas, new TypeToken<List<Personas>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); String listData = jsonArray.toString(); // Return Json in the format required by jTable plugin listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}"; response.getWriter().print(listData); } catch (ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getMessage() + "}"; response.getWriter().print(error); ex.printStackTrace(); } break; case "vendedor": try { // Fetch Data from User Table String a = "Vendedor"; personas = crud.getPersonas(a); // Convert Java Object to Json JsonElement element = gson.toJsonTree(personas, new TypeToken<List<Personas>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); String listData = jsonArray.toString(); // Return Json in the format required by jTable plugin listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}"; response.getWriter().print(listData); } catch (ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getMessage() + "}"; response.getWriter().print(error); ex.printStackTrace(); } break; case "list": try { // Fetch Data from User Table personas = crud.getPersonas(); // Convert Java Object to Json JsonElement element = gson.toJsonTree(personas, new TypeToken<List<Personas>>() {}.getType()); JsonArray jsonArray = element.getAsJsonArray(); String listData = jsonArray.toString(); // Return Json in the format required by jTable plugin listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}"; response.getWriter().print(listData); } catch (ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getMessage() + "}"; response.getWriter().print(error); ex.printStackTrace(); } break; case "create": case "update": Personas persona = new Personas(); if (request.getParameter("Identificacion") != null) { int Identificacion = Integer.parseInt(request.getParameter("Identificacion")); persona.setIdentificacion(Identificacion); } if (request.getParameter("Nombre") != null) { String Nombre = (String) request.getParameter("Nombre"); persona.setNombre(Nombre); } if (request.getParameter("Apellido") != null) { String Apellido = (String) request.getParameter("Apellido"); persona.setApellido(Apellido); } if (request.getParameter("Celular") != null) { String Celular = (String) request.getParameter("Celular"); persona.setCelular(Celular); } if (request.getParameter("Telefono") != null) { String Telefono = (String) request.getParameter("Telefono"); persona.setTelefono(Telefono); } if (request.getParameter("Correo") != null) { String Correo = (String) request.getParameter("Correo"); persona.setCorreo(Correo); } if (request.getParameter("Usuario") != null) { String Usuario = (String) request.getParameter("Usuario"); persona.setUsuario(Usuario); } if (request.getParameter("Contrasena") != null) { String Contrasena = (String) request.getParameter("Contrasena"); persona.setContrasena(Contrasena); } if (request.getParameter("Rol") != null) { String Rol = (String) request.getParameter("Rol"); persona.setRol(Rol); } try { switch (action) { case "create": { // Create new record crud.AgregarPersona(persona); personas.add(persona); // Convert Java Object to Json String json = gson.toJson(persona); // Return Json in the format required by jTable plugin String listData = "{\"Result\":\"OK\",\"Record\":" + json + "}"; response.getWriter().print(listData); break; } case "update": { // Update existing record crud.ModificarPersona(persona); String listData = "{\"Result\":\"OK\"}"; response.getWriter().print(listData); break; } } } catch (ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + Arrays.toString(ex.getStackTrace()) + "}"; response.getWriter().print(error); } break; case "delete": // Delete record try { if (request.getParameter("Identificacion") != null) { String IdInmueble = (String) request.getParameter("Identificacion"); crud.EliminarPersona(Integer.parseInt(IdInmueble)); String listData = "{\"Result\":\"OK\"}"; response.getWriter().print(listData); } } catch (NumberFormatException | ClassNotFoundException | SQLException | IOException ex) { String error = "{\"Result\":\"ERROR\",\"Message\":" + Arrays.toString(ex.getStackTrace()) + "}"; response.getWriter().print(error); } break; } } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { JsonUtil jutil = new JsonUtil(); String input = jutil.readJsonStrFromHttpRequest(request); System.out.println("input:" + input); JsonUserToken jsonUserToken = null; Gson gson = new Gson(); try { jsonUserToken = gson.fromJson(input, JsonUserToken.class); if (jsonUserToken == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null); return; } } catch (Exception ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Input_Json_Format_Error, null, null); return; } UserDAO userdao = new UserDAO(); String username = null; String password = null; username = jsonUserToken.getLoginid(); password = jsonUserToken.getPassword(); if (username == null || username.length() < 1) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_Login_format, null, null); return; } if (password == null || password.length() < 1) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_password_format, null, null); return; } Users user = userdao.getLogin(username); if (user == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_LoginID, null, null); return; } if (!user.getPassword().equalsIgnoreCase(password)) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_wrong_password, null, null); return; } Date expireTime = null; if (jsonUserToken.getExpire_in_seconds() != null && jsonUserToken.getExpire_in_seconds().length() > 1) { try { long expireInSeconds = Long.parseLong(jsonUserToken.getExpire_in_seconds()); if (expireInSeconds > 1) { Date now = new Date(); long expireLong = now.getTime() + 1000L * expireInSeconds; expireTime = new Date(); expireTime.setTime(expireLong); } } catch (Exception ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_date_format, null, null); return; } } String ipAddress = request.getRemoteAddr(); LoginToken token = userdao.requestNewLoginToken(username, ipAddress, expireTime); jsonUserToken.setPassword(null); jsonUserToken.setToken(token.getTokenID()); DBtoJsonUtil dbtoJUtil = new DBtoJsonUtil(); // dbtoJUtil.convert_a_Subject(null) UserDAO userDao = new UserDAO(); UserInfo userinfo = userDao.getUserInfo(user.getLoginID()); if (userinfo == null) { ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Invalid_LoginID, null, null); return; } FollowingDAO followingDao = new FollowingDAO(); List<Follower> follwerList = followingDao.getFollowers(user.getLoginID()); List<Follower> follweringList = followingDao.getFollowerings(user.getLoginID()); Map<String, String> followerMap = null; Map<String, String> followeringsMap = null; JsonUserInfo juserinfo = dbtoJUtil.convert_a_userinfo(userinfo, followerMap, followeringsMap); juserinfo.setTotal_followers(Integer.toString(follwerList.size())); juserinfo.setTotal_followings(Integer.toString(follweringList.size())); JsonElement je = gson.toJsonTree(juserinfo); JsonObject jo = new JsonObject(); JsonElement je_usertoken = gson.toJsonTree(jsonUserToken); jo.addProperty(AllConstants.ProgramConts.result, AllConstants.ProgramConts.succeed); jo.add("usertoken", je_usertoken); jo.add("userinfo", je); JsonWriter jwriter = new JsonWriter(response.getWriter()); gson.toJson(jo, jwriter); } catch (Exception ex) { ex.printStackTrace(); ReturnParser.outputErrorException( response, AllConstants.ErrorDictionary.Internal_Fault, null, null); return; } finally { out.close(); } }