List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceAssignmentTypeAdapter.java
License:Apache License
@Override public JsonElement serialize(ResourceAssignment src, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); json.addProperty("name", src.getName()); src.getAssignments().entries();/* w w w . j av a2 s . co m*/ JsonArray assignments = new JsonArray(); for (Map.Entry<Discoverable, PartitionReplica> entry : src.getAssignments().entries()) { JsonArray entryJson = new JsonArray(); entryJson.add(context.serialize(entry.getKey(), Discoverable.class)); entryJson.add(context.serialize(entry.getValue())); assignments.add(entryJson); } json.add("assignments", assignments); return json; }
From source file:co.cask.cdap.common.zookeeper.coordination.ServiceDiscoveredCodec.java
License:Apache License
@Override public JsonElement serialize(ServiceDiscovered serviceDiscovered, Type typeOfSrc, JsonSerializationContext context) { JsonArray object = new JsonArray(); for (Discoverable discoverable : serviceDiscovered) { JsonObject discoverableJson = new JsonObject(); discoverableJson.addProperty("host", discoverable.getSocketAddress().getHostName()); discoverableJson.addProperty("port", discoverable.getSocketAddress().getPort()); object.add(discoverableJson); }/*w w w .j av a 2 s . c om*/ return object; }
From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java
License:Apache License
/** * Returns next scheduled runtime of a workflow. *//*from w w w .ja va 2 s . com*/ @GET @Path("/apps/{app-id}/workflows/{workflow-id}/nextruntime") public void getScheduledRunTime(HttpRequest request, HttpResponder responder, @PathParam("app-id") final String appId, @PathParam("workflow-id") final String workflowId) { try { String accountId = getAuthenticatedAccountId(request); Id.Program id = Id.Program.from(accountId, appId, workflowId); List<ScheduledRuntime> runtimes = scheduler.nextScheduledRuntime(id, ProgramType.WORKFLOW); JsonArray array = new JsonArray(); for (ScheduledRuntime runtime : runtimes) { JsonObject object = new JsonObject(); object.addProperty("id", runtime.getScheduleId()); object.addProperty("time", runtime.getTime()); array.add(object); } responder.sendJson(HttpResponseStatus.OK, array); } catch (SecurityException e) { responder.sendStatus(HttpResponseStatus.UNAUTHORIZED); } catch (Throwable e) { LOG.error("Got exception:", e); responder.sendStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); } }
From source file:co.cask.cdap.gateway.handlers.DashboardHttpHandler.java
License:Apache License
@Path("/") @GET/*from ww w . j a v a 2 s . c om*/ public void list(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespace) throws Exception { JsonArray jsonArray = new JsonArray(); List<Config> configList = dashboardStore.list(namespace); for (Config config : configList) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(ID, config.getId()); jsonObject.add(CONFIG_PROPERTY, JSON_PARSER.parse(config.getProperties().get(CONFIG_PROPERTY))); jsonArray.add(jsonObject); } responder.sendJson(HttpResponseStatus.OK, jsonArray); }
From source file:co.cask.cdap.gateway.router.handlers.SecurityAuthenticationHttpHandler.java
License:Apache License
/** * * @param externalAuthenticationURIs the list that should be populated with discovered with * external auth servers URIs * @throws Exception/* w w w. j a va2 s. c o m*/ */ private void stopWatchWait(JsonArray externalAuthenticationURIs) throws Exception { boolean done = false; Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); String protocol; int port; if (configuration.getBoolean(Constants.Security.SSL_ENABLED)) { protocol = "https"; port = configuration.getInt(Constants.Security.AuthenticationServer.SSL_PORT); } else { protocol = "http"; port = configuration.getInt(Constants.Security.AUTH_SERVER_BIND_PORT); } do { for (Discoverable d : discoverables) { String url = String.format("%s://%s:%d/%s", protocol, d.getSocketAddress().getHostName(), port, GrantAccessToken.Paths.GET_TOKEN); externalAuthenticationURIs.add(new JsonPrimitive(url)); done = true; } if (!done) { TimeUnit.MILLISECONDS.sleep(200); } } while (!done && stopwatch.elapsedTime(TimeUnit.SECONDS) < 2L); }
From source file:co.cask.cdap.metrics.query.BatchMetricsHandler.java
License:Apache License
@POST public void handleBatch(HttpRequest request, HttpResponder responder) throws IOException { if (!CONTENT_TYPE_JSON.equals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE))) { responder.sendError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, "Only " + CONTENT_TYPE_JSON + " is supported."); return;/*from w ww . j ava2 s. co m*/ } JsonArray output = new JsonArray(); Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8); String currPath = ""; try { // decode requests List<URI> uris = GSON.fromJson(reader, new TypeToken<List<URI>>() { }.getType()); LOG.trace("Requests: {}", uris); for (URI uri : uris) { currPath = uri.toString(); // if the request is invalid, this will throw an exception and return a 400 indicating the request // that is invalid and why. MetricsRequest metricsRequest = parseAndValidate(request, uri); JsonObject json = new JsonObject(); json.addProperty("path", metricsRequest.getRequestURI().toString()); json.add("result", requestExecutor.executeQuery(metricsRequest)); json.add("error", JsonNull.INSTANCE); output.add(json); } responder.sendJson(HttpResponseStatus.OK, output); } catch (MetricsPathException e) { responder.sendError(HttpResponseStatus.BAD_REQUEST, "Invalid path '" + currPath + "': " + e.getMessage()); } catch (OperationException e) { LOG.error("Exception querying metrics ", e); responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics"); } catch (ServerException e) { responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics"); } finally { reader.close(); } }
From source file:co.cask.cdap.metrics.query.MetricsDiscoveryHandler.java
License:Apache License
private void getMetrics(HttpRequest request, HttpResponder responder) { String contextPrefix = null;// ww w . j a v a 2 s.co m try { String path = request.getUri(); String base = Constants.Gateway.GATEWAY_VERSION + "/metrics/available/apps"; if (path.startsWith(base)) { Iterator<String> pathParts = Splitter.on('/').split(path.substring(base.length() + 1)).iterator(); MetricsRequestContext.Builder builder = new MetricsRequestContext.Builder(); MetricsRequestParser.parseSubContext(pathParts, builder); MetricsRequestContext metricsRequestContext = builder.build(); contextPrefix = metricsRequestContext.getContextPrefix(); validatePathElements(request, metricsRequestContext); } } catch (MetricsPathException e) { responder.sendError(HttpResponseStatus.NOT_FOUND, e.getMessage()); return; } catch (ServerException e) { responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while looking for metrics"); return; } // TODO(albert): add ability to pass in maxAge through query params Map<String, List<String>> queryParams = new QueryStringDecoder(request.getUri()).getParameters(); List<String> prefixEntity = queryParams.get("prefixEntity"); // shouldn't be in params more than once, but if it is, just take any one String metricPrefix = (prefixEntity == null || prefixEntity.isEmpty()) ? null : prefixEntity.get(0); Map<String, ContextNode> metricContextsMap = Maps.newHashMap(); for (AggregatesTable table : aggregatesTables.get().values()) { AggregatesScanner scanner = table.scanRowsOnly(contextPrefix, metricPrefix); // scanning through all metric rows in the aggregates table // row has context plus metric info // each metric can show up in multiple contexts while (scanner.hasNext()) { AggregatesScanResult result = scanner.next(); addContext(result.getContext(), result.getMetric(), metricContextsMap); } } // return the metrics sorted by metric name so it can directly be displayed to the user. JsonArray output = new JsonArray(); List<String> sortedMetrics = Lists.newArrayList(metricContextsMap.keySet()); Collections.sort(sortedMetrics); for (String metric : sortedMetrics) { JsonObject metricNode = new JsonObject(); metricNode.addProperty("metric", metric); ContextNode metricContexts = metricContextsMap.get(metric); // the root node has junk for its type and id, but has the list of contexts as its "children" metricNode.add("contexts", metricContexts.toJson().getAsJsonArray("children")); output.add(metricNode); } responder.sendJson(HttpResponseStatus.OK, output); }
From source file:color.GetColorMaster.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w.j a va2 s . c o m * * @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 { final DBHelper helper = DBHelper.GetDBHelper(); final Connection dataConnection = helper.getConnMpAdmin(); final JsonObject jResultObj = new JsonObject(); if (dataConnection != null) { try { String sql = "select COLOUR_CD,COLOUR_NAME,USER_ID from COLOURMST"; PreparedStatement pstLocal = dataConnection.prepareStatement(sql); ResultSet rsLocal = pstLocal.executeQuery(); JsonArray array = new JsonArray(); while (rsLocal.next()) { JsonObject object = new JsonObject(); object.addProperty("COLOUR_CD", rsLocal.getString("COLOUR_CD")); object.addProperty("COLOUR_NAME", rsLocal.getString("COLOUR_NAME")); object.addProperty("USER_ID", rsLocal.getInt("USER_ID")); array.add(object); } jResultObj.addProperty("result", 1); jResultObj.addProperty("Cause", "success"); jResultObj.add("data", array); } catch (SQLNonTransientConnectionException ex1) { jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", "Server is down"); } catch (SQLException ex) { jResultObj.addProperty("result", -1); jResultObj.addProperty("Cause", ex.getMessage()); } } response.getWriter().print(jResultObj); }
From source file:com.adobe.acs.commons.audit_log_search.impl.AuditLogSearchServlet.java
License:Apache License
@Override @SuppressWarnings("squid:S1141") protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { log.trace("doGet"); AuditLogSearchRequest req = null;/*from w w w.ja v a 2s. c o m*/ JsonObject result = new JsonObject(); boolean succeeded = true; try { req = new AuditLogSearchRequest(request); log.debug("Loaded search request: {}", req); JsonArray results = new JsonArray(); long count = 0; String whereClause = req.getQueryParameters(); StringBuilder queryBuilder = new StringBuilder("SELECT * FROM [cq:AuditEvent] AS s"); if (StringUtils.isNotEmpty(whereClause)) { queryBuilder.append(" WHERE ").append(whereClause); } String queryStr = queryBuilder.toString(); log.debug("Finding audit events with: {}", queryStr); ResourceResolver resolver = request.getResourceResolver(); QueryManager queryManager = resolver.adaptTo(Session.class).getWorkspace().getQueryManager(); Query query = queryManager.createQuery(queryStr, Query.JCR_SQL2); int limit = -1; if (StringUtils.isNotEmpty(request.getParameter("limit"))) { limit = Integer.parseInt(request.getParameter("limit"), 10); if (limit > 0) { log.debug("Limiting to {} results", limit); query.setLimit(limit); } } NodeIterator nodes = query.execute().getNodes(); log.debug("Query execution complete!"); while (nodes.hasNext()) { results.add(serializeAuditEvent(resolver.getResource(nodes.nextNode().getPath()), req)); count++; } result.addProperty("count", count); result.add("events", results); log.debug("Found {} audit events", count); } catch (ParseException e) { log.warn("Encountered exception parsing start / end date", e); succeeded = false; } catch (RepositoryException e) { log.warn("Encountered respository exception attempting to retrieve audit events", e); succeeded = false; } catch (ClassNotFoundException e) { log.warn("Encountered exception deserializing attributes", e); succeeded = false; } result.addProperty("succeeded", succeeded); response.setContentType("application/json"); response.getWriter().write(result.toString()); }
From source file:com.adobe.acs.commons.audit_log_search.impl.AuditLogSearchServlet.java
License:Apache License
private JsonObject serializeAuditEvent(Resource auditEventResource, AuditLogSearchRequest request) throws RepositoryException, IOException, ClassNotFoundException { JsonObject auditEvent = new JsonObject(); ValueMap properties = auditEventResource.getValueMap(); auditEvent.addProperty("category", properties.get("cq:category", String.class)); auditEvent.addProperty("eventPath", auditEventResource.getPath()); auditEvent.addProperty("path", properties.get("cq:path", String.class)); auditEvent.addProperty("type", properties.get("cq:type", String.class)); String userId = properties.get("cq:userid", String.class); auditEvent.addProperty("userId", userId); auditEvent.addProperty("userName", request.getUserName(auditEventResource.getResourceResolver(), userId)); auditEvent.addProperty("userPath", request.getUserPath(auditEventResource.getResourceResolver(), userId)); auditEvent.addProperty("time", properties.get("cq:time", new Date()).getTime()); JsonArray modified = getModifiedProperties(properties); if (properties.get("above", String.class) != null) { modified.add(new JsonPrimitive("above=" + properties.get("above", String.class))); }//from w w w . j a v a 2s . c o m if (properties.get("destination", String.class) != null) { modified.add(new JsonPrimitive("destination=" + properties.get("destination", String.class))); } if (properties.get("versionId", String.class) != null) { modified.add(new JsonPrimitive("versionId=" + properties.get("versionId", String.class))); } if (modified.size() != 0) { auditEvent.add("modified", modified); } return auditEvent; }