List of usage examples for com.google.gson Gson toJsonTree
public JsonElement toJsonTree(Object src)
From source file:Resources.EmpresaResource.java
@POST @Path("/buscarEmpresas") @Produces("application/json") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String buscarEmpresas(String value) throws SQLException, UnsupportedEncodingException { value = URLDecoder.decode(value, "UTF-8"); value = value.substring(0, value.length() - 1); String[] keyValuePairs = value.split("=", 2); JsonObject json = new JsonObject(); /*/*from w w w . j a v a2s .c o m*/ value = value.substring(1, value.length() - 1); String[] keyValuePairs = value.split(",", 2); */ Gson gson = new Gson(); Filtro filtro = gson.fromJson(keyValuePairs[1], Filtro.class); FiltroDAO filtroDao = new FiltroDAO(); List<Empresa> empresasFiltradas = filtroDao.filtraEmpresa(filtro); List<Empresa> empresas = empresadao.pegarEmpresas(); //Pegar ultima empresa apresentada //Pegar qual ordenacao //Pegar Parametros da filtragem (Culinaria, Endereco, preco max e min) String teste = "testando"; json.add("Empresas", gson.toJsonTree(empresasFiltradas)); json.add("Favoritos", gson.toJsonTree(teste)); //String emps = gson.toJsonTree(empresas); //emps = emps+gson.toJson(teste); return json.toString(); }
From source file:se.sics.datamodel.gson.ObjectValueAdapter.java
License:Open Source License
@Override public void write(JsonWriter writer, ObjectValue t) throws IOException { Gson gson = GsonHelper.getGson(); writer.beginObject();/* w w w . j a va2 s. co m*/ writer.name("fieldMap"); writer.beginArray(); for (Map.Entry<ByteId, Object> e : t.entrySet()) { writer.beginObject(); gson.toJson(gson.toJsonTree(e.getKey().getId()), writer.name("id")); gson.toJson(gson.toJsonTree(e.getValue()), writer.name("field")); writer.endObject(); } writer.endArray(); writer.endObject(); }
From source file:se.sics.datamodel.gson.TypeInfoAdapter.java
License:Open Source License
@Override public void write(JsonWriter writer, TypeInfo ti) throws IOException { Gson gson = GsonHelper.getGson(); writer.beginObject();/*from w ww . ja va 2s .c o m*/ writer.name("typeName").value(ti.name); writer.name("fieldMap").beginArray(); for (Map.Entry<ByteId, FieldInfo> e : ti.entrySet()) { writer.beginObject(); gson.toJson(gson.toJsonTree(e.getKey().getId()), writer.name("id")); gson.toJson(gson.toJsonTree(e.getValue()), writer.name("field")); writer.endObject(); } writer.endArray(); writer.endObject(); }
From source file:se.sics.datamodel.gson.TypeInfoAdapter.java
License:Open Source License
private void writeFieldInfo(JsonWriter writer, FieldInfo fi) throws IOException { Gson gson = GsonHelper.getGson(); writer.name("name").value(fi.name); gson.toJson(gson.toJsonTree(fi.type), writer.name("type")); writer.name("indexed").value(fi.indexed); }
From source file:Servlets.SessionUpdate.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . ja va 2s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Cache-control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); Gson gson = new Gson(); JsonObject myObj = new JsonObject(); try { //session update session.setMaxInactiveInterval(60); myObj.addProperty("SESSION", session.getId()); //System.out.println("Session Update [" + session.getId() + "]"); if (session.getServletContext().getAttribute("Live") != null) { Set<String> live = (Set<String>) session.getServletContext().getAttribute("Live"); live.add(session.getId()); session.getServletContext().setAttribute("Live", live); } else { Set<String> live = new HashSet<String>(); live.add(session.getId()); session.getServletContext().setAttribute("Live", live); } //System.out.println("Live: " + session.getServletContext().getAttribute("Live")); myObj.add("Devices", gson.toJsonTree(session.getServletContext().getAttribute("Live"))); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } finally { out.print(myObj); out.close(); } }
From source file:ss16lab.data.linking.FusekiAPI.java
/** * Fetches observations information based on inputed IDs * * @param observations array of observations IDs * @param outliePropertyName outlier property name in RDF dataset * @return Json format of observations information * @author Gj/*www . j a v a2 s . c o m*/ */ public String fetchObservationsInfo(String[] observations, String outliePropertyName) throws FileNotFoundException, IOException { String ret = "["; String serviceURI = "http://localhost:3030/test/data"; DatasetAccessorFactory factory = null; DatasetAccessor accessor; accessor = factory.createHTTP(serviceURI); Model m = ModelFactory.createDefaultModel(); for (int i = 0; i < observations.length; i++) { String observation = observations[i]; String q = URLEncoder.encode("PREFIX dbpedia: <http://dbpedia.org/resource/>\n" + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#>\n" + "PREFIX dbp: <http://dbpedia.org/property/>\n" + "PREFIX dbo: <http://dbpedia.org/ontology/>\n" + "PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>\n" + "PREFIX qb: <http://purl.org/linked-data/cube#>\n" + "PREFIX datacube: <http://example.org/datacube/>\n" + "PREFIX owl: <http://www.w3.org/2002/07/owl#>\n" + "\n" + "SELECT (str(?observation) as ?ID) (str(?prefLabel) AS ?functionLabel) (str(?definition) AS ?functionDefinition) \n" + "(str(?lat) AS ?latitude) (str(?long) AS ?longitude) (str(?value) AS ?amount)\n" + "WHERE {\n" + " ?observation a qb:Observation.\n" + "?observation datacube:info_lat ?lat .\n" + "?observation datacube:info_long ?long .\n" + "?observation " + outliePropertyName + " ?value .\n" + "OPTIONAL {" + " ?observation <http://data.openbudgets.eu/ontology/dsd/ESIF-2014-2020/dimension/functionalClassification> ?function.\n" + " ?function skos:prefLabel ?prefLabel.\n" + " ?function skos:definition ?definition.\n" + "}" + "FILTER (contains(str(?observation),'" + observation + "'))\n" + "}", "UTF-8"); InputStream queryRes = new URL("http://localhost:3030/test/query?query=" + q).openStream(); JsonParser jsonParser = new JsonParser(); JsonObject jsonObject = (JsonObject) jsonParser.parse(new InputStreamReader(queryRes, "UTF-8")); JsonArray jsonArr = jsonObject.getAsJsonObject("results").getAsJsonArray("bindings"); String functionLabel, functionDefinition, ID = ""; if (jsonArr.size() > 0) { functionLabel = ""; functionDefinition = ""; ID = ""; JsonObject obj = jsonArr.get(0).getAsJsonObject(); ID = obj.get("ID").getAsJsonObject().get("value").getAsString(); if (obj.get("functionLabel") != null) { functionLabel = obj.get("functionLabel").getAsJsonObject().get("value").getAsString(); } if (obj.get("functionDefinition") != null) { functionDefinition = obj.get("functionDefinition").getAsJsonObject().get("value").getAsString(); } float latitude = obj.get("latitude").getAsJsonObject().get("value").getAsFloat(); float longitude = obj.get("longitude").getAsJsonObject().get("value").getAsFloat(); double amountValue = obj.get("amount").getAsJsonObject().get("value").getAsDouble(); Gson gson = new Gson(); JsonObject newobj = new JsonObject(); //Json Object newobj.add("lat", gson.toJsonTree(latitude)); newobj.add("lng", gson.toJsonTree(longitude)); newobj.add("functionLabel", gson.toJsonTree(functionLabel)); newobj.add("functionDefinition", gson.toJsonTree(functionDefinition)); newobj.add("amount", gson.toJsonTree(amountValue)); newobj.add("ID", gson.toJsonTree(observation)); ret += newobj.toString(); ret += ","; } } ret += "]"; ret = ret.replace(",]", "]"); return ret; }
From source file:tech.sirwellington.alchemy.http.mock.Actions.java
License:Apache License
static <T> Callable<JsonElement> returnPojo(T pojo, Gson gson) { return () -> gson.toJsonTree(pojo); }
From source file:tesis.Tesis.java
public static void mainviejo() { /*try (Connection con = DriverManager.getConnection("jdbc:neo4j:bolt://localhost")) { /*from w ww .j ava 2 s . c o m*/ // Querying String query = "MATCH (u:User)-[:FRIEND]-(f:User) WHERE u.name = {1} RETURN f.name, f.age"; try (PreparedStatement stmt = con.prepareStatement(query)) { stmt.setString(1,"John"); try (ResultSet rs = stmt.execute()) { while (rs.next()) { System.out.println("Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age")); } } } } catch (SQLException ex) { Logger.getLogger(Tesis.class.getName()).log(Level.SEVERE, null, ex); }*/ Driver driver = GraphDatabase.driver("bolt://localhost", AuthTokens.basic("neo4j", "123456")); Session session = driver.session(); //session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" ); Gson gson = new Gson(); //StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title" ); //StatementResult result = session.run( "MATCH (n:investigador) RETURN n.Nombre as Nombre, n.TipoInstitucionTrabajo as TipoInstitucionTrabajo, n.InstitucionDeTrabajo as InstitucionDeTrabajo, n.CuitOPasaporte as CuitOPasaporte, n.DisciplinaActuacion as DisciplinaActuacion, n.ProvinciaResidencia as ProvinciaResidencia,n.RangoEtario as RangoEtario,n.MaximoNivelEducativo as MaximoNivelEducativo,n.RangoDeActualizacionCV as RangoDeActualizacionCV, n.Nacionalidad as Nacionalidad, n.ProvinciaLugarDeTrabajo as ProvinciaLugarDeTrabajo,n.Apellido as Apellido, n.Identificador as Identificador,n.GranAreaActuacion as GranAreaActuacion LIMIT 25" ); //StatementResult result = session.run( "MATCH p=(n:pais)-[r:nacionalidad]->() RETURN p"); /*StatementResult resultOrigen = session.run("MATCH (n:investigador) RETURN n" ); int n=0; while ( resultOrigen.hasNext() ){ org.neo4j.driver.v1.types.Node origen=resultOrigen.next().get(0).asNode(); StatementResult resultDestino = session.run("MATCH (n:investigador) where ID(n)>"+origen.id()+" RETURN n" ); while(resultDestino.hasNext()){ org.neo4j.driver.v1.types.Node destino=resultDestino.next().get(0).asNode(); StatementResult result= session.run("MATCH (from:investigador{CuitOPasaporte:\""+origen.get("CuitOPasaporte").asString()+"\"}), (to:investigador{ CuitOPasaporte:\""+destino.get("CuitOPasaporte").asString()+"\"}) , path = shortestPath((from)-[*0..]-(to))\n" + "RETURN path AS shortestPath,\n" + "reduce(distance = 0, r in relationships(path) | distance+1) AS totalDistance \n" + " ORDER BY totalDistance ASC\n" + " LIMIT 1 "); while ( result.hasNext() ) { n=n+1; Record record = result.next(); //System.out.println(gson.toJsonTree(record.asMap())); if(n%10==0) System.out.println(n); //Investigador inv = gson.fromJson(gson.toJson(record.asMap()), Investigador.class); //System.out.println( record.get( "f" ).asNode().id() + " " + record.get( "f" ).asNode().get("CuitOPasaporte")); } } }*/ StatementResult result = session.run( "MATCH (from:investigador), (to:investigador) , path = shortestPath((from)-[*0..]-(to)) RETURN path AS shortestPath "); long n = 0; System.out.println("consulta lista"); while (result.hasNext()) { Record record = result.next(); if (n % 10000 == 0) System.out.println(gson.toJsonTree(record.asMap())); n++; } System.out.println(n); session.close(); driver.close(); /* HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("neo4j", "123456"); Client client = ClientBuilder.newClient(); client.register(feature); Form form = new Form(); form.param("x", "foo"); form.param("y", "bar"); MyJAXBBean bean = target.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form,MediaType.APPLICATION_FORM_URLENCODED_TYPE), MyJAXBBean.class); */ /* Response response = client.target("http://localhost:7474").path("db/data/cypher").request(MediaType.APPLICATION_JSON_TYPE).header("Content-Type", "application/json;charset=UTF-8").post("{\n" + " \"query\" : \"CREATE (n:Person { name : {name} }) RETURN n\",\n" + " \"params\" : {\n" + " \"name\" : \"Andres\"\n" + " }\n" + "}");*/ /* MongoClient mongo; mongo = new MongoClient( "localhost" , 27017 ); MongoDatabase db; db = mongo.getDatabase("test"); MongoCollection<org.bson.Document> investigadores = db.getCollection("investigadores"); MongoCollection<org.bson.Document> enlaces = db.getCollection("enlaces"); for (org.bson.Document document : investigadores.find()) System.out.println(document.getInteger("Identificador"));*/ /* for (org.bson.Document document : investigadores.find()) { for (org.bson.Document document2 : investigadores.find()){ if(document.getString("DisciplinaActuacion").equals(document2.getString("DisciplinaActuacion"))){ org.bson.Document nuevo= new org.bson.Document("id1",document.getString("identificador")); nuevo.append("id2", document2.getString("identificador")); enlaces.insertOne(nuevo); } } }*/ }
From source file:ua.pp.msk.cliqr.job.JobFilter.java
License:Apache License
public ParsedJob[] filter(ParsedJob[] pjs) { GsonBuilder gbuilder = new GsonBuilder(); gbuilder.registerTypeAdapter(ParsedJob.class, new ParsedJob.JobDeserializer()); gbuilder.registerTypeAdapter(ParsedJob.class, new ParsedJob.JobSerializer()); Gson gson = gbuilder.create(); List<ParsedJob> jbs = new LinkedList<>(); for (ParsedJob pj : pjs) { JsonObject j = gson.toJsonTree(pj).getAsJsonObject(); String val = j.get(key).getAsString(); if (val.equals(value)) { jbs.add(gson.fromJson(j, ParsedJob.class)); }//w w w. j a v a2 s .com } return jbs.toArray(new ParsedJob[0]); }
From source file:uk.ac.open.kmi.iserve.rest.sal.resource.DocumentsResource.java
License:Apache License
@GET @ApiOperation(value = "List all the service documents", notes = "Returns a list of service documents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Documents Found"), @ApiResponse(code = 500, message = "Internal error") }) @Produces({ "application/json", "text/html" }) public Response listDocuments( @ApiParam(value = "Response message media type", allowableValues = "application/json,text/html") @HeaderParam("Accept") String accept) { try {// www .java 2 s . c om Set<URI> result = registryManager.getDocumentManager().listDocuments(); String response; if (accept.contains(MediaType.TEXT_HTML)) { StringBuilder responseBuilder = new StringBuilder().append( "<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n </head>\n") .append("<body>\n").append(result.size()).append(" documents are available.") .append("<ul>"); for (URI docUri : result) { responseBuilder.append("<li><a href='").append(docUri).append("'>").append(docUri) .append("</a></li>\n"); } responseBuilder.append("</ul></body>\n</html>"); response = responseBuilder.toString(); } else { Gson gson = new Gson(); JsonObject message = new JsonObject(); message.add("message", new JsonPrimitive(result.size() + " documents are available.")); message.add("uris", gson.toJsonTree(result)); response = message.toString(); } return Response.status(Status.OK).entity(response).build(); } catch (DocumentException e) { e.printStackTrace(); String error; if (accept.contains(MediaType.TEXT_HTML)) { error = "<html>\n <head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n </head>\n" + "<body>\nThere was an error while loading documents. Contact the system administrator. \n </body>\n</html>"; } else { JsonObject message = new JsonObject(); message.add("message", new JsonPrimitive( "There was an error while loading documents. Contact the system administrator.")); error = message.toString(); } return Response.status(Status.INTERNAL_SERVER_ERROR).entity(error).build(); } }