List of usage examples for com.google.gson.reflect TypeToken TypeToken
@SuppressWarnings("unchecked") protected TypeToken()
From source file:MainFrame.java
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) { return;//from w ww .ja v a 2s . c o m } File file = chooser.getSelectedFile(); if (file == null) { return; } BufferedReader reader; try { reader = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String line = reader.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = reader.readLine(); } String everything = sb.toString(); Gson gson = new Gson(); DiagramProject project = gson.fromJson(everything, new TypeToken<DiagramProject>() { }.getType()); umlDesigner1.setProject(project); umlDesigner1.repaint(); } catch (Exception ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:createNewHomeController.java
public HashMap getHashmapfromJsonString(String JsonString) { //String output = JsonString.substring(1, JsonString.length() - 1); HashMap<String, String> tmpMap = new Gson().fromJson(JsonString, new TypeToken<HashMap<String, String>>() { }.getType());//from w ww. j a v a 2s . co m return tmpMap; }
From source file:NewServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request/*from ww w .j a v a 2 s .c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); String json = getAll(); Gson gson = new Gson(); Type listType = new TypeToken<List<Question>>() { }.getType(); List<Question> questionListFromJson = gson.fromJson(json, listType); }
From source file:ProtocoloActions.java
public void enviaPedidos() { while (true) { //System.out.println("Entrou no while"); if (this.fila.size() != 0) { //System.out.println("Inseriu elemento"); try { AcessoRest ac = new AcessoRest(); String mensagem = ac .exemploGet("http://192.168.0.104:8084/TestHome/webresources//sensor?sensorId==" + this.fila.poll()); Gson g = new Gson(); SensorAnswer s = new SensorAnswer(); Type modelo = new TypeToken<SensorAnswer>() { }.getType();//from w w w . j av a2s . c om s = g.fromJson(mensagem, modelo); //Esses no precisa mostrar, por enquanto! } catch (IOException ex) { ex.printStackTrace(); } } else { try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }
From source file:ProtocoloDeEnvio.java
public void enviaPedidos() { while (true) { for (Integer p : pedidos) { try { AcessoRest ac = new AcessoRest(); String mensagem = ac .exemploGet("http://192.168.0.104:8084/TestHome/webresources//sensor?sensorId==" + p); Gson g = new Gson(); SensorAnswer sa = new SensorAnswer(); Type modelo = new TypeToken<SensorAnswer>() { }.getType();/*from ww w . j av a2 s . c o m*/ sa = g.fromJson(mensagem, modelo); if (sa.getValue() == 666) { //Lana notificao para o usurio que a casa est pegando fogo System.out.println("T pegando fogo"); } else if (sa.getValue() == 999) { //Lana notificao para o usurio que est faltando comida System.out.println("O rango t pouco"); } try { Thread.sleep(500); } catch (InterruptedException ex) { ex.printStackTrace(); } } catch (IOException ex) { ex.printStackTrace(); } } } }
From source file:$.ParseStatusesFromJsonResponse.java
License:Apache License
public SortedSet<Status> apply(InputStream stream) { Type setType = new TypeToken<SortedSet<Status>>() { }.getType();// ww w . j a va 2 s . co m try { return gson.fromJson(new InputStreamReader(stream, "UTF-8"), setType); } catch (UnsupportedEncodingException e) { throw new RuntimeException("jclouds requires UTF-8 encoding", e); } }
From source file:abstractions.AbstractWorker.java
License:Open Source License
/** * Get node credentials// w w w . j ava 2s .c o m * * @return Boolean - result of get-parse node credentials */ protected Boolean getCredentials() { /* * Getting credentials Json */ Map<String, String> params = new HashMap<>(); params.put("node_id", this.coordinates.get("nodeId")); ApiRequest getCredentials = new ApiRequest(coordinates).setRequestMethod(ApiRequestMethods.GET) .setApiMethod("v1/core/get-node-credentials").setParams(params); ApiResponse credentialsResponse = ApiCaller.request(getCredentials); if (!credentialsResponse.success) { /* * Log record * Can't get node credentials */ String getCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't get credentials from API."; this.logBadResponse("WARNING", "NODE GET CREDENTIALS", getCredMessage, credentialsResponse); return false; } /* * Parsing credentials Json to map * Writing parse result */ String credentialsJson = credentialsResponse.response; Type credentialsType = new TypeToken<HashMap<String, String>>() { }.getType(); try { this.credentials = gson.fromJson(credentialsJson, credentialsType); } catch (JsonSyntaxException e) { String parseCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't parse credentials JSON."; this.logException("WARNING", "NODE PARSE CREDENTIALS", parseCredMessage, e); return false; } return true; }
From source file:abstractions.AbstractWorker.java
License:Open Source License
/** * Get job list// w ww .j a v a2 s . c o m * Set job list to this.jobs * * @return Boolean - job list get result */ protected Boolean processJobs() { /* * Getting credentials Json */ Map<String, String> params = new HashMap<>(); params.put("worker_id", this.coordinates.get("workerId")); ApiRequest getCredentials = new ApiRequest(coordinates).setRequestMethod(ApiRequestMethods.GET) .setApiMethod("v1/core/get-jobs").setParams(params); ApiResponse jobsResponse = ApiCaller.request(getCredentials); if (!jobsResponse.success) { /* * Log record * Can't get node credentials */ String getCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't get jobs from api."; this.logBadResponse("WARNING", "NODE GET JOBS", getCredMessage, jobsResponse); return false; } /* * Parsing credentials Json to map * Writing parse result */ String jobsJson = jobsResponse.response; Type jobsType = new TypeToken<TreeMap<String, HashMap<String, String>>>() { }.getType(); try { this.jobs = gson.fromJson(jobsJson, jobsType); } catch (JsonSyntaxException e) { String parseCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't parse jobs JSON."; this.logException("WARNING", "NODE PARSE JOBS", parseCredMessage, e); return false; } /* * Empty job list */ if (this.jobs.size() == 0) { String jobsCountMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": empty jobs list."; this.logMessage("WARNING", "NODE GET JOBS", jobsCountMessage); return false; } return true; }
From source file:abstractions.AbstractWorker.java
License:Open Source License
/** * Check for data saving required/* ww w . ja va 2 s. com*/ * Getting old data hash, comparing with new hash * * @return Boolean */ protected Boolean isSetResultRequired() { // noinspection UnusedAssignment Boolean required = true; String oldHash; String allData = ""; // noinspection UnusedAssignment String newHash = ""; if (this.coordinates.get("put") == null) { required = false; } else { /* * Getting old hash */ Map<String, String> params = new HashMap<>(); params.put("task_name", this.coordinates.get("taskName")); params.put("node_id", this.coordinates.get("nodeId")); ApiRequest getCredentials = new ApiRequest(coordinates).setRequestMethod(ApiRequestMethods.GET) .setApiMethod("v1/core/get-hash").setParams(params); ApiResponse hashResponse = ApiCaller.request(getCredentials); if (!hashResponse.success) { /* * Log record * Can't get old hash */ String getCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't get old hash from API."; this.logBadResponse("ERROR", "WORKER SEND RESULT", getCredMessage, hashResponse); return false; } /* * Parsing old hash Json to string * Writing parse result */ String hashJson = hashResponse.response; Type hashType = new TypeToken<String>() { }.getType(); try { oldHash = gson.fromJson(hashJson, hashType); } catch (JsonSyntaxException e) { String parseCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't parse old hash JSON."; this.logException("WARNING", "WORKER SEND RESULT", parseCredMessage, e); return false; } // Calculating new hash // Get a set of the entries Set resultDataSet = this.workerResult.data.entrySet(); // Get an iterator Iterator it = resultDataSet.iterator(); // Concatenating all new data // noinspection WhileLoopReplaceableByForEach while (it.hasNext()) { Map.Entry result = (Map.Entry) it.next(); allData += result.getValue(); } // Getting new hash try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(allData.getBytes()); // todo test getBytes("UTF-8") byte[] digest = md.digest(); newHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); } catch (NoSuchAlgorithmException e) { String parseCredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": can't get new md5 hash from result."; this.logException("ERROR", "WORKER SEND RESULT", parseCredMessage, e); return false; } this.workerResult.hash = newHash; required = oldHash == null || !oldHash.equals(newHash); } if (required) { return true; } else { String saveNotRequiredMessage = "Task " + this.coordinates.get("taskName") + ", node " + this.coordinates.get("nodeId") + ": worker success. Result saving is not required."; this.logMessage("INFO", "WORKER SEND RESULT", saveNotRequiredMessage); return false; } }
From source file:abtlibrary.utils.as24ApiClient.api.AdminApi.java
License:Apache License
/** * /*from ww w.j a v a 2s . c o m*/ * * @return ApiResponse<ResponseMessageBoolean> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<ResponseMessageBoolean> gETpublicV41AdminFeedbacksWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = gETpublicV41AdminFeedbacksCall(null, null); Type localVarReturnType = new TypeToken<ResponseMessageBoolean>() { }.getType(); return apiClient.execute(call, localVarReturnType); }