List of usage examples for com.google.gson GsonBuilder registerTypeAdapter
@SuppressWarnings({ "unchecked", "rawtypes" }) public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
From source file:co.Converters.java
License:Open Source License
/** * Registers the {@link Interval} converter. * @param builder The GSON builder to register the converter with. * @return A reference to {@code builder}. *//*from w w w .j a va 2 s. co m*/ public static GsonBuilder registerInterval(GsonBuilder builder) { if (builder == null) { throw new NullPointerException("builder cannot be null"); } builder.registerTypeAdapter(INTERVAL_TYPE, new IntervalConverter()); return builder; }
From source file:codemate.ui.Config.java
License:Open Source License
/** * load// w ww . j a va 2s .co m * * This method loads the given configuration. * * @param fileName * * @author Li Dong <dongli@lasg.iap.ac.cn> */ public static void load(String fileName) { if (fileName.equals(defaultConfig)) { File root = new File(defaultRoot); if (!root.exists()) { UI.notice("Config", "There is no runtime directory as" + defaultRoot + "."); boolean succ = (new File(defaultRoot)).mkdir(); if (succ) UI.notice("codemate", "Create one."); else UI.error("codemate", "Couldn't create one!"); } } File file = new File(fileName); if (!file.exists()) { UI.notice("codemate", "Create a configuration as " + fileName + "."); createTemplateConfig(fileName); } else { UI.notice("codemate", "Load configuration from " + fileName + "."); try { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(ConfigData.class, new ConfigDataDeserializer()); Gson gson = gsonBuilder.create(); String json = new Scanner(file).useDelimiter("\\Z").next(); configData = gson.fromJson(json, ConfigData.class); } catch (Exception e) { e.printStackTrace(); UI.error("codemate", "Encounter error while loading configuation from " + fileName + "!"); } } // spread configuration to other classes for (Entry<String, BlockData> libraryData : configData.data.get("library").data.entrySet()) { LibraryMate libraryMate = LibraryMates.searchLibrary(libraryData.getKey()); if (libraryMate != null) { libraryMate.setRoot(libraryData.getValue().data.get("root")); libraryMate.setWrapper("Fortran", libraryData.getValue().data.get("fortran_wrapper")); } } }
From source file:codemate.ui.Config.java
License:Open Source License
/** * createTemplateConfig/* w w w .j a v a 2s.c om*/ * * This method creates a template of configuration and asks user for * necessary information. * * @param fileName * * @author Li Dong <dongli@lasg.iap.ac.cn> */ private static void createTemplateConfig(String fileName) { UI.notice("codemate", "Create a configuration as " + fileName + "."); // compiler section SectionData compilerSection = new SectionData(); BlockData fortranBlock = new BlockData(); UI.notice("codemate", "Choose a Fortran compiler:"); String vendor = UI.getAnswer(CompilerMates.getVendorNames())[0]; fortranBlock.data.put("vendor", vendor); compilerSection.data.put("Fortran", fortranBlock); configData.data.put("compiler", compilerSection); // library section SectionData librarySection = new SectionData(); for (LibraryMate libraryMate : LibraryMates.getLibraryMates()) { BlockData libraryBlock = new BlockData(); if (libraryMate.provideCompilerWrapper()) { UI.notice("codemate", "Set Fortran compiler wrappers for " + libraryMate.getLibraryName() + ":"); String wrapper = UI.getAnswer(null)[0]; libraryBlock.data.put("fortran_wrapper", wrapper); } else { UI.notice("codemate", "Set library root for " + libraryMate.getLibraryName() + ":"); String root = UI.getAnswer(null)[0]; libraryBlock.data.put("root", root); } librarySection.data.put(libraryMate.getLibraryName(), libraryBlock); } configData.data.put("library", librarySection); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(ConfigData.class, new ConfigDataSerializer()); Gson gson = gsonBuilder.setPrettyPrinting().create(); PrintWriter writer = null; try { writer = new PrintWriter(fileName); } catch (FileNotFoundException e) { e.printStackTrace(); UI.error("codemate", "Encounter error while creating configuration as " + fileName + "!"); } writer.println(gson.toJson(configData)); writer.flush(); }
From source file:com.actionml.entity.Event.java
License:Apache License
@Override public String toString() { // handle DateTime separately GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeAdapter()); Gson gson = gsonBuilder.create();/*from ww w . j a v a 2s. co m*/ return gson.toJson(this); // works when there are no generic types }
From source file:com.addhen.voto.sdk.BaseApiBuilder.java
License:Apache License
private void initializeGson() { GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); builder.registerTypeAdapter(Date.class, new DateDeserializer()); mGson = builder.create();// w w w . ja v a 2s .co m }
From source file:com.algodefu.yeti.web.ClusterServlet.java
License:Apache License
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setHeader("Cache-Control", "nocache"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); ClusterFormat clusterFormat = new ClusterFormat(); // for JSON/* w ww. j a v a 2 s . c o m*/ String errMsg = ""; String clusterTitle = ""; List<Cluster> clusterData = new ArrayList<>(); String symbol = ""; try { symbol = request.getParameter("symbol"); int count = Integer.parseInt(request.getParameter("count")); LocalDateTime beginDt = LocalDateTime.parse(request.getParameter("beginDt"), dtf); LocalDateTime endDt = LocalDateTime.parse(request.getParameter("endDt"), dtf); ClusterType clusterType = ClusterType.fromName(request.getParameter("cluster-type")); clusterFormat.setType(clusterType); clusterFormat.setSymbol(symbol); clusterFormat.setBeginDt(beginDt); clusterFormat.setEndDt(endDt); clusterFormat.setCount(count); switch (clusterType) { case TIMEFRAME: case TICKTIME: int timeInterval = Integer.parseInt(request.getParameter("time-interval")); ChronoUnit chronoUnit = ChronoUnit.valueOf(request.getParameter("chronoUnit")); clusterFormat.setTimeInterval(timeInterval); clusterFormat.setChronoUnit(chronoUnit); break; case PRICERANGE: double priceRange = Double.parseDouble(request.getParameter("price-range")); clusterFormat.setPriceRange(priceRange); break; case VOLUME: long clusterVolume = Long.parseLong(request.getParameter("cluster-volume")); clusterFormat.setClusterVolume(clusterVolume); break; case TRADECOUNT: long maxTicksInCluster = Long.parseLong(request.getParameter("maxNumTicksInCluster")); clusterFormat.setMaxTicksInCluster(maxTicksInCluster); break; } ClusterSource clusterSource = new ClusterSource(clusterFormat); Instant start = Instant.now(); clusterData = clusterSource.getClusters(); Instant stop = Instant.now(); System.out.printf("%d clusters of type %s generated in %d ms. \n", clusterData.size(), clusterFormat.getType().toString(), Duration.between(start, stop).toMillis()); // add clusterType as title if (clusterFormat.getType() != null) clusterTitle = clusterFormat.getType().toString() + " CLUSTERS"; } catch (Exception e) { errMsg = e.toString().replace("\"", " "); e.printStackTrace(); } Hashtable<String, Object> hashtable = new Hashtable<>(); hashtable.put("errMsg", errMsg); hashtable.put("symbol", symbol); hashtable.put("clusterTitle", clusterTitle); hashtable.put("clusterData", clusterData.toArray()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter()); Gson gson = gsonBuilder.create(); out.println(gson.toJson(hashtable)); out.flush(); out.close(); }
From source file:com.algodefu.yeti.web.ShowTradeInPassServlet.java
License:Apache License
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String reqTradeId = request.getParameter("tradeId"); String reqPassId = request.getParameter("passId"); String reqShowAllTrades = request.getParameter("showAllTrades"); String reqStartTradeId = request.getParameter("startTradeId"); String reqEndTradeId = request.getParameter("endTradeId"); // for JSON//from www . j av a 2s. c o m String errMsg = ""; String symbol = ""; String clusterTitle = ""; List<Cluster> clusterData = new ArrayList<>(); boolean forwardReq = false; if (reqPassId == null || reqPassId.trim().isEmpty()) forwardReq = true; if (forwardReq) { // show input passId form RequestDispatcher view = request.getRequestDispatcher("/formpassid.html"); view.forward(request, response); } else { response.setHeader("Cache-Control", "nocache"); response.setCharacterEncoding("utf-8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); long singleTradeId = 0; long startTradeId = 0; long endTradeId = 0; int showAllTrades = 0; try { if (!reqTradeId.equals("undefined") && reqTradeId != null && !reqTradeId.trim().isEmpty()) singleTradeId = Long.parseLong(reqTradeId); if (!reqStartTradeId.equals("undefined") && reqStartTradeId != null && !reqStartTradeId.trim().isEmpty()) startTradeId = Long.parseLong(reqStartTradeId); if (!reqEndTradeId.equals("undefined") && reqEndTradeId != null && !reqEndTradeId.trim().isEmpty()) endTradeId = Long.parseLong(reqEndTradeId); if (!reqShowAllTrades.equals("undefined") && reqShowAllTrades != null && !reqShowAllTrades.trim().isEmpty()) showAllTrades = Integer.parseInt(reqShowAllTrades); TaskStorage taskStorage = TaskStorage.getInstance(); // find the required trade / trades Trade[] trades = taskStorage.getTradesByPassId(reqPassId); if (showAllTrades != 1) { List<Trade> tradeList = new ArrayList<>(); for (Trade t : trades) { if (singleTradeId > 0 && t.getTradeID() == singleTradeId) { tradeList.add(t); break; } else if (startTradeId > 0 && endTradeId > 0 && t.getTradeID() >= startTradeId && t.getTradeID() <= endTradeId) { tradeList.add(t); } } trades = tradeList.toArray(new Trade[0]); } // get deals for each trade List<Deal> deals = new ArrayList<>(); List<Deal> tempDeals = new ArrayList<>(); for (Trade t : trades) { tempDeals = t.getDeals(); for (int i = 0; i < tempDeals.size(); i++) { if (tempDeals.get(i).getOrder() != OrderType.CANCELLED) deals.add(tempDeals.get(i)); } } ClusterFormat clusterFormat = taskStorage.getStrategyParamSetByPassId(reqPassId).getClusterFormat(); symbol = clusterFormat.getSymbol(); ClusterSource clusterSource = new ClusterSource(clusterFormat); List<Cluster> clusterList = clusterSource.getClusters(); int startClusterIndex = 0; int endClusterIndex = 0; int tempClusterIndex = 0; for (Deal deal : deals) { Cluster cluster = null; for (int i = 0; i < clusterList.size(); i++) { cluster = clusterList.get(i); if (deal.getDateTime().compareTo(cluster.getOpenDateTime()) >= 0 && deal.getDateTime().compareTo(cluster.getCloseDateTime()) <= 0) { if (deal.getEntry() == DealEntry.IN) { cluster.addDeal(deal); tempClusterIndex = i - 20; if (tempClusterIndex < 0) tempClusterIndex = 0; if (startClusterIndex == 0) startClusterIndex = tempClusterIndex; if (tempClusterIndex < startClusterIndex) startClusterIndex = tempClusterIndex; // if(tempClusterIndex > 0 && (startClusterIndex > 0 && tempClusterIndex < startClusterIndex)) // startClusterIndex = tempClusterIndex; break; } if (deal.getEntry() == DealEntry.OUT && deal.getPrice() >= cluster.getLow() && deal.getPrice() <= cluster.getHigh()) { cluster.addDeal(deal); tempClusterIndex = i + 1; if (tempClusterIndex > clusterList.size() - 1) tempClusterIndex = clusterList.size() - 1; if (endClusterIndex == 0) endClusterIndex = tempClusterIndex; if (tempClusterIndex > endClusterIndex) endClusterIndex = tempClusterIndex; // if(tempClusterIndex > 0 && tempClusterIndex < clusterList.size() - 1 && // (endClusterIndex >= 0 && tempClusterIndex > endClusterIndex)) // endClusterIndex = tempClusterIndex; break; } } } // end for clusterList } // end for - deal // add clusterType as title if (clusterFormat.getType() != null) clusterTitle = clusterFormat.getType().toString() + " CLUSTERS"; // add clusterData for (int i = startClusterIndex; i <= endClusterIndex; i++) { clusterData.add(clusterList.get(i)); } } catch (Exception e) { errMsg = e.toString(); e.printStackTrace(); } Hashtable<String, Object> hashtable = new Hashtable<>(); hashtable.put("errMsg", errMsg); hashtable.put("symbol", symbol); hashtable.put("clusterTitle", clusterTitle); hashtable.put("clusterData", clusterData.toArray()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter()); Gson gson = gsonBuilder.create(); out.println(gson.toJson(hashtable)); out.flush(); out.close(); } }
From source file:com.aliakseipilko.flightdutytracker.utils.BackupUtils.java
License:Open Source License
public static File serialiseFlightsRealmToFile(File destFile, RealmResults<Flight> data) throws IOException { destFile.createNewFile();/* w w w .j a v a 2s . c o m*/ destFile.setWritable(true); if (!destFile.canWrite()) { return null; } GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.registerTypeAdapter(Flight.class, new FlightSerialiser()).serializeNulls() .setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .setDateFormat(DateFormat.FULL, DateFormat.FULL).create(); JsonWriter writer = gson.newJsonWriter(new FileWriter(destFile)); writer.beginArray(); for (Flight f : data) { // writer.beginArray(); gson.toJson(f, Flight.class, writer); // String json = gson.toJson(f, Flight.class); // writer.endArray(); } writer.endArray(); writer.close(); return destFile; }
From source file:com.aliakseipilko.flightdutytracker.utils.BackupUtils.java
License:Open Source License
public static void deserialiseFlightsFileToRealm(Realm realm, final File srcFile, final BackupRestoreBaseFragment callingView) { realm.executeTransactionAsync(new Realm.Transaction() { @Override// w ww .j a va2s . co m public void execute(Realm realm) { try { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.registerTypeAdapter(Flight.class, new FlightSerialiser()) .serializeNulls().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) .setDateFormat(DateFormat.FULL, DateFormat.FULL).create(); JsonReader reader = gson.newJsonReader(new FileReader(srcFile)); List<Flight> flights; Type type = new TypeToken<List<Flight>>() { }.getType(); flights = gson.fromJson(reader, type); for (Flight f : flights) { //Check for ID duplication if (realm.where(Flight.class).equalTo("id", f.getId()).findFirst() == null) { realm.copyToRealm(f); } else { long newId; Number idNum = realm.where(Flight.class).max("id"); if (idNum == null) { newId = 1; } else { long id = idNum.longValue(); newId = id + 1; } f.setId(newId); realm.copyToRealm(f); } } } catch (IOException e) { e.printStackTrace(); } } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { callingView.showSuccess("Restore completed successfully!"); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { callingView.showError("That didn't work. Try again"); } }); }
From source file:com.alignace.chargeio.mapper.JsonMapper.java
License:Apache License
private static Gson getGson() { if (gson == null) { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss"); builder.registerTypeAdapter(IPaymentMethod.class, new IPaymentTypeAdapter()); builder.registerTypeAdapter(TokenReferenceOption.class, new TokenReferenceAdapter()); gson = builder.create();/*from w ww .j av a 2 s.c o m*/ } return gson; }