List of usage examples for com.google.gson GsonBuilder GsonBuilder
public GsonBuilder()
From source file:alexandre.letteridentification.ListAction.java
@Override public void execute(HttpServletRequest request, PrintWriter out) { try {/*w w w. ja va2 s .c om*/ String type = request.getParameter("type"); JsonArray list = new JsonArray(); switch (type) { case "images_to_be_analyzed": String path = ActionServlet.path + "\\Images to be analyzed"; File[] letters = new File(path).listFiles(); for (int i = 0; i < letters.length; i++) { JsonObject letter_obj = new JsonObject(); letter_obj.addProperty("letter", letters[i].getName()); File[] drawings = new File(letters[i].getAbsolutePath() + "\\Drawings").listFiles(); JsonArray list_drawings = new JsonArray(); for (int j = 0; j < drawings.length; j++) { BufferedImage im = ImageIO.read(drawings[j]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(im, "png", baos); baos.flush(); byte[] data = baos.toByteArray(); baos.close(); String encodedImage = "data:image/png;base64," + Base64.getEncoder().encodeToString(data); list_drawings.add(encodedImage); } letter_obj.add("drawings", list_drawings); File[] computer_vision = new File(letters[i].getAbsolutePath() + "\\Computer Vision") .listFiles(); JsonArray list_computer = new JsonArray(); for (int j = 0; j < computer_vision.length; j++) { BufferedImage im = ImageIO.read(computer_vision[j]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(im, "png", baos); baos.flush(); byte[] data = baos.toByteArray(); baos.close(); String encodedImage = "data:image/png;base64," + Base64.getEncoder().encodeToString(data); list_computer.add(encodedImage); } letter_obj.add("computer_vision", list_computer); list.add(letter_obj); } break; } JsonObject container = new JsonObject(); container.add("list", list); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(container); out.println(json); } catch (IOException ex) { Logger.getLogger(ListAction.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:alexandre.letteridentification.LoginAction.java
@Override public void execute(HttpServletRequest request, PrintWriter out) { try {//from w w w. j a v a2s. com HttpSession session = request.getSession(); String email = request.getParameter("email"); String password = request.getParameter("password"); Administrator a = serv.findAdministratorByEmail(email); if (a != null) { if (password.equals(a.getPassword())) { session.setAttribute("administrator", a); JsonObject result = new JsonObject(); result.addProperty("administrator", a.getId()); result.addProperty("link", "administration.html"); JsonObject container = new JsonObject(); container.add("result", result); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(container); out.println(json); } else { session.invalidate(); } } else { session.invalidate(); } } catch (Throwable ex) { Logger.getLogger(LoginAction.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:alexiil.node.core.GraphJson.java
public static void write(NodeGraph graph, OutputStream stream) throws IOException { List<INode> nodes = graph.getNodes(); JsonGraph jsonGraph = new JsonGraph(); jsonGraph.nodes = new JsonNode[nodes.size()]; for (int nodeIndex = 0; nodeIndex < nodes.size(); nodeIndex++) { INode node = nodes.get(nodeIndex); JsonNode jNode = new JsonNode(); jsonGraph.nodes[nodeIndex] = jNode; jNode.name = node.getName();/*from www . j ava 2 s . c o m*/ jNode.registryPackage = node.getRegistry().packageName; jNode.tag = node.getTypeTag(); if (node instanceof INodeAdditionalData) { INodeAdditionalData addNode = (INodeAdditionalData) node; String[] addData = addNode.addtionalData(); String[] keys = addNode.dataKeys(); jNode.extraData = new JsonEntry[addData.length]; for (int i = 0; i < jNode.extraData.length; i++) { JsonEntry entry = new JsonEntry(); jNode.extraData[i] = entry; entry.key = keys[i]; entry.value = addData[i]; } } Set<Entry<String, GraphConnection<?>>> inputs = node.getInputs().entrySet(); Iterator<Entry<String, GraphConnection<?>>> inputIterator = inputs.iterator(); jNode.inputs = new JsonInput[inputs.size()]; for (int inputIndex = 0; inputIndex < jNode.inputs.length; inputIndex++) { JsonInput jInput = new JsonInput(); jNode.inputs[inputIndex] = jInput; Entry<String, GraphConnection<?>> entry = inputIterator.next(); jInput.inName = entry.getKey(); jInput.outName = entry.getValue().connectedOutput.getName(); jInput.otherNodeName = entry.getValue().connectedOutput.getNode().getName(); } } String json = new GsonBuilder().setPrettyPrinting().create().toJson(jsonGraph); OutputStreamWriter writer = new OutputStreamWriter(stream); writer.write(json); writer.close(); }
From source file:alfio.manager.NotificationManager.java
License:Open Source License
@Autowired public NotificationManager(Mailer mailer, MessageSource messageSource, PlatformTransactionManager transactionManager, EmailMessageRepository emailMessageRepository, EventRepository eventRepository, EventDescriptionRepository eventDescriptionRepository, OrganizationRepository organizationRepository, ConfigurationManager configurationManager, FileUploadManager fileUploadManager, TemplateManager templateManager, TicketReservationRepository ticketReservationRepository) { this.messageSource = messageSource; this.mailer = mailer; this.emailMessageRepository = emailMessageRepository; this.eventRepository = eventRepository; this.organizationRepository = organizationRepository; this.tx = new TransactionTemplate(transactionManager); this.configurationManager = configurationManager; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Mailer.Attachment.class, new AttachmentConverter()); this.gson = builder.create(); attachmentTransformer = new EnumMap<>(Mailer.AttachmentIdentifier.class); attachmentTransformer.put(Mailer.AttachmentIdentifier.CALENDAR_ICS, (model) -> { Event event = eventRepository.findById(Integer.valueOf(model.get("eventId"), 10)); Locale locale = Json.fromJson(model.get("locale"), Locale.class); String description = eventDescriptionRepository.findDescriptionByEventIdTypeAndLocale(event.getId(), EventDescription.EventDescriptionType.DESCRIPTION, locale.getLanguage()).orElse(""); Organization organization = organizationRepository.getById(event.getOrganizationId()); return event.getIcal(description, organization.getName(), organization.getEmail()).orElse(null); });//from w ww . j ava 2 s . co m attachmentTransformer.put(Mailer.AttachmentIdentifier.RECEIPT_PDF, (model) -> { String reservationId = model.get("reservationId"); Event event = eventRepository.findById(Integer.valueOf(model.get("eventId"), 10)); Locale language = Json.fromJson(model.get("language"), Locale.class); Map<String, Object> reservationEmailModel = Json.fromJson(model.get("reservationEmailModel"), new TypeReference<Map<String, Object>>() { }); //FIXME hack: reservationEmailModel should be a minimal and typed container reservationEmailModel.put("event", event); Optional<byte[]> receipt = TemplateProcessor.buildReceiptPdf(event, fileUploadManager, language, templateManager, reservationEmailModel); if (!receipt.isPresent()) { log.warn("was not able to generate the bill for reservation id " + reservationId + " for locale " + language); } return receipt.orElse(null); }); attachmentTransformer.put(Mailer.AttachmentIdentifier.TICKET_PDF, (model) -> { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Ticket ticket = Json.fromJson(model.get("ticket"), Ticket.class); try { TicketReservation reservation = ticketReservationRepository .findReservationById(ticket.getTicketsReservationId()); TicketCategory ticketCategory = Json.fromJson(model.get("ticketCategory"), TicketCategory.class); Event event = eventRepository.findById(ticket.getEventId()); Organization organization = organizationRepository .getById(Integer.valueOf(model.get("organizationId"), 10)); PDFTemplateGenerator pdfTemplateGenerator = TemplateProcessor.buildPDFTicket( Locale.forLanguageTag(ticket.getUserLanguage()), event, reservation, ticket, ticketCategory, organization, templateManager, fileUploadManager); pdfTemplateGenerator.generate().createPDF(baos); } catch (IOException e) { log.warn("was not able to generate ticket pdf for ticket with id" + ticket.getId(), e); } return baos.toByteArray(); }); }
From source file:allout58.mods.techtree.tree.TreeManager.java
License:Open Source License
public String getTreeAsString() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(TechNode.class, new TechNodeGSON()); Gson gson = gsonBuilder.create();//from w w w . j a va 2s . com TechNode[] nodes = currentTree.getRealNodes().toArray(new TechNode[currentTree.getNodes().size()]); return gson.toJson(nodes); // return treeString; }
From source file:allout58.mods.techtree.tree.TreeManager.java
License:Open Source License
public void makeFromReader(Reader reader) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(TechNode.class, new TechNodeGSON()); gsonBuilder.registerTypeAdapter(ItemStack.class, new ItemStackGSON()); Gson gson = gsonBuilder.create();// www. ja va 2 s . c o m TechNode[] nodes = gson.fromJson(reader, TechNode[].class); TechNode head = null; for (TechNode node : nodes) { if (node.getParentID().size() == 0) { head = node; } else { for (int parentID : node.getParentID()) { if (parentID == node.getId()) throw new RuntimeException("Tree node with a self-referencing parent: " + parentID); TechNode parent = nodes[parentID]; node.addParentNode(parent); parent.addChildNode(node); } } } currentTree = new TechTree(head); }
From source file:am.ik.categolj3.api.CategoLJ3ApiConfig.java
License:Apache License
@Bean Gson gson() {//w ww . ja va 2 s.c o m return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").registerTypeAdapter(OffsetDateTime.class, (JsonDeserializer<OffsetDateTime>) (json, type, context) -> DateTimeFormatter.ISO_OFFSET_DATE_TIME .parse(json.getAsString(), OffsetDateTime::from)) .registerTypeAdapter(OffsetDateTime.class, (JsonSerializer<OffsetDateTime>) (json, type, context) -> new JsonPrimitive(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(json))) .create(); }
From source file:anakiou.com.picontrol.service.BaseService.java
License:Apache License
public PiserverApi prepareApi() { final Gson gson = new GsonBuilder().create(); final Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)).build(); return retrofit.create(PiserverApi.class); }
From source file:android.zetterstrom.com.forecast.ForecastClient.java
License:Apache License
private static Gson createGson() { final long MILLIS = 1000; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong() * MILLIS); }//from ww w . j ava 2 s .c o m }); return builder.create(); }
From source file:angularBeans.util.AngularBeansUtil.java
License:Open Source License
public String getJson(Object object) { if (object instanceof Properties) { return new Gson().toJson(object); }/*from w w w .j a va2 s .c o m*/ GsonBuilder builder = new GsonBuilder().serializeNulls(); if (object == null) { return new GsonBuilder().serializeNulls().create().toJson(null); } Class clazz = object.getClass(); builder.registerTypeAdapter(LobWrapper.class, new ByteArrayJsonAdapter(cache)); Gson gson = builder.create(); return gson.toJson(object); }