List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
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 w ww . j a va 2 s . c om*/ 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.jsonrpc.DianneRequestHandler.java
License:Open Source License
private Tensor asTensor(JsonArray array) { // support up to 3 dim input atm int dim0 = 1; int dim1 = 1; int dim2 = 1; int dims = 1; dim0 = array.size();//from ww w . j a va 2 s.com if (array.get(0).isJsonArray()) { dims = 2; JsonArray a = array.get(0).getAsJsonArray(); dim1 = a.size(); if (a.get(0).isJsonArray()) { dims = 3; dim2 = a.get(0).getAsJsonArray().size(); } } int size = dim0 * dim1 * dim2; float[] data = new float[size]; int k = 0; for (int i = 0; i < dim0; i++) { for (int j = 0; j < dim1; j++) { for (int l = 0; l < dim2; l++) { JsonElement e = array.get(i); if (e.isJsonArray()) { e = e.getAsJsonArray().get(j); if (e.isJsonArray()) { e = e.getAsJsonArray().get(l); } } data[k++] = e.getAsFloat(); } } } int[] d = new int[dims]; d[0] = dim0; if (dims > 1) d[1] = dim1; if (dims > 2) d[2] = dim2; return new Tensor(data, d); }
From source file:blusunrize.immersiveengineering.common.crafting.RecipeFactoryShapedIngredient.java
@Override public IRecipe parse(JsonContext context, JsonObject json) { String group = JsonUtils.getString(json, "group", ""); Map<Character, Ingredient> ingMap = Maps.newHashMap(); for (Entry<String, JsonElement> entry : JsonUtils.getJsonObject(json, "key").entrySet()) { if (entry.getKey().length() != 1) throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)."); if (" ".equals(entry.getKey())) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); ingMap.put(entry.getKey().toCharArray()[0], CraftingHelper.getIngredient(entry.getValue(), context)); }//from w ww . ja v a 2 s . c o m ingMap.put(' ', Ingredient.EMPTY); JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern"); if (patternJ.size() == 0) throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed"); String[] pattern = new String[patternJ.size()]; for (int x = 0; x < pattern.length; ++x) { String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]"); if (x > 0 && pattern[0].length() != line.length()) throw new JsonSyntaxException("Invalid pattern: each row must be the same width"); pattern[x] = line; } ShapedPrimer primer = new ShapedPrimer(); primer.width = pattern[0].length(); primer.height = pattern.length; primer.mirrored = JsonUtils.getBoolean(json, "mirrored", true); primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY); Set<Character> keys = Sets.newHashSet(ingMap.keySet()); keys.remove(' '); int x = 0; for (String line : pattern) for (char chr : line.toCharArray()) { Ingredient ing = ingMap.get(chr); if (ing == null) throw new JsonSyntaxException( "Pattern references symbol '" + chr + "' but it's not defined in the key"); primer.input.set(x++, ing); keys.remove(chr); } if (!keys.isEmpty()) throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys); ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context); RecipeShapedIngredient recipe = new RecipeShapedIngredient( group.isEmpty() ? null : new ResourceLocation(group), result, primer); if (JsonUtils.getBoolean(json, "quarter_turn", false)) recipe.allowQuarterTurn(); if (JsonUtils.getBoolean(json, "eighth_turn", false)) recipe.allowEighthTurn(); if (JsonUtils.hasField(json, "copy_nbt")) { if (JsonUtils.isJsonArray(json, "copy_nbt")) { JsonArray jArray = JsonUtils.getJsonArray(json, "copy_nbt"); int[] array = new int[jArray.size()]; for (int i = 0; i < array.length; i++) array[i] = jArray.get(i).getAsInt(); recipe.setNBTCopyTargetRecipe(array); } else recipe.setNBTCopyTargetRecipe(JsonUtils.getInt(json, "copy_nbt")); if (JsonUtils.hasField(json, "copy_nbt_predicate")) recipe.setNBTCopyPredicate(JsonUtils.getString(json, "copy_nbt_predicate")); } return recipe; }
From source file:bmw.assigment.BMWAssigment.java
/** * Recursive method to populate the data extracted from the Json file * //from w ww. j av a2 s . c o m * @param employee * @return */ public static AbstractEmployee populateSubordinate(JsonObject employee) { AbstractEmployee emp = null; if (employee.has("_subordinates")) { emp = new Manager(employee.get("_name").getAsString(), employee.get("_salary").getAsLong()); JsonArray array = employee.getAsJsonArray("_subordinates"); for (int i = 0; i < array.size(); i++) { emp.addEmployee(populateSubordinate(array.get(i).getAsJsonObject())); } } else { emp = new Employee(employee.get("_name").getAsString(), employee.get("_salary").getAsLong()); } return emp; }
From source file:br.com.eventick.api.Event.java
License:Open Source License
/** * Retorna a lista de participantes {@link Attendee} do evento * @return uma {@link List} de {@link Attendee} * @throws IOException// w w w . j a v a 2 s. c o m * @throws InterruptedException * @throws ExecutionException */ public void setAttendees() throws IOException, InterruptedException, ExecutionException { String fetchURL = String.format("%s/%d/attendees", URL, this.id); String json = api.getRequests().get(fetchURL, this.getApi().getToken()); JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("attendees").getAsJsonArray(); Attendee att; int i = 0; for (; i < jsonArray.size(); i++) { att = this.api.getGson().fromJson(jsonArray.get(i), Attendee.class); this.attendees.add(att); } }
From source file:br.com.eventick.api.Event.java
License:Open Source License
public void setTickets() throws IOException, InterruptedException, ExecutionException { String fetchURL = String.format("%s/%d", URL, this.id); String json = api.getRequests().get(fetchURL, this.getApi().getToken()); JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("tickets").getAsJsonArray(); Ticket tick;/*from w w w. j av a2 s. c o m*/ int i = 0; for (; i < jsonArray.size(); i++) { tick = this.api.getGson().fromJson(jsonArray.get(i), Ticket.class); this.tickets.add(tick); } }
From source file:br.com.eventick.api.EventickAPI.java
License:Open Source License
/** * Retorna a colecao de eventos do usuario * @return/*from w w w . j a v a 2 s .c o m*/ * @throws IOException * @throws InterruptedException * @throws ExecutionException */ public List<Event> getMyEvents() throws IOException, InterruptedException, ExecutionException { List<Event> collection = new ArrayList<Event>(); String fetchURL = String.format("%s/events", URL); String json = requests.get(fetchURL, this.getToken()); JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("events").getAsJsonArray(); Event eve; int i = 0; for (; i < jsonArray.size(); i++) { eve = gson.fromJson(jsonArray.get(i), Event.class); collection.add(eve); } return collection; }
From source file:br.com.eventick.api.EventickAPI.java
License:Open Source License
/** * Otenha qualquer um de seus eventos a partir do ID * @param id, ID do evento/*from www . j a va 2s. com*/ * @return * @return um objeto {@link Event} daquele evento * @throws IOException * @throws ExecutionException * @throws InterruptedException */ public Event getEventById(int id) throws IOException, InterruptedException, ExecutionException { String fetchURL = String.format("%s/events/%d", URL, id); String json = requests.get(fetchURL, this.getToken()); JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("events").getAsJsonArray(); Event eve = gson.fromJson(jsonArray.get(0), Event.class); return eve; }
From source file:br.mack.api.Marvel.java
public static void main(String[] args) { //Criao de um timestamp Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhhmmss"); String ts = sdf.format(date); //Criao do HASH String hashStr = MD5(ts + privatekey + apikey); String uri;/*from ww w.ja v a 2s.c om*/ String name = "Captain%20America"; //url de consulta uri = urlbase + "?nameStartsWith=" + name + "&ts=" + ts + "&apikey=" + apikey + "&hash=" + hashStr; try { CloseableHttpClient cliente = HttpClients.createDefault(); //HttpHost proxy = new HttpHost("172.16.0.10", 3128, "http"); //RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); HttpGet httpget = new HttpGet(uri); //httpget.setConfig(config); HttpResponse response = cliente.execute(httpget); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); //Header[] h = (Header[]) response.getAllHeaders(); /*for (Header head : h) { System.out.println(head.getValue()); }*/ HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } //System.out.println(out.toString()); reader.close(); instream.close(); JsonParser parser = new JsonParser(); // find character's comics JsonElement comicResultElement = parser.parse(out.toString()); JsonObject comicDataWrapper = comicResultElement.getAsJsonObject(); JsonObject data = (JsonObject) comicDataWrapper.get("data"); JsonArray results = data.get("results").getAsJsonArray(); System.out.println(((JsonObject) results.get(0)).get("thumbnail")); } } catch (Exception e) { e.printStackTrace(); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get a specific device from Meshblu instance. * * @param device the device identifier (uuid) * @param clazz The class for this device. Meshblu works with any type of objects and * it is necessary deserialize the return to a valid object. * Note: The class parameter should be a extension of {@link AbstractThingDevice} * @return an object based on the class parameter * @throws KnotException KnotException/*from w w w . ja v a 2 s. c o m*/ */ public <T extends AbstractThingDevice> T getDevice(String device, Class<T> clazz) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get the specific device from meshblue instance final String endPoint = mEndPoint + DEVICE_PATH + device; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); if (jsonArray.size() == 0) { return null; } return mGson.fromJson(jsonArray.get(0).toString(), clazz); } catch (Exception e) { throw new KnotException(e); } }