List of usage examples for com.google.gson JsonObject has
public boolean has(String memberName)
From source file:au.edu.unsw.soacourse.client.ApplicationLogic.java
static public void getAppsByAppID(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); try {/*from ww w . j av a2 s. c o m*/ StringBuffer sb = new StringBuffer(); BufferedReader reader = request.getReader(); String temp = ""; while ((temp = reader.readLine()) != null) { sb.append(temp); } // System.out.println(sb.toString()); // convert to object Gson gson = new Gson(); JsonElement je = gson.fromJson(sb.toString(), JsonElement.class); JsonObject jo = je.getAsJsonObject(); String appID = ""; if (jo.has("appID")) appID = jo.get("appID").getAsString(); String REST_URI = "http://localhost:8080/RESTfulFoundITService/apps/"; REST_URI += appID; WebClient client = WebClient.create(REST_URI); String s = client.get(String.class); // System.out.println(s); // write to json out.write(s); out.close(); } catch (Exception e) { out.write("failed"); e.printStackTrace(); out.close(); } }
From source file:au.edu.unsw.soacourse.client.ApplicationLogic.java
static public void getApps(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); try {//from www. j a v a 2 s. c om StringBuffer sb = new StringBuffer(); BufferedReader reader = request.getReader(); String temp = ""; while ((temp = reader.readLine()) != null) { sb.append(temp); } // System.out.println(sb.toString()); // convert to object Gson gson = new Gson(); JsonElement je = gson.fromJson(sb.toString(), JsonElement.class); JsonObject jo = je.getAsJsonObject(); String profileID = ""; if (jo.has("profileID")) profileID = jo.get("profileID").getAsString(); // System.out.println(profileID); String REST_URI = "http://localhost:8080/RESTfulFoundITService/apps"; REST_URI += "/profileID/" + profileID; WebClient client = WebClient.create(REST_URI); String s = client.get(String.class); // System.out.println(s); // write the json out.write(s); out.close(); } catch (Exception e) { out.write("failed"); e.printStackTrace(); out.close(); } }
From source file:au.edu.unsw.soacourse.client.RegisterLogic.java
static public void getpro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf8"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); try {// www .j a va 2s . com StringBuffer sb = new StringBuffer(); BufferedReader reader = request.getReader(); String temp = ""; while ((temp = reader.readLine()) != null) { sb.append(temp); } // System.out.println(sb.toString()); // convert to object Gson gson = new Gson(); JsonElement je = gson.fromJson(sb.toString(), JsonElement.class); JsonObject jo = je.getAsJsonObject(); String profileID = ""; if (jo.has("profileID")) profileID = jo.get("profileID").getAsString(); String REST_URI = "http://localhost:8080/RESTfulFoundITService/userProfiles"; REST_URI += "/profile/" + profileID; WebClient client = WebClient.create(REST_URI); String s = client.get(String.class); // System.out.println(s); // write the json out.write(s); out.close(); } catch (Exception e) { out.write("failed"); e.printStackTrace(); out.close(); } }
From source file:augsburg.se.alltagsguide.common.Location.java
License:Open Source License
@NonNull public static Location fromJson(JsonObject jsonPage) { int id = jsonPage.get("id").getAsInt(); String name = jsonPage.get("name").getAsString(); String icon = jsonPage.get("icon").isJsonNull() ? null : jsonPage.get("icon").getAsString(); String path = jsonPage.get("path").getAsString(); String description = jsonPage.get("description").getAsString(); boolean global = false; if (jsonPage.has("global")) { global = !jsonPage.get("global").isJsonNull() && jsonPage.get("global").getAsBoolean(); }//from w w w . j av a2 s . c o m int color = jsonPage.get("color").isJsonNull() ? Color.parseColor("#00BCD4") : Color.parseColor(jsonPage.get("color").getAsString()); String cityImage = jsonPage.get("cover_image").isJsonNull() ? "" : jsonPage.get("cover_image").getAsString(); if (cityImage == null || "".equals(cityImage)) { cityImage = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Brandenburger_Tor_abends.jpg/300px-Brandenburger_Tor_abends.jpg"; } float latitude = 0.0f; //TODO float longitude = 0.0f; //TODO boolean debug = false; if (jsonPage.has("live")) { JsonElement elem = jsonPage.get("live"); if (elem != null && !elem.isJsonNull()) { debug = elem.getAsBoolean(); } } return new Location(id, name, icon, path, description, global, color, cityImage, latitude, longitude, debug); }
From source file:augsburg.se.alltagsguide.common.Page.java
License:Open Source License
@NonNull public static Page fromJson(@NonNull final JsonObject jsonPage) { int id = jsonPage.get("id").getAsInt(); String title = jsonPage.get("title").getAsString(); String type = jsonPage.get("type").getAsString(); String status = jsonPage.get("status").getAsString(); long modified; try {//from w w w . j a v a 2 s . c om modified = Helper.FROM_DATE_FORMAT.parse(jsonPage.get("modified_gmt").getAsString()).getTime(); } catch (ParseException e) { Ln.e(e); modified = -1; } String description = jsonPage.get("excerpt").getAsString(); String content = jsonPage.get("content").getAsString(); int parentId = jsonPage.get("parent").getAsInt(); int order = jsonPage.get("order").getAsInt(); String thumbnail = jsonPage.get("thumbnail").isJsonNull() ? "" : jsonPage.get("thumbnail").getAsString(); Author author = Author.fromJson(jsonPage.get("author").getAsJsonObject()); List<AvailableLanguage> languages = AvailableLanguage.fromJson(jsonPage.get("available_languages")); boolean autoTranslated = false; if (jsonPage.has("automatic_translation")) { JsonElement elem = jsonPage.get("automatic_translation"); if (elem != null && !elem.isJsonNull()) { autoTranslated = elem.getAsBoolean(); } } return new Page(id, title, type, status, modified, description, content, parentId, order, thumbnail, author, autoTranslated, languages); }
From source file:basedefense.client.version.ModificationVersionCheck.java
License:Apache License
/** * Checks the modification version.//from w w w .j av a2 s. co m * * @return The version. */ public Optional<String> check() { // We will only run this check once as this check may take a lot of time to process if (this.latestVersion != null) return this.latestVersion; InputStreamReader inputStreamReader = null; try { HttpGet getRequest = new HttpGet(API_URL + String.format(API_PATTERN, "LordAkkarin", "BaseDefense2")); HttpResponse response = this.httpClient.execute(getRequest); Preconditions.checkState(response.getStatusLine().getStatusCode() == 200, "Expected status code 200 but received %s", response.getStatusLine()); HttpEntity entity = response.getEntity(); inputStreamReader = new InputStreamReader(entity.getContent()); Gson gson = new Gson(); JsonObject object = gson.fromJson(inputStreamReader, JsonObject.class); Preconditions.checkState(object.has("tag_name"), "No valid version found."); this.latestVersion = Optional.of(object.get("tag_name").getAsString()); } catch (Exception ex) { BaseDefenseModification.getInstance().getLogger() .warn("Unable to retrieve version information: " + ex.getMessage(), ex); this.latestVersion = Optional.empty(); } finally { IOUtils.closeQuietly(inputStreamReader); } return this.latestVersion; }
From source file:be.iminds.iot.dianne.dataset.DatasetConfigurator.java
License:Open Source License
private void parseDatasetConfiguration(File f) { try {//from www. j ava2 s . com // parse any adapter configurations from JSON and apply config? JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new JsonReader(new FileReader(f))).getAsJsonObject(); String name = json.get("name").getAsString(); if (name == null) return; // should have a name Hashtable<String, Object> props = new Hashtable<>(); String dir = f.getParentFile().getAbsolutePath(); props.put("dir", dir); String pid = null; if (json.has("adapter")) { String adapter = json.get("adapter").getAsString(); pid = adapter.contains(".") ? adapter : "be.iminds.iot.dianne.dataset.adapters." + adapter; // in case of adapter, set Dataset target: the dataset it is adapting String dataset = json.get("dataset").getAsString(); props.put("Dataset.target", "(name=" + dataset + ")"); } else if (json.has("type")) { String type = json.get("type").getAsString(); pid = "be.iminds.iot.dianne.dataset." + type; } else { // some hard coded pids if (name.startsWith("MNIST")) { pid = "be.iminds.iot.dianne.dataset.MNIST"; } else if (name.startsWith("CIFAR-100")) { pid = "be.iminds.iot.dianne.dataset.CIFAR100"; } else if (name.startsWith("CIFAR-10")) { pid = "be.iminds.iot.dianne.dataset.CIFAR10"; } else if (name.startsWith("STL-10")) { pid = "be.iminds.iot.dianne.dataset.STL10"; } else if (name.startsWith("SVHN")) { pid = "be.iminds.iot.dianne.dataset.SVHN"; } else if (name.equalsIgnoreCase("ImageNetValidation")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.validation"; } else if (name.equalsIgnoreCase("ImageNetTraining")) { pid = "be.iminds.iot.dianne.dataset.ImageNet.training"; } else { pid = "be.iminds.iot.dianne.dataset." + name; } } // set an aiolos instance id using the dataset name to treat // equally named datasets as single instance in the network props.put("aiolos.instance.id", name); // combine all offered interfaces (might be SequenceDataset or ExperiencePool) props.put("aiolos.combine", "*"); // TODO use object conversion from JSON here? Configuration config = ca.createFactoryConfiguration(pid, null); json.entrySet().stream().forEach(e -> { if (e.getValue().isJsonArray()) { JsonArray a = e.getValue().getAsJsonArray(); String[] val = new String[a.size()]; for (int i = 0; i < val.length; i++) { val[i] = a.get(i).getAsString(); } props.put(e.getKey(), val); } else { props.put(e.getKey(), e.getValue().getAsString()); } }); config.update(props); } catch (Exception e) { System.err.println("Error parsing Dataset config file: " + f.getAbsolutePath()); e.printStackTrace(); } }
From source file:be.iminds.iot.dianne.jsonrpc.DianneRequestHandler.java
License:Open Source License
@Override public void handleRequest(JsonObject request, JsonWriter writer) throws IOException { String i = "null"; if (request.has("id")) { i = request.get("id").getAsString(); }//from ww w . ja v a 2s . co m final String id = i; if (!request.has("jsonrpc")) { writeError(writer, id, -32600, "Invalid JSONRPC request"); return; } if (!request.get("jsonrpc").getAsString().equals("2.0")) { writeError(writer, id, -32600, "Wrong JSONRPC version: " + request.get("jsonrpc").getAsString()); return; } if (!request.has("method")) { writeError(writer, id, -32600, "No method specified"); return; } String method = request.get("method").getAsString(); // TODO use a more generic approach here? switch (method) { case "deploy": try { String description = null; UUID runtimeId = null; String[] tags = null; NeuralNetworkInstanceDTO nni; JsonArray params = request.get("params").getAsJsonArray(); if (params.size() > 1) { description = params.get(1).getAsString(); } if (params.size() > 2) { runtimeId = UUID.fromString(params.get(2).getAsString()); } if (params.size() > 3) { tags = new String[params.size() - 3]; for (int t = 3; t < params.size(); t++) { tags[t - 3] = params.get(t).getAsString(); } } if (params.get(0).isJsonPrimitive()) { String nnName = params.get(0).getAsString(); nni = platform.deployNeuralNetwork(nnName, description, runtimeId, tags); } else { NeuralNetworkDTO nn = DianneJSONConverter.parseJSON(params.get(0).getAsJsonObject()); nni = platform.deployNeuralNetwork(nn, description, runtimeId, tags); } writeResult(writer, id, nni.id.toString()); } catch (Exception e) { writeError(writer, id, -32602, "Incorrect parameters provided: " + e.getMessage()); return; } break; case "undeploy": try { JsonArray params = request.get("params").getAsJsonArray(); if (params.get(0).isJsonPrimitive()) { String s = params.get(0).getAsString(); UUID nnId = UUID.fromString(s); platform.undeployNeuralNetwork(nnId); writeResult(writer, id, nnId); } } catch (Exception e) { writeError(writer, id, -32602, "Incorrect parameters provided: " + e.getMessage()); return; } break; case "forward": try { JsonArray params = request.get("params").getAsJsonArray(); if (params.size() != 2) { throw new Exception("2 parameters expected"); } if (!params.get(0).isJsonPrimitive()) throw new Exception("first parameter should be neural network instance id"); if (!params.get(1).isJsonArray()) throw new Exception("second parameter should be input data"); String s = params.get(0).getAsString(); UUID nnId = UUID.fromString(s); NeuralNetworkInstanceDTO nni = platform.getNeuralNetworkInstance(nnId); if (nni == null) { writeError(writer, id, -32603, "Neural network with id " + nnId + " does not exist."); return; } NeuralNetwork nn = dianne.getNeuralNetwork(nni).getValue(); JsonArray in = params.get(1).getAsJsonArray(); Tensor input = asTensor(in); nn.forward(null, null, input).then(p -> { int argmax = TensorOps.argmax(p.getValue().tensor); writeResult(writer, id, nn.getOutputLabels()[argmax]); return null; }, p -> { writeError(writer, id, -32603, "Error during forward: " + p.getFailure().getMessage()); }); } catch (Exception e) { writeError(writer, id, -32602, "Incorrect parameters provided: " + e.getMessage()); return; } break; case "learn": case "eval": case "act": String[] nnName = null; NeuralNetworkDTO nn = null; String dataset; Map<String, String> config; try { JsonArray params = request.get("params").getAsJsonArray(); if (params.get(0).isJsonPrimitive()) { nnName = params.get(0).getAsString().split(","); for (int k = 0; k < nnName.length; k++) { nnName[k] = nnName[k].trim(); } } else { nn = DianneJSONConverter.parseJSON(params.get(0).getAsJsonObject()); } dataset = params.get(1).getAsString(); config = params.get(2).getAsJsonObject().entrySet().stream() .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().getAsString())); } catch (Exception e) { writeError(writer, id, -32602, "Incorrect parameters provided: " + e.getMessage()); return; } // call coordinator if (method.equals("learn")) { // learn Promise<LearnResult> result = null; if (nnName != null) { result = coordinator.learn(dataset, config, nnName); } else { result = coordinator.learn(dataset, config, nn); } try { result.then(p -> { writeResult(writer, id, p.getValue()); return null; }, p -> { writeError(writer, id, -32603, "Error during learning: " + p.getFailure().getMessage()); }).getValue(); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } else if (method.equals("eval")) { // eval Promise<EvaluationResult> result = null; if (nnName != null) { result = coordinator.eval(dataset, config, nnName); } else { result = coordinator.eval(dataset, config, nn); } try { result.then(p -> { writeResult(writer, id, p.getValue()); return null; }, p -> { writeError(writer, id, -32603, "Error during learning: " + p.getFailure().getMessage()); }).getValue(); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } else if (method.equals("act")) { Promise<AgentResult> result = null; if (nnName != null) { result = coordinator.act(dataset, config, nnName); } else { result = coordinator.act(dataset, config, nn); } try { result.then(p -> { writeResult(writer, id, null); return null; }, p -> { writeError(writer, id, -32603, "Error during learning: " + p.getFailure().getMessage()); }).getValue(); } catch (InvocationTargetException | InterruptedException e) { e.printStackTrace(); } } break; case "learnResult": case "evaluationResult": case "agentResult": case "job": case "stop": UUID jobId = null; try { JsonArray params = request.get("params").getAsJsonArray(); if (params.get(0).isJsonPrimitive()) { String s = params.get(0).getAsString(); jobId = UUID.fromString(s); } } catch (Exception e) { writeError(writer, id, -32602, "Incorrect parameters provided: " + e.getMessage()); return; } if (method.equals("learnResult")) { writeResult(writer, id, coordinator.getLearnResult(jobId)); } else if (method.equals("evaluationResult")) { writeResult(writer, id, coordinator.getEvaluationResult(jobId)); } else if (method.equals("agentResult")) { writeResult(writer, id, coordinator.getAgentResult(jobId)); } else if (method.equals("stop")) { try { coordinator.stop(jobId); } catch (Exception e) { writeError(writer, id, -32603, "Error stopping job: " + e.getMessage()); } } else { writeResult(writer, id, coordinator.getJob(jobId)); } break; case "availableNeuralNetworks": writeResult(writer, id, platform.getAvailableNeuralNetworks()); break; case "availableDatasets": writeResult(writer, id, datasets.getDatasets().stream().map(d -> d.name).collect(Collectors.toList())); break; case "queuedJobs": writeResult(writer, id, coordinator.queuedJobs()); break; case "runningJobs": writeResult(writer, id, coordinator.runningJobs()); break; case "finishedJobs": writeResult(writer, id, coordinator.finishedJobs()); break; case "notifications": writeResult(writer, id, coordinator.getNotifications()); break; case "status": writeResult(writer, id, coordinator.getStatus()); break; case "devices": writeResult(writer, id, coordinator.getDevices()); break; default: writeError(writer, id, -32601, "Method " + method + " not found"); } }
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
public static NeuralNetworkDTO parseJSON(JsonObject json) { String name = null;//from w w w. j a va 2 s . c o m List<ModuleDTO> modules = new ArrayList<ModuleDTO>(); if (json.has("name")) { name = json.get("name").getAsString(); } // could be either a nice NeuralNetworkDTO or just a bunch of modules JsonObject jsonModules = json; if (json.has("modules")) { jsonModules = json.get("modules").getAsJsonObject(); } for (Entry<String, JsonElement> module : jsonModules.entrySet()) { JsonObject moduleJson = (JsonObject) module.getValue(); modules.add(parseModuleJSON(moduleJson)); } return new NeuralNetworkDTO(name, modules); }
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
private static ModuleDTO parseModuleJSON(JsonObject jsonModule) { UUID id = UUID.fromString(jsonModule.get("id").getAsString()); String type = jsonModule.get("type").getAsString(); UUID[] next = null, prev = null; Map<String, String> properties = new HashMap<String, String>(); if (jsonModule.has("next")) { if (jsonModule.get("next").isJsonArray()) { JsonArray jsonNext = jsonModule.get("next").getAsJsonArray(); next = new UUID[jsonNext.size()]; int i = 0; Iterator<JsonElement> it = jsonNext.iterator(); while (it.hasNext()) { JsonElement e = it.next(); next[i++] = UUID.fromString(e.getAsString()); }//from w w w . ja v a 2 s . c o m } else { next = new UUID[1]; next[0] = UUID.fromString(jsonModule.get("next").getAsString()); } } if (jsonModule.has("prev")) { if (jsonModule.get("prev").isJsonArray()) { JsonArray jsonPrev = jsonModule.get("prev").getAsJsonArray(); prev = new UUID[jsonPrev.size()]; int i = 0; Iterator<JsonElement> it = jsonPrev.iterator(); while (it.hasNext()) { JsonElement e = it.next(); prev[i++] = UUID.fromString(e.getAsString()); } } else { prev = new UUID[1]; prev[0] = UUID.fromString(jsonModule.get("prev").getAsString()); } } // TODO this uses the old model where properties where just stored as flatmap for (Entry<String, JsonElement> property : jsonModule.entrySet()) { String key = property.getKey(); if (key.equals("id") || key.equals("type") || key.equals("prev") || key.equals("next")) { continue; // this is only for module-specific properties } properties.put(property.getKey(), property.getValue().getAsString()); } // TODO evolve to a separate "properties" item if (jsonModule.has("properties")) { JsonObject jsonProperties = jsonModule.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> jsonProperty : jsonProperties.entrySet()) { String key = jsonProperty.getKey(); String value = jsonProperty.getValue().getAsString(); properties.put(key, value); } } ModuleDTO dto = new ModuleDTO(id, type, next, prev, properties); return dto; }