Example usage for com.google.gson JsonObject add

List of usage examples for com.google.gson JsonObject add

Introduction

In this page you can find the example usage for com.google.gson JsonObject add.

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

From source file:co.cask.cdap.internal.app.WorkflowActionSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(WorkflowActionSpecification src, Type typeOfSrc,
        JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();

    jsonObj.add("className", new JsonPrimitive(src.getClassName()));
    jsonObj.add("name", new JsonPrimitive(src.getName()));
    jsonObj.add("description", new JsonPrimitive(src.getDescription()));
    jsonObj.add("properties", serializeMap(src.getProperties(), context, String.class));

    return jsonObj;
}

From source file:co.cask.cdap.internal.app.WorkflowSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(WorkflowSpecification src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();

    jsonObj.add("className", new JsonPrimitive(src.getClassName()));
    jsonObj.add("name", new JsonPrimitive(src.getName()));
    jsonObj.add("description", new JsonPrimitive(src.getDescription()));
    jsonObj.add("actions", serializeList(src.getActions(), context, WorkflowActionSpecification.class));
    jsonObj.add("mapReduces", serializeMap(src.getMapReduce(), context, MapReduceSpecification.class));
    jsonObj.add("schedules", serializeList(src.getSchedules(), context, Schedule.class));

    return jsonObj;
}

From source file:co.cask.cdap.internal.filesystem.LocationCodec.java

License:Apache License

@Override
public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.add("uri", new JsonPrimitive(src.toURI().toASCIIString()));
    return jsonObj;
}

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 ww  w. j a v  a2 s  . c  om*/
    }

    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;//from w  w  w  .jav  a2 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:co.cask.cdap.proto.codec.BasicThrowableCodec.java

License:Apache License

@Override
public JsonElement serialize(BasicThrowable src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject json = new JsonObject();
    json.addProperty("className", src.getClassName());
    json.addProperty("message", src.getMessage());
    json.add("stackTraces", context.serialize(src.getStackTraces(), StackTraceElement[].class));
    json.add("cause", context.serialize(src.getCause(), BasicThrowable.class));
    return json;/*from w w  w  . j  a  va2  s.  c  om*/
}

From source file:co.cask.cdap.proto.codec.CustomActionSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(CustomActionSpecification src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();

    jsonObj.add("className", new JsonPrimitive(src.getClassName()));
    jsonObj.add("name", new JsonPrimitive(src.getName()));
    jsonObj.add("description", new JsonPrimitive(src.getDescription()));
    jsonObj.add("datasets", serializeSet(src.getDatasets(), context, String.class));
    jsonObj.add("properties", serializeMap(src.getProperties(), context, String.class));

    return jsonObj;
}

From source file:co.cask.cdap.proto.codec.FlowletSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(FlowletSpecification src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();

    jsonObj.add("className", new JsonPrimitive(src.getClassName()));
    jsonObj.add("name", new JsonPrimitive(src.getName()));
    jsonObj.add("description", new JsonPrimitive(src.getDescription()));
    jsonObj.add("failurePolicy", new JsonPrimitive(src.getFailurePolicy().name()));
    jsonObj.add("datasets", serializeSet(src.getDataSets(), context, String.class));
    jsonObj.add("properties", serializeMap(src.getProperties(), context, String.class));
    jsonObj.add("resources", context.serialize(src.getResources(), Resources.class));

    return jsonObj;
}

From source file:co.cask.cdap.proto.codec.HttpServiceSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(HttpServiceHandlerSpecification src, Type typeOfSrc,
        JsonSerializationContext context) {
    JsonObject json = new JsonObject();
    json.addProperty("className", src.getClassName());
    json.addProperty("name", src.getName());
    json.addProperty("description", src.getDescription());
    json.add("properties", serializeMap(src.getProperties(), context, String.class));
    json.add("datasets", serializeSet(src.getDatasets(), context, String.class));
    json.add("endpoints", serializeList(src.getEndpoints(), context, ServiceHttpEndpoint.class));

    return json;/*w w  w  . ja  v a  2s.c  o m*/
}

From source file:co.cask.cdap.proto.codec.MapReduceSpecificationCodec.java

License:Apache License

@Override
public JsonElement serialize(MapReduceSpecification src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();

    jsonObj.addProperty("className", src.getClassName());
    jsonObj.addProperty("name", src.getName());
    jsonObj.addProperty("description", src.getDescription());

    if (src.getDriverResources() != null) {
        jsonObj.add("driverResources", context.serialize(src.getDriverResources()));
    }//from  w  w  w  .  j ava  2  s .  c  o  m
    if (src.getMapperResources() != null) {
        jsonObj.add("mapperResources", context.serialize(src.getMapperResources()));
    }
    if (src.getReducerResources() != null) {
        jsonObj.add("reducerResources", context.serialize(src.getReducerResources()));
    }
    if (src.getInputDataSet() != null) {
        jsonObj.addProperty("inputDataSet", src.getInputDataSet());
    }
    if (src.getOutputDataSet() != null) {
        jsonObj.addProperty("outputDataSet", src.getOutputDataSet());
    }
    jsonObj.add("datasets", serializeSet(src.getDataSets(), context, String.class));
    jsonObj.add("properties", serializeMap(src.getProperties(), context, String.class));

    return jsonObj;
}