static { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); builder.registerTypeAdapterFactory(new LowerCaseEnumTypeAdapterFactory()); builder.registerTypeAdapter(Date.class, new DateTypeAdapter()); builder.enableComplexMapKeySerialization(); mojangGson = builder.create(); builder = new GsonBuilder(); builder.setPrettyPrinting(); gson = builder.create(); }
/* * Finds recipe task for machine if it has been already created otherwise makes a new one and adds it into the DAG */ private static RunRecipeTask makeRecipeTaskIfNotExist( String recipeName, MachineRuntime machine, ClusterStats clusterStats, JsonObject chefJson, TaskSubmitter submitter, String cookbookId, String cookbookName, Map<String, RunRecipeTask> allRecipeTasks, Dag dag) throws DagConstructionException { String recId = RunRecipeTask.makeUniqueId(machine.getId(), recipeName); RunRecipeTask runRecipeTask = allRecipeTasks.get(recId); if (!allRecipeTasks.containsKey(recId)) { ChefJsonGenerator.addRunListForRecipe(chefJson, recipeName); GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); Gson gson = builder.setPrettyPrinting().create(); String jsonString = gson.toJson(chefJson); runRecipeTask = new RunRecipeTask( machine, clusterStats, recipeName, jsonString, submitter, cookbookId, cookbookName); dag.addTask(runRecipeTask); } allRecipeTasks.put(recId, runRecipeTask); return runRecipeTask; }
private Note getNote(String key) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create(); S3Object s3object; try { s3object = s3client.getObject(new GetObjectRequest(bucketName, key)); } catch (AmazonClientException ace) { throw new IOException("Unable to retrieve object from S3: " + ace, ace); } Note note; try (InputStream ins = s3object.getObjectContent()) { String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING)); note = gson.fromJson(json, Note.class); } for (Paragraph p : note.getParagraphs()) { if (p.getStatus() == Status.PENDING || p.getStatus() == Status.RUNNING) { p.setStatus(Status.ABORT); } } return note; }
/** * import JSON as a new note. * * @param sourceJson - the note JSON to import * @param noteName - the name of the new note * @return notebook ID * @throws IOException */ public Note importNote(String sourceJson, String noteName, AuthenticationInfo subject) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.registerTypeAdapter(Date.class, new NotebookImportDeserializer()).create(); JsonReader reader = new JsonReader(new StringReader(sourceJson)); reader.setLenient(true); Note newNote; try { Note oldNote = gson.fromJson(reader, Note.class); newNote = createNote(subject); if (noteName != null) newNote.setName(noteName); else newNote.setName(oldNote.getName()); List<Paragraph> paragraphs = oldNote.getParagraphs(); for (Paragraph p : paragraphs) { newNote.addCloneParagraph(p); } newNote.persist(subject); } catch (IOException e) { logger.error(e.toString(), e); throw e; } return newNote; }
/** * Export existing note. * * @param noteId - the note ID to clone * @return Note JSON * @throws IOException, IllegalArgumentException */ public String exportNote(String noteId) throws IOException, IllegalArgumentException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.create(); Note note = getNote(noteId); if (note == null) { throw new IllegalArgumentException(noteId + " not found"); } return gson.toJson(note); }
public String getInfoJson() { if (json == null) { CookbookInfoJson cookbookInfoJson = new CookbookInfoJson(urls.id, metadataRb); GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); Gson gson = builder.setPrettyPrinting().create(); json = gson.toJson(cookbookInfoJson); } return json; }
/** start a new game */ public Game(String name, Difficulty difficulty) throws Exception { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new LowercaseEnumTypeAdapterFactory()); gson = builder.setPrettyPrinting().create(); // order important: fetch exercises for name, then set difficulty to refresh setName(name); fetchMaterials(); fetchExercises(); setDifficulty(difficulty); }
public static void main(String args[]) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Student.class, new StudentAdapter()); builder.setPrettyPrinting(); Gson gson = builder.create(); String jsonString = "{\"name\":\"Mahesh\", \"rollNo\":1}"; Student student = gson.fromJson(jsonString, Student.class); System.out.println(student); jsonString = gson.toJson(student); System.out.println(jsonString); }
private static String encode(Map<String, Object> m) { try { Gson gson; final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new EnumAdaptorFactory()); builder.registerTypeAdapter(Date.class, new DateAdapter()); builder.registerTypeAdapter(File.class, new FileAdapter()); builder.enableComplexMapKeySerialization(); builder.setPrettyPrinting(); gson = builder.create(); return gson.toJson(m); } catch (Exception e) { Logger.logError("Error encoding Authlib JSON", e); return null; } }
@Override public List<ShellCommand> getCommands() throws IOException { Set<JsonElement> paramsToMerge = DagParams.getGlobalParams(); if (paramsToMerge != null) { try { // Merge in Global return results into the json file. JsonElement obj = new JsonParser().parse(json); if (obj.isJsonObject()) { JsonObject jsonObj = obj.getAsJsonObject(); for (JsonElement param : paramsToMerge) { if (param.isJsonObject()) { JsonObject paramObj = param.getAsJsonObject(); merge(jsonObj, paramObj); } } GsonBuilder builder = new GsonBuilder(); builder.disableHtmlEscaping(); Gson gson = builder.setPrettyPrinting().create(); json = gson.toJson(jsonObj); } else { logger.warn(String.format("Invalid json object for chef-solo: \n %s'", json)); } } catch (JsonIOException | JsonSyntaxException ex) { logger.warn( String.format("Invalid return value as Json object: %s \n %s'", ex.toString(), json)); } } if (commands == null) { String jsonFileName = recipeCanonicalName.replaceAll(Settings.COOOKBOOK_DELIMITER, "__"); commands = ShellCommandBuilder.fileScript2Commands( Settings.SCRIPT_PATH_RUN_RECIPE, "chef_json", json, "json_file_name", jsonFileName, "log_file_name", jsonFileName, "sudo_command", ClusterService.getInstance().getCommonContext().getSudoCommand()); } return commands; }
@PostConstruct public void init() { monitoringService = (ActorRef) context.getAttribute(MonitoringService.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); super.init(configuration); CallinfoConverter converter = new CallinfoConverter(configuration); MonitoringServiceConverter listConverter = new MonitoringServiceConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallInfo.class, converter); builder.registerTypeAdapter(MonitoringServiceResponse.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(listConverter); xstream.registerConverter(new RestCommResponseConverter(configuration)); }
@Override public void save(Note note, AuthenticationInfo subject) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.create(); String json = gson.toJson(note); String key = user + "/" + "notebook" + "/" + note.getId() + "/" + "note.json"; File file = File.createTempFile("note", "json"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write(json); writer.close(); s3client.putObject(new PutObjectRequest(bucketName, key, file)); } catch (AmazonClientException ace) { throw new IOException("Unable to store note in S3: " + ace, ace); } finally { FileUtils.deleteQuietly(file); } }
/** Saves the state of the current settings to a file. */ public static void saveToFile() { // Create a map of fields, indexed on categories then names. // Those are sorted maps, to preserve alphabetical order. SortedMap<String, SortedMap<String, Object>> categories = new TreeMap<>(); for (Field field : getSettableFields()) { // Retrieve the field info. SettingsField fieldInfo = field.getAnnotation(SettingsField.class); // Create a category map, if it doesn't exist. SortedMap<String, Object> category; if (categories.containsKey(fieldInfo.category())) { category = categories.get(fieldInfo.category()); } else { category = new TreeMap<>(); categories.put(fieldInfo.category(), category); } // If the name wasn't set, get the field's declared name. String actualName = fieldInfo.name().isEmpty() ? field.getName() : fieldInfo.name(); // Put the field and its value, as a string. category.put(actualName, get(field).toString()); } // Export the result to a json file. GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); Gson gson = gsonBuilder.create(); String jsonString = gson.toJson(categories); // Write to file. try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("settings.json"))) { bufferedWriter.write(jsonString); } catch (IOException ex) { // If the file can't be written, it's an error. Logger.getLogger(SettingsHandler.class.getName()).log(Level.SEVERE, null, ex); } }
@PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); callManager = (ActorRef) context.getAttribute("org.mobicents.servlet.restcomm.telephony.CallManager"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); super.init(configuration); CallDetailRecordConverter converter = new CallDetailRecordConverter(configuration); listConverter = new CallDetailRecordListConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallDetailRecord.class, converter); builder.registerTypeAdapter(CallDetailRecordList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); normalizePhoneNumbers = configuration.getBoolean("normalize-numbers-for-outbound-calls"); }
@RequestMapping("/view-data") public void viewJSON(HttpServletRequest request, HttpServletResponse res) { String query = request.getParameter("q"); if (null == query || query.trim().length() == 0) query = null; String depthStr = request.getParameter("d"); int depth = 1; try { depth = Integer.parseInt(depthStr); // check boundaries [1, 5] if (depth < 1 || depth > 5) depth = 1; } catch (Exception ex) { } Set<Connected> eList = new HashSet<Connected>(); Network net = new Network(); if (null != query) { try { Storage storage = NMSServerConfig.getInstance().getStorage(request.getParameter("storage")); if (null == storage) { logger.error("storage is not defined"); return; } net = (Network) request.getSession().getAttribute(query); if (null == net) { net = storage.query(query); } else { request.getSession().removeAttribute(query); } String[] entities = net.getIds(); for (String eid : entities) { doDepthView(net.getById(eid), eList, depth); } } catch (NQLException e) { logger.error("Wrong NQL query " + query, e); } catch (StorageException e) { logger.error("Can't execute query " + query, e); } } else { logger.error("No NQL query"); } List<Node> nodes = adaptNodes(eList, net); GsonBuilder gb = new GsonBuilder(); Gson gson = gb.setPrettyPrinting().create(); String jsonStr = gson.toJson(nodes); res.setContentType("application/json"); logger.debug("JSON: " + jsonStr); // System.out.println(jsonStr); try { res.getWriter().write(jsonStr); } catch (IOException e) { logger.error("Can't write JSON string to output stream", e); } return; }
public static Gson prettyWithExpose() { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting().excludeFieldsWithoutExposeAnnotation(); return builder.create(); }
static { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); gson = builder.create(); }