List of usage examples for com.google.gson JsonArray JsonArray
public JsonArray()
From source file:co.cask.cdap.gateway.handlers.AppFabricHttpHandler.java
License:Apache License
/** * Returns next scheduled runtime of a workflow. *//*from w w w . j av a2 s .co m*/ @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 .java 2s . c o m*/ 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
/** * Intercepts the HttpMessage for getting the access token in authorization header * @param ctx channel handler context delegated from MessageReceived callback * @param msg intercepted HTTP message// w w w . jav a 2 s. c om * @param inboundChannel * @return {@code true} if the HTTP message has valid Access token * @throws Exception */ private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel, AuditLogEntry logEntry) throws Exception { String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION); String accessToken = null; /* * Parse the access token from authorization header. The header will be in the form: * Authorization: Bearer ACCESSTOKEN * * where ACCESSTOKEN is the base64 encoded serialized AccessToken instance. */ if (auth != null) { int spIndex = auth.trim().indexOf(' '); if (spIndex != -1) { accessToken = auth.substring(spIndex + 1).trim(); } } logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress()); logEntry.setRequestLine(msg.getMethod(), msg.getUri(), msg.getProtocolVersion()); TokenState tokenState = tokenValidator.validate(accessToken); if (!tokenState.isValid()) { HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode()); JsonObject jsonObject = new JsonObject(); if (tokenState == TokenState.MISSING) { httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm)); LOG.debug("Authentication failed due to missing token"); } else { httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\" error=\"invalid_token\"" + " error_description=\"%s\"", realm, tokenState.getMsg())); jsonObject.addProperty("error", "invalid_token"); jsonObject.addProperty("error_description", tokenState.getMsg()); LOG.debug("Authentication failed due to invalid token, reason={};", tokenState); } JsonArray externalAuthenticationURIs = new JsonArray(); //Waiting for service to get discovered stopWatchWait(externalAuthenticationURIs); jsonObject.add("auth_uri", externalAuthenticationURIs); ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8)); httpResponse.setContent(content); int contentLength = content.readableBytes(); httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength); httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8"); logEntry.setResponseContentLength(new Long(contentLength)); ChannelFuture writeFuture = Channels.future(inboundChannel); Channels.write(ctx, writeFuture, httpResponse); writeFuture.addListener(ChannelFutureListener.CLOSE); return false; } else { AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair = accessTokenTransformer .transform(accessToken); logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername()); msg.setHeader(HttpHeaders.Names.AUTHORIZATION, "CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr()); msg.setHeader(Constants.Security.Headers.USER_ID, accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername()); msg.setHeader(Constants.Security.Headers.USER_IP, ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress()); return true; } }
From source file:co.cask.cdap.logging.gateway.handlers.LogReaderCallback.java
License:Apache License
LogReaderCallback(HttpResponder responder, String logPattern, boolean escape) { this.logResults = new JsonArray(); this.responder = responder; this.escape = escape; ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory .getLogger(Logger.ROOT_LOGGER_NAME); LoggerContext loggerContext = rootLogger.getLoggerContext(); this.patternLayout = new PatternLayout(); this.patternLayout.setContext(loggerContext); this.patternLayout.setPattern(logPattern); }
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;// w w w .j a v a 2 s . c o 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;// w w w.java 2 s . c o 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 ww . j ava 2 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;/* w w w .ja va2s . c om*/ 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
@SuppressWarnings("unchecked") private JsonArray getModifiedProperties(ValueMap properties) throws IOException { JsonArray modifiedProperties = new JsonArray(); InputStream is = properties.get("cq:properties", InputStream.class); if (is != null) { ObjectInputStream ois = new ObjectInputStream(is); ois.readInt();// w w w. j ava 2s. c om while (ois.available() != -1) { try { Object obj = ois.readObject(); if (obj instanceof HashSet) { Set<String> propertiesSet = (Set<String>) obj; for (String property : propertiesSet) { modifiedProperties.add(new JsonPrimitive(property)); } break; } } catch (Exception e) { break; } } } return modifiedProperties; }
From source file:com.adobe.acs.commons.dam.impl.CustomComponentActivatorListServlet.java
License:Apache License
@Activate protected void activate(Config conf) { Map<String, String> components = ParameterUtil .toMap(PropertiesUtil.toStringArray(conf.components(), DEFAULT_COMPONENTS), "="); JsonArray array = new JsonArray(); for (Map.Entry<String, String> entry : components.entrySet()) { JsonObject obj = new JsonObject(); obj.addProperty("propertyName", entry.getKey()); obj.addProperty("componentPath", entry.getValue()); array.add(obj);/*from ww w .ja v a 2 s. co m*/ } this.json = new JsonObject(); json.add("components", array); }