List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java
License:Apache License
@Override public JsonElement serialize(EventMessageBundle src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray events = new JsonArray(); for (Event event : src.getEvents()) { try {/*from w w w .j a v a2 s .c o m*/ events.add(EventSerializer.serialize(event, context)); } catch (EventSerializationException e) { throw new JsonParseException(e); } } result.add(EVENTS_TAG, events); result.add(WAVELET_TAG, context.serialize(src.getWaveletData())); result.add(BLIPS_TAG, context.serialize(src.getBlipData())); result.add(THREADS_TAG, context.serialize(src.getThreads())); result.addProperty(ROBOT_ADDRESS_TAG, src.getRobotAddress()); String proxyingFor = src.getProxyingFor(); if (proxyingFor != null && !proxyingFor.isEmpty()) { result.addProperty(PROXYING_FOR_TAG, proxyingFor); } String rpcServerUrl = src.getRpcServerUrl(); if (rpcServerUrl != null && !rpcServerUrl.isEmpty()) { result.addProperty(RPC_SERVER_URL_TAG, rpcServerUrl); } return result; }
From source file:com.google.wave.api.RobotSerializer.java
License:Apache License
/** * Deserializes operations. This method supports only the new JSON-RPC style * operations.//ww w. j a va 2s . c o m * * @param jsonString the operations JSON string to deserialize. * @return a list of {@link OperationRequest},that represents the operations. * @throws InvalidRequestException if there is a problem deserializing the * operations. */ public List<OperationRequest> deserializeOperations(String jsonString) throws InvalidRequestException { if (Util.isEmptyOrWhitespace(jsonString)) { return Collections.emptyList(); } // Parse incoming operations. JsonArray requestsAsJsonArray = null; JsonElement json = null; try { json = jsonParser.parse(jsonString); } catch (JsonParseException e) { throw new InvalidRequestException("Couldn't deserialize incoming operations: " + jsonString, null, e); } if (json.isJsonArray()) { requestsAsJsonArray = json.getAsJsonArray(); } else { requestsAsJsonArray = new JsonArray(); requestsAsJsonArray.add(json); } // Convert incoming operations into a list of JsonRpcRequest. ProtocolVersion protocolVersion = determineProtocolVersion(requestsAsJsonArray); PROTOCOL_VERSION_COUNTERS.get(protocolVersion).incrementAndGet(); List<OperationRequest> requests = new ArrayList<OperationRequest>(requestsAsJsonArray.size()); for (JsonElement requestAsJsonElement : requestsAsJsonArray) { validate(requestAsJsonElement); requests.add(getGson(protocolVersion).fromJson(requestAsJsonElement, OperationRequest.class)); } return requests; }
From source file:com.googlesource.gerrit.plugins.github.wizard.PullRequestListController.java
License:Apache License
@Override public void doAction(IdentifiedUser user, GitHubLogin hubLogin, HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) throws ServletException, IOException { PrintWriter out = resp.getWriter(); SimpleDateFormat dateFmt = new SimpleDateFormat(DATE_FMT); String organisation = req.getParameter("organisation"); String repository = req.getParameter("repository"); Map<String, List<GHPullRequest>> pullRequests = getPullRequests(hubLogin, organisation, repository); JsonArray reposPullRequests = new JsonArray(); for (Entry<String, List<GHPullRequest>> repoEntry : pullRequests.entrySet()) { JsonObject repoPullRequests = new JsonObject(); repoPullRequests.add("repository", new JsonPrimitive(repoEntry.getKey())); if (repoEntry.getValue() != null) { JsonArray prArray = new JsonArray(); for (GHPullRequest pr : repoEntry.getValue()) { JsonObject prObj = new JsonObject(); prObj.add("id", new JsonPrimitive(pr.getNumber())); prObj.add("title", new JsonPrimitive(pr.getTitle())); prObj.add("body", new JsonPrimitive(pr.getBody())); prObj.add("author", new JsonPrimitive(pr.getUser() == null ? "" : pr.getUser().getLogin())); prObj.add("status", new JsonPrimitive(pr.getState().name())); prObj.add("date", new JsonPrimitive(dateFmt.format(pr.getUpdatedAt()))); prArray.add(prObj); }/*from ww w . ja v a 2 s.c om*/ repoPullRequests.add("pullrequests", prArray); } reposPullRequests.add(repoPullRequests); } out.println(reposPullRequests.toString()); }
From source file:com.googlesource.gerrit.plugins.github.wizard.RepositoriesListController.java
License:Apache License
@Override public void doAction(IdentifiedUser user, GitHubLogin hubLogin, HttpServletRequest req, HttpServletResponse resp, ControllerErrors errors) throws ServletException, IOException { String organisation = req.getParameter("organisation"); JsonArray jsonRepos = new JsonArray(); int numRepos = 0; PagedIterator<GHRepository> repoIter = getRepositories(hubLogin, organisation).iterator(); while (repoIter.hasNext() && numRepos < config.repositoryListLimit) { GHRepository ghRepository = repoIter.next(); JsonObject repository = new JsonObject(); String projectName = organisation + "/" + ghRepository.getName(); if (projects.get(Project.NameKey.parse(projectName)) == null) { repository.add("name", new JsonPrimitive(ghRepository.getName())); repository.add("organisation", new JsonPrimitive(organisation)); repository.add("description", new JsonPrimitive(Strings.nullToEmpty(ghRepository.getDescription()))); repository.add("private", new JsonPrimitive(ghRepository.isPrivate())); jsonRepos.add(repository); numRepos++;//from w ww . j a v a 2s .c om } } resp.getWriter().println(jsonRepos.toString()); }
From source file:com.googlesource.gerrit.plugins.replication.ListCommand.java
License:Apache License
private void addProperty(JsonObject obj, String key, List<String> values) { if (!values.isEmpty()) { JsonArray list = new JsonArray(); for (String v : values) { list.add(new JsonPrimitive(v)); }/* www . ja v a 2 s . c o m*/ obj.add(key, list); } }
From source file:com.googlesource.gerrit.plugins.replication.ListCommand.java
License:Apache License
private void addQueueDetails(JsonObject obj, String key, Collection<PushOne> values) { if (values.size() > 0) { JsonArray list = new JsonArray(); for (PushOne p : values) { list.add(new JsonPrimitive(p.toString())); }/*from w w w . j a v a 2s. co m*/ obj.add(key, list); } }
From source file:com.googlesource.gerrit.plugins.verifystatus.VerifyStatusQueryShell.java
License:Apache License
/** * Outputs a result set to stdout in Json format. * * @param rs ResultSet to show./*from w ww. j av a 2 s. c om*/ * @param alreadyOnRow true if rs is already on the first row. false otherwise. * @param start Timestamp in milliseconds when executing the statement started. This timestamp is * used to compute statistics about the statement. If no statistics should be shown, set it to * 0. * @param show Functions to map columns * @throws SQLException */ private void showResultSetJson(final ResultSet rs, boolean alreadyOnRow, long start, Function... show) throws SQLException { JsonArray collector = new JsonArray(); final ResultSetMetaData meta = rs.getMetaData(); final Function[] columnMap; if (show != null && 0 < show.length) { columnMap = show; } else { final int colCnt = meta.getColumnCount(); columnMap = new Function[colCnt]; for (int colId = 0; colId < colCnt; colId++) { final int p = colId + 1; final String name = meta.getColumnLabel(p); columnMap[colId] = new Identity(p, name); } } int rowCnt = 0; while (alreadyOnRow || rs.next()) { final JsonObject row = new JsonObject(); final JsonObject cols = new JsonObject(); for (Function function : columnMap) { String v = function.apply(rs); if (v == null) { continue; } cols.addProperty(function.name.toLowerCase(), v); } row.addProperty("type", "row"); row.add("columns", cols); switch (outputFormat) { case JSON: println(row.toString()); break; case JSON_SINGLE: collector.add(row); break; case PRETTY: default: final JsonObject obj = new JsonObject(); obj.addProperty("type", "error"); obj.addProperty("message", "Unsupported Json variant"); println(obj.toString()); return; } alreadyOnRow = false; rowCnt++; } JsonObject tail = null; if (start != 0) { tail = new JsonObject(); tail.addProperty("type", "query-stats"); tail.addProperty("rowCount", rowCnt); final long ms = TimeUtil.nowMs() - start; tail.addProperty("runTimeMilliseconds", ms); } switch (outputFormat) { case JSON: if (tail != null) { println(tail.toString()); } break; case JSON_SINGLE: if (tail != null) { collector.add(tail); } println(collector.toString()); break; case PRETTY: default: final JsonObject obj = new JsonObject(); obj.addProperty("type", "error"); obj.addProperty("message", "Unsupported Json variant"); println(obj.toString()); } }
From source file:com.grameenfoundation.cropinfo.manager.CropDetailManager.java
public JsonObject cropDetailJSON(String[] crops, String region, String date) { LOGGER.info("in JSON Object"); JsonObject jsonObject = new JsonObject(); CropDetail cropDetail = null;//from w w w .j a va2 s .co m //get crop detail Model object CropDetailModel cropDetailModel = (CropDetailModel) ModelFactory.getModel(FactoryId.CROPDETAIL); jsonObject.addProperty("rc", "00"); JsonArray jsonArray = new JsonArray(); for (String crop : crops) { JsonObject json = new JsonObject(); cropDetail = cropDetailModel.getActivity(crop, region, date); LOGGER.log(Level.INFO, "Crop Details retrieval failed {0}", cropDetail); if (null != cropDetail) { json.addProperty("crop", cropDetail.getCrop()); json.addProperty("activity", cropDetail.getActivity()); } else { json.addProperty("crop", crop); json.addProperty("activity", "no activity"); } jsonArray.add(json); } jsonObject.add("cropDtl", jsonArray); return jsonObject; }
From source file:com.grarak.cafntracker.Tracker.java
License:Apache License
private Tracker(int port, String api, ArrayList<Repo> repos) throws IOException { File idsFile = new File("ids.json"); if (idsFile.exists()) { String content = Utils.readFile(idsFile); JsonArray array = new JsonParser().parse(content).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { mIds.add(array.get(i).getAsString().trim()); }/*from w w w . j a v a2s . c o m*/ } for (Repo repo : repos) { try { repo.script_content = Utils.resourceFileReader( getClass().getClassLoader().getResourceAsStream("parsers/" + repo.content_script)); } catch (IOException ignored) { Log.e(TAG, "Failed to read " + repo.content_script); return; } } new Thread(() -> { while (true) { for (Repo repo : repos) { File file = new File("repos/" + repo.name); if (!file.exists()) { Log.i(TAG, "Cloning " + repo.name); try { Utils.executeProcess("git clone " + repo.link + " " + file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Failed cloning " + repo.name); } } try { String tags = Utils.executeProcess("git -C " + file.getAbsolutePath() + " tag"); repo.tags = Arrays.asList(tags.split("\\r?\\n")); Log.i(TAG, repo.tags.size() + " tags found for " + repo.name); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Failed getting tags from " + repo.name); } try { Log.i(TAG, "Sleeping"); Thread.sleep(10000); Utils.executeProcess("git -C " + file.getAbsolutePath() + " fetch origin"); String tags = Utils.executeProcess("git -C " + file.getAbsolutePath() + " tag"); List<String> curTags = Arrays.asList(tags.split("\\r?\\n")); List<String> newTags = curTags.stream() .filter(tag -> !repo.tags.contains(tag) && !tag.startsWith("android-")) .collect(Collectors.toList()); for (String newTag : newTags) { File parserScript = new File("parse_script.sh"); Utils.writeFile(repo.script_content, parserScript, false); Utils.executeProcess("chmod a+x " + parserScript.getAbsolutePath()); String content = Utils.executeProcess( parserScript.getAbsolutePath() + " " + file.getAbsolutePath() + " " + newTag); for (String id : mIds) { try { Request.post(id, api, repo.name, content, newTag, String.format(repo.tag_link, newTag)); } catch (Exception e) { e.printStackTrace(); Log.i(TAG, "Failed to send post request to " + id); } } } } catch (Exception e) { e.printStackTrace(); Log.i(TAG, "Failed to update tags for " + repo.name); } } } }).start(); Log.i(TAG, "Start listening on port " + port); SSLServerSocketFactory ssf = loadKeyStore().getServerSocketFactory(); SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(port); while (true) { try { SSLSocket socket = (SSLSocket) s.accept(); String address = socket.getRemoteSocketAddress().toString(); Log.i(TAG, "Connected to " + address); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); byte[] buffer = new byte[8192]; dataInputStream.read(buffer); String id = new String(buffer).trim(); Log.i(TAG, id); JsonArray repoList = new JsonArray(); for (Repo repo : repos) { JsonObject repoObject = new JsonObject(); repoObject.addProperty("name", repo.name); repoObject.addProperty("content_name", repo.content_name); repoList.add(repoObject); } DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.write(repoList.toString().getBytes()); if (!mIds.contains(id)) { mIds.add(id); JsonArray array = new JsonArray(); mIds.forEach(array::add); Utils.writeFile(array.toString(), idsFile, false); } dataInputStream.close(); socket.close(); } catch (IOException ignored) { Log.e(TAG, "Failed to connect to client"); } } }
From source file:com.gst.batch.service.ResolutionHelper.java
License:Apache License
private JsonArray processJsonArray(final JsonArray elementArray, final JsonModel responseJsonModel) { JsonArray valueArr = new JsonArray(); for (JsonElement element : elementArray) { if (element.isJsonObject()) { final JsonObject jsObject = element.getAsJsonObject(); valueArr.add(processJsonObject(jsObject, responseJsonModel)); }//from w w w . ja va2 s .com } return valueArr; }