List of usage examples for com.google.gson JsonElement toString
@Override
public String toString()
From source file:eu.smartfp7.EdgeNode.RetrieveXML.java
License:Mozilla Public License
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from ww w . j av a 2 s . co m*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/xml;charset=UTF-8"); PrintWriter out = response.getWriter(); // Get the requested database String feedName = request.getParameter("feed"); if (feedName != null) { feedName = feedName.toLowerCase(); System.out.println("feed=" + feedName); } else { try { response.sendRedirect("retrieveXML.html"); } catch (IOException e1) { System.out.println("doGet IOException: Can not redirect"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println("<?xml version=\"1.0\"?><error>feed parameter not specified</error>"); } return; } // Check if the database (corresponding feed) already exists if (!allClients.get("feeds").context().getAllDbs().contains(feedName)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); out.println("<?xml version=\"1.0\"?><error>Feed " + feedName + " does not exist!</error>"); return; } // Client for current request CouchDbClient curClient; if (!allClients.containsKey(feedName)) { // No request for this feed has arrived so far, add a new client to // the list curClient = new CouchDbClient(feedName, true, "http", server, port, user, pass); allClients.put(feedName, curClient); } else { // We've had requests for this feed before, set the corresponding // client as active curClient = allClients.get(feedName); } System.out.println("Connected to DB: " + curClient.context().info().getDbName()); // Check if a maximum number of results has been specified String limitStr = request.getParameter("limit"); Integer limit = 100; if (limitStr != null) { try { limit = Integer.parseInt(limitStr); } catch (NumberFormatException e) { // Ignore if improperly formatted } } if (!curClient.contains("_design/get_data")) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); out.println("<?xml version=\"1.0\"?><error>Design document for feed " + feedName + " does not exist!</error>"); return; } Long startMillis = null, endMillis = null; String startDate = request.getParameter("start_date"); if (startDate != null) { try { startMillis = Long.parseLong(startDate); } catch (NumberFormatException e) { try { startMillis = javax.xml.bind.DatatypeConverter.parseDateTime(startDate).getTimeInMillis(); } catch (IllegalArgumentException e1) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println("<?xml version=\"1.0\"?><error>Could not parse start date</error>"); return; } } } String endDate = request.getParameter("end_date"); if (endDate != null) { try { endMillis = Long.parseLong(endDate); } catch (NumberFormatException e) { try { endMillis = javax.xml.bind.DatatypeConverter.parseDateTime(endDate).getTimeInMillis(); } catch (IllegalArgumentException e1) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); out.println("<?xml version=\"1.0\"?><error>Could not parse end date</error>"); return; } } } List<JsonObject> resList = null; String low_level = request.getParameter("low_level_events"); if (low_level != null) { try { curClient.view("get_data/with_low_level_event").limit(1).query(JsonObject.class); } catch (org.lightcouch.NoDocumentException e) { response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); out.println("<?xml version=\"1.0\"?><error>Can not search feed '" + feedName + "' for low level events, ensure that the '_design/get_data' document contains a view named 'with_low_level_event'</error>"); return; } } String viewStr; if (low_level != null) viewStr = "get_data/with_low_level_event"; else viewStr = "get_data/by_date"; if (startMillis != null && endMillis != null) resList = curClient.view(viewStr).startKey(startMillis).endKey(endMillis).query(JsonObject.class); else if (startMillis == null && endMillis == null) resList = curClient.view(viewStr).limit(limit).descending(true).query(JsonObject.class); if (resList == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); out.println("<?xml version=\"1.0\"?><error>no data could be found</error>"); return; } // Convert the response to an XML-RDF document StringBuilder result = new StringBuilder(); for (int i = 0; i < resList.size(); i++) { JsonObject item = resList.get(i); JsonElement el = item.get("value"); String data = el.toString(); if (low_level != null) { String time = Common.millis2String(item.get("key").getAsLong()); // Add time and a low_level_event element before each data data = "{\"time\":\"" + time + "\",\"low_level_event\": " + data + "}"; if (i > 0) data = "," + data; } else { // Add a measurement element before each data if (i == 0) data = "\"measurement\": " + data; else data = ",\"measurement\": " + data; } result.append(data); } if (low_level != null) { // Surround the results with the rdf and measurement tags result.insert(0, "{\"rdf\": { \"measurement\": ["); result.append("]}}"); } else { // Surround the result with the rdf tag result.insert(0, "{\"rdf\": {"); result.append("}}"); } String finalres = Json.convertToXml(result.toString()); out.print(finalres); }
From source file:eu.smartfp7.facebook.FacebookUtil.java
/** * Given a JsonObject coming from a Facebook API call, returns a Collection of * FacebookPage objects./* ww w. j a va2s .com*/ */ public static Collection<FacebookPage> getFacebookPagesFromJSON(JsonObject jsonObj) { Collection<FacebookPage> return_coll = new ArrayList<FacebookPage>(); for (JsonElement e : jsonObj.get("data").getAsJsonArray()) return_coll.add(new FacebookPage(e.toString())); return return_coll; }
From source file:ezbake.data.elastic.test.EzElasticTestUtils.java
License:Apache License
public static Map<String, Object> jsonToMap(String json) { final JsonObject object = (JsonObject) new JsonParser().parse(json); final Iterator<Map.Entry<String, JsonElement>> iterator = object.entrySet().iterator(); final Map<String, Object> map = new HashMap<>(); while (iterator.hasNext()) { final Map.Entry<String, JsonElement> entry = iterator.next(); final String key = entry.getKey(); final JsonElement value = entry.getValue(); if (value.isJsonPrimitive()) { map.put(key, value.getAsString()); } else {//from w w w .ja va 2s. com map.put(key, jsonToMap(value.toString())); } } return map; }
From source file:ezbake.services.search.SSRServiceHandler.java
License:Apache License
private SSRSearchResult processSsrSearchResult(SearchResult datasetResults, short pageSize, int offset) { SSRSearchResult results = new SSRSearchResult(); results.setTotalHits(datasetResults.getTotalHits()); results.setPageSize(pageSize);/*from w w w .j a v a 2 s . c om*/ results.setOffset(offset); results.setMatchingRecords(new ArrayList<SSR>()); if (datasetResults.isSetHighlights()) { results.setHighlights(datasetResults.getHighlights()); } for (Document match : datasetResults.getMatchingDocuments()) { String jsonObjectAsString = match.get_jsonObject(); if (jsonObjectAsString == null) { logger.error("Document had no json object"); } JsonElement jsonElement = jsonParser.parse(jsonObjectAsString); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement ssrObject = jsonObject.get(SSRUtils.SSR_FIELD); String ssrJson = ssrObject.toString(); SSR ssrResult = gson.fromJson(ssrJson, SSR.class); ssrResult.setVisibility(match.getVisibility()); results.addToMatchingRecords(ssrResult); } results.setFacets(new HashMap<String, FacetCategory>()); if (results.getTotalHits() > 0) { Map<String, FacetCategory> facetValues = new HashMap<>(); FacetCategory dateCategory = new FacetCategory(); dateCategory.setField(SSRUtils.SSR_DATE_FIELD); dateCategory.setFacetValues(getDateFacets(datasetResults.getFacets().get(DATE_FACET_KEY))); facetValues.put(DATE_FACET_KEY, dateCategory); // ingest time category FacetCategory ingestCategory = new FacetCategory(); ingestCategory.setField(SSRUtils.SSR_TIME_OF_INGEST); ingestCategory.setFacetValues(getDateFacets(datasetResults.getFacets().get(INGEST_FACET_KEY))); facetValues.put(INGEST_FACET_KEY, ingestCategory); FacetCategory visibilityCategory = new FacetCategory(); visibilityCategory.setField("ezbake_auths"); visibilityCategory .setFacetValues(getVisibilityFacets(datasetResults.getFacets().get(VISIBILITY_FACET_KEY))); facetValues.put(VISIBILITY_FACET_KEY, visibilityCategory); FacetCategory typeCategory = new FacetCategory(); typeCategory.setField(SSRUtils.SSR_TYPE_FIELD); typeCategory.setFacetValues(getTermFacets(datasetResults.getFacets().get(TYPE_FACET_KEY))); facetValues.put(TYPE_FACET_KEY, typeCategory); if (isGeoEnabled) { FacetCategory countryCategory = new FacetCategory(); countryCategory.setField(SSRUtils.SSR_COUNTRY_FIELD); countryCategory .setFacetValues(getTermFacets(datasetResults.getFacets().get(GEO_COUNTRY_FACET_KEY))); facetValues.put(GEO_COUNTRY_FACET_KEY, countryCategory); FacetCategory provinceCategory = new FacetCategory(); provinceCategory.setField(SSRUtils.SSR_PROVINCE_FIELD); provinceCategory .setFacetValues(getTermFacets(datasetResults.getFacets().get(GEO_PROVINCE_FACET_KEY))); facetValues.put(GEO_PROVINCE_FACET_KEY, provinceCategory); } results.setFacets(facetValues); } return results; }
From source file:FileHelper.ExcelHelper.java
public DataSheet ReadTestCaseFileFromSheet(String fileName, String sheetName, MyDataHash myDataHash, String rawData) {// ww w . ja v a2 s . c o m try { File excel = new File(fileName); FileInputStream fis = new FileInputStream(excel); XSSFWorkbook book = new XSSFWorkbook(fis); XSSFSheet sheet = book.getSheet(sheetName); Iterator<Row> itr = sheet.iterator(); DataSheet dataSheet = new DataSheet(); ArrayList<RowDataFromFile> datas = new ArrayList<RowDataFromFile>(); ArrayList<DataHash> dataHash = new ArrayList<>(); int colmnDataStart = 0, colmnDataStop = 0, numReal = 0; ArrayList<NameDynamic> nameDynamic = new ArrayList<NameDynamic>(); ArrayList<DataInput> listDataInput = new ArrayList<>(); ArrayList<DataInputLevel2> dataInputLevel2 = new ArrayList<>(); while (itr.hasNext()) { RowDataFromFile dataRow = new RowDataFromFile(); JsonObject jObjReq = new JsonObject(); String caller = ""; Row row = itr.next(); Iterator<Cell> cellIterator = row.cellIterator(); Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: { String str = cell.getStringCellValue(); if (str.equals("STT")) { while (cellIterator.hasNext()) { Cell cell1 = cellIterator.next(); switch (cell1.getCellType()) { case Cell.CELL_TYPE_STRING: { // System.out.println(cell1.getStringCellValue()); if (cell1.getStringCellValue().equals("Data Request")) { colmnDataStart = cell1.getColumnIndex(); } if (cell1.getStringCellValue().equals("Threads")) { colmnDataStop = cell1.getColumnIndex() - 1; } if (cell1.getStringCellValue().equals("Result Real")) { // System.out.println("Colmn Reail: " + cell1.getColumnIndex()); numReal = cell1.getColumnIndex(); } break; } case Cell.CELL_TYPE_NUMERIC: { System.out.println(cell1.getNumericCellValue()); break; } } } Row row1 = sheet.getRow(1); Row row2 = sheet.getRow(2); Row row3 = sheet.getRow(3); Row row4 = sheet.getRow(4); Cell cellColmn; Cell cellColmn2; int numColmn = colmnDataStart; while (numColmn <= colmnDataStop) { cellColmn = row1.getCell(numColmn); String temp = GetValueStringFromCell(cellColmn); cellColmn2 = row2.getCell(numColmn); NameDynamic nameDy = CutStrGetNameDynamic(GetValueStringFromCell(cellColmn2)); if (nameDy.getIsDyn().equals("1")) { // Check Data is change when run Thread nameDynamic.add(nameDy); } // Add to list save data api listDataInput.add(new DataInput(temp, nameDy.getName())); DataHash dataHt = myDataHash.CheckNameDataIsHash(sheetName, nameDy.getName()); if (dataHt != null) { dataHt.setNumColumn(numColmn); dataHash.add(dataHt); } if (temp.equals("Object")) { // Exist object group datas name ArrayList<DataInput> listDataIputLevel2 = new ArrayList<>(); cellColmn = row3.getCell(numColmn); cellColmn2 = row4.getCell(numColmn); String tempT = GetValueStringFromCell(cellColmn); if (!tempT.equals("")) { while (!GetValueStringFromCell(cellColmn).equals("")) { nameDy = CutStrGetNameDynamic(GetValueStringFromCell(cellColmn2)); if (nameDy.getIsDyn().equals("1")) { // Check Data is change when run Thread nameDynamic.add(nameDy); } dataHt = myDataHash.CheckNameDataIsHash(sheetName, nameDy.getName()); if (dataHt != null) { dataHt.setNumColumn(numColmn); dataHash.add(dataHt); } listDataIputLevel2.add( new DataInput(GetValueStringFromCell(cellColmn), nameDy.getName())); numColmn++; cellColmn = row3.getCell(numColmn); cellColmn2 = row4.getCell(numColmn); } numColmn--; dataInputLevel2.add(new DataInputLevel2(listDataIputLevel2)); } else { dataInputLevel2.add(new DataInputLevel2(listDataIputLevel2)); } } numColmn++; } Gson gson = new Gson(); System.out.println(gson.toJson(listDataInput)); System.out.println(gson.toJson(dataHash)); } break; } case Cell.CELL_TYPE_NUMERIC: { // System.out.println(cell.getNumericCellValue()); if (cell.getNumericCellValue() > 0) { dataRow.setId(row.getRowNum()); String isSecutiry = "no"; int arrIndex = 0; int arrIndexReq = 0; // Object con int arrIndexRow = 0; while (cellIterator.hasNext()) { Cell cell1 = cellIterator.next(); if ((cell1.getColumnIndex() >= colmnDataStart) && (cell1.getColumnIndex() < colmnDataStop)) { if (listDataInput.get(arrIndex).getType().equals("Object")) { JsonObject jObj = new JsonObject(); int i = 0; int size = dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().size(); while (i < size) { if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("String")) { String value = GetValueStringFromCell(cell1); if (!dataHash.isEmpty()) { for (DataHash dataH : dataHash) { if (dataH.getNumColumn() == cell1.getColumnIndex()) { value = EncryptHelper.EncryptData(value, dataH.getAlgorithm(), dataH.getKey(), dataH.getIv()); } } } jObj.addProperty(dataInputLevel2.get(arrIndexReq) .getListDataIputLevel2().get(i).getName(), value); } else if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("Integer")) { int value = GetValueIntegerFromCell(cell1); jObj.addProperty(dataInputLevel2.get(arrIndexReq) .getListDataIputLevel2().get(i).getName(), value); } else if (dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getType().equals("Object")) { String value = GetValueStringFromCell(cell1); Gson gson = new Gson(); JsonObject obj = gson.fromJson(value, JsonObject.class); jObj.add(dataInputLevel2.get(arrIndexReq).getListDataIputLevel2().get(i) .getName(), obj); } i++; if (i < size) { cell1 = cellIterator.next(); } } arrIndexReq++; jObjReq.add(listDataInput.get(arrIndex).getName(), jObj); } else if (listDataInput.get(arrIndex).getType().equals("String")) { String value = GetValueStringFromCell(cell1); if (!dataHash.isEmpty()) { for (DataHash dataH : dataHash) { if (dataH.getNumColumn() == cell1.getColumnIndex()) { value = EncryptHelper.EncryptData(value, dataH.getAlgorithm(), dataH.getKey(), dataH.getIv()); } } } jObjReq.addProperty(listDataInput.get(arrIndex).getName(), value); } else if (listDataInput.get(arrIndex).getType().equals("Integer")) { int value = GetValueIntegerFromCell(cell1); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), value); } arrIndex++; } else if (cell1.getColumnIndex() == colmnDataStop) { isSecutiry = GetValueStringFromCell(cell1); dataRow.setNameAlgorithm(isSecutiry); } else if (cell1.getColumnIndex() > colmnDataStop) { if (arrIndexRow == 0) { dataRow.setThread(GetValueIntegerFromCell(cell1)); } else if (arrIndexRow == 1) { dataRow.setResultExpect(GetValueStringFromCell(cell1)); } arrIndexRow++; } } // System.out.println("data: " + jObj.toString()); // System.out.println("data Req: " + jObjReq.toString()); String[] arrR = rawData.split(","); String rawDataNew = ""; char a = '"'; for (String str : arrR) { if (str.charAt(0) == a) { String value = str.substring(1, str.length() - 1); rawDataNew += value; } else { JsonElement je = jObjReq.get(str); if (je.isJsonObject()) { String value = je.toString(); rawDataNew += value; } else { String value = je.getAsString(); rawDataNew += value; } } } String[] arr = isSecutiry.split("-"); if (arr[0].equals("chksum")) { String chksum = CheckSumInquireCard.createCheckSum(isSecutiry, rawDataNew); // System.out.println("chksum: " + chksum); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), chksum); } else if (arr[0].equals("signature")) { String signature = RSASHA1Signature.getSignature(isSecutiry, rawDataNew); // System.out.println("signature: " + signature); jObjReq.addProperty(listDataInput.get(arrIndex).getName(), signature); } // System.out.println("data Request: " + jObjReq.toString()); dataRow.setData(jObjReq); dataRow.setNumReal(numReal); Gson gson = new Gson(); System.out.println("data row: " + gson.toJson(dataRow)); datas.add(dataRow); } break; } } } dataSheet.setDatas(datas); dataSheet.setNameDynamic(nameDynamic); dataSheet.setListDataInput(listDataInput); dataSheet.setDataInputLevel2(dataInputLevel2); Gson gson = new Gson(); // System.out.println("save data: " + gson.toJson(datas)); fis.close(); return dataSheet; } catch (Throwable t) { System.out.println("Throwsable: " + t.getMessage()); return new DataSheet(); } }
From source file:FileHelper.ExcelHelper.java
private JsonObject CreateJsonOnject(ArrayList<DataInput> listDataInput, ArrayList<DataInputLevel2> dataInputLevel2, JsonObject jObjOld, Gson gson, ArrayList<NameDynamic> nameDys, int k, String nameAlgro, String rawData) throws NoSuchAlgorithmException, UnsupportedEncodingException, SignatureException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, Exception { JsonObject jObjNew = new JsonObject(); int countObject = 0; for (DataInput dataI : listDataInput) { JsonElement je = jObjOld.get(dataI.getName()); if (je != null) { if (dataI.getType().equals("String")) { String value = je.getAsString(); if (!nameDys.isEmpty()) { for (NameDynamic nameDy : nameDys) { if (dataI.getName().equals(nameDy.getName())) { value = new String(value + k); }//from w ww . j a v a 2 s .co m } } jObjNew.addProperty(dataI.getName(), value); } else if (dataI.getType().equals("Integer")) { int value = je.getAsInt(); jObjNew.addProperty(dataI.getName(), value); } else if (dataI.getType().equals("Object")) { JsonObject jsonChild = gson.fromJson(je.toString(), JsonObject.class); JsonObject jsonChildNew = new JsonObject(); DataInputLevel2 dataIL2 = dataInputLevel2.get(countObject); for (DataInput dataI2 : dataIL2.getListDataIputLevel2()) { if (dataI2.getType().equals("String")) { je = jsonChild.get(dataI2.getName()); if (je != null) { String value = je.getAsString(); if (!nameDys.isEmpty()) { for (NameDynamic nameDy : nameDys) { if (dataI2.getName().equals(nameDy.getName())) { value = new String(value + k); } } } jsonChildNew.addProperty(dataI2.getName(), value); } } else if (dataI2.getType().equals("Integer")) { je = jsonChild.get(dataI2.getName()); if (je != null) { int value = je.getAsInt(); jsonChildNew.addProperty(dataI2.getName(), value); } } else if (dataI2.getType().equals("Object")) { je = jsonChild.get(dataI2.getName()); if (je != null) { JsonObject value = je.getAsJsonObject(); jsonChildNew.add(dataI2.getName(), value); } } } jObjNew.add(dataI.getName(), jsonChildNew); countObject++; } } } // Raw Data String[] arr = rawData.split(","); String rawDataNew = ""; char a = '"'; for (String str : arr) { if (str.charAt(0) == a) { String value = str.substring(1, str.length() - 1); rawDataNew += value; } else { JsonElement je = jObjNew.get(str); if (je.isJsonObject()) { String value = je.toString(); rawDataNew += value; } else { String value = je.getAsString(); rawDataNew += value; } } } String[] arrS = nameAlgro.split("-"); if (arrS[0].equals("chksum")) { String chksum = CheckSumInquireCard.createCheckSum(nameAlgro, rawDataNew); System.out.println("chksum: " + chksum); jObjNew.addProperty(listDataInput.get(listDataInput.size() - 1).getName(), chksum); } else if (arrS[0].equals("signature")) { String signature = RSASHA1Signature.getSignature(nameAlgro, rawDataNew); System.out.println("signature: " + signature); jObjNew.addProperty(listDataInput.get(listDataInput.size() - 1).getName(), signature); } return jObjNew; }
From source file:fm.audiobox.sync.stream.SocketClient.java
License:Open Source License
@Override public void on(String event, IOAcknowledge ack, JsonElement... args) { log.info("An event emitted " + event); String messageEvent = EventsTypes.MESSAGE.toString().toLowerCase(); if (messageEvent.equals(event)) { log.info("A message received with " + args.length + " arguments"); for (JsonElement json : args) { log.debug("firing actions for '" + json.toString() + "'"); this.onMessage(json, ack); }/*from w w w . j ava 2 s . c o m*/ } }
From source file:fm.audiobox.sync.stream.SocketClient.java
License:Open Source License
@Override public void onMessage(JsonElement json, IOAcknowledge arg1) { try {// w ww .j a v a 2s .c o m log.info("Action received"); // {action: {name: "stream", id: 123, args:{filename: "", rangemin: 0, rangemax: 1000, etag: ""}} } JsonObject jobj = json.getAsJsonObject(); if (jobj != null && jobj.isJsonObject()) { log.debug("message is: " + jobj.toString()); Action action = new Action(this.configuration); JParser jp = new JParser(action); jp.parse(jobj); // Message received: notify observers Event event = new Event(action, Event.States.ENTITY_REFRESHED); this.setChanged(); this.notifyObservers(event); } else { log.error("Invalid message received: " + json.toString()); } } catch (Exception e) { log.error("Error while reveiving message: " + json.toString(), e); } }
From source file:fr.eurecom.nerd.api.rest.Entity.java
License:Apache License
@GET @Produces(MediaType.APPLICATION_JSON)//w w w . j a v a 2 s . c om public Response doGetJSON(@Context SecurityContext context, @QueryParam("idAnnotation") int idAnnotation, @QueryParam("granularity") String granularity) { NerdPrincipal user = ((NerdPrincipal) context.getUserPrincipal()); try { LogFactory.logger.info( "user=" + user.getId() + " requires to fetch entities for the annotation=" + idAnnotation); ResponseBuilder response = Response.status(Response.Status.OK); List<TEntity> entities = sql.selectEntities(idAnnotation); if (granularity != null && granularity.equals("oed")) entities = oed(entities); // if(grouped!=null && grouped) // Collections.sort(extractions, TExtraction.NERDTYPE); String docuType = sql.selectDocumentTypeByAnnotation(idAnnotation); GsonBuilder gsonbuilder = new GsonBuilder(); String json = null; if (docuType.equals(DocumentType.TIMEDTEXTTYPE)) { Gson gson = gsonbuilder.registerTypeAdapter(TEntity.class, new SRTAdapter()).create(); JsonElement itemsjson = gson.toJsonTree(entities); json = itemsjson.toString();//String json = gson.toJson(entities).concat("\n"); } else { Gson gson = gsonbuilder.registerTypeAdapter(TEntity.class, new TextAdapter()).create(); JsonElement itemsjson = gson.toJsonTree(entities); json = itemsjson.toString();//String json = gson.toJson(entities).concat("\n"); } return response.header("Access-Control-Allow-Origin", "*").entity(json).build(); } catch (SQLException e) { e.printStackTrace(); } return null; }
From source file:fr.zcraft.zbanque.json.ContainerTypeAdapter.java
License:Open Source License
@Override public Container deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { final JsonObject rawContainer = jsonElement.getAsJsonObject(); final Location main = jsonDeserializationContext.deserialize(rawContainer.get("mainLocation"), Location.class); Location secondary = null;// w w w. j a v a 2s. c om final JsonElement rawSecondaryLocation = rawContainer.get("secondaryLocation"); if (rawSecondaryLocation != null) secondary = jsonDeserializationContext.deserialize(rawSecondaryLocation, Location.class); final Container container = new Container(main, secondary, true); final JsonObject content = rawContainer.getAsJsonObject("content"); for (Map.Entry<String, JsonElement> entry : content.entrySet()) { final String[] rawType = entry.getKey().split(":"); if (rawType.length != 2) { PluginLogger.error("Malformed JSON content: malformed item type {0} in {1}", entry.getKey(), jsonElement.toString()); continue; } final Material itemType = Material.matchMaterial(rawType[0]); if (itemType == null) { PluginLogger.error("Malformed JSON content: unknown item type {0} in {1}", rawType[0], jsonElement.toString()); continue; } final Short itemData; try { itemData = Short.valueOf(rawType[1]); } catch (NumberFormatException e) { PluginLogger.error("Malformed JSON content: badly formatted data value {0} in {1}", e, rawType[1], jsonElement.toString()); continue; } BlockType blockType = new BlockType(itemType, itemData); Integer amount = entry.getValue().getAsInt(); container.updateBlockType(blockType, amount); } final JsonElement rawContainerType = rawContainer.get("containerType"); if (rawContainerType != null) container.setContainerType(Material.matchMaterial(rawContainerType.getAsString())); return container; }