Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

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

License:Apache License

@Override
public JsonElement serialize(ProcedureSpecification 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));
    jsonObj.add("resources", context.serialize(src.getResources(), new TypeToken<ResourceSpecification>() {
    }.getType()));//  w w w  .  j a  v  a  2s.  c om
    jsonObj.addProperty("instances", src.getInstances());
    return jsonObj;
}

From source file:co.cask.cdap.internal.app.runtime.codec.ProgramOptionsCodec.java

License:Apache License

@Override
public JsonElement serialize(ProgramOptions src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject json = new JsonObject();
    json.addProperty("name", src.getName());
    json.add("arguments", context.serialize(src.getArguments(), Arguments.class));
    json.add("userArguments", context.serialize(src.getUserArguments(), Arguments.class));
    json.addProperty("debug", src.isDebug());

    return json;//w w w  .  j av a2s .co  m
}

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

License:Apache License

@Override
public JsonElement serialize(ServiceSpecification spec, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject object = new JsonObject();
    object.addProperty("className", spec.getClassName());
    object.addProperty("name", spec.getName());
    object.addProperty("description", spec.getDescription());
    object.add("handlers", serializeMap(spec.getHandlers(), context, HttpServiceHandlerSpecification.class));
    object.add("resources", context.serialize(spec.getResources(), Resources.class));
    object.addProperty("instances", spec.getInstances());
    return object;
}

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setWorkerInstances(String namespaceId, String appId, String workerId, int instances)
        throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/worker/%s/instances", getNamespacePath(namespaceId), appId,
            workerId);/*from   w  w  w .  ja  va2  s  .co  m*/
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setWorkerInstances(request, responder, namespaceId, appId, workerId);
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set worker instances failed");
}

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setServiceInstances(String namespaceId, String applicationId, String serviceName, int instances)
        throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/services/%s/instances", getNamespacePath(namespaceId), applicationId,
            serviceName);//from   w  w w.  j  a v  a2s.c o m
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setServiceInstances(request, responder, namespaceId, applicationId,
            serviceName);
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set service instances failed");
}

From source file:co.cask.cdap.internal.AppFabricClient.java

License:Apache License

public void setFlowletInstances(String namespaceId, String applicationId, String flowId, String flowletName,
        int instances) throws Exception {
    MockResponder responder = new MockResponder();
    String uri = String.format("%s/apps/%s/flows/%s/flowlets/%s/instances/%s", getNamespacePath(namespaceId),
            applicationId, flowId, flowletName, instances);
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uri);
    JsonObject json = new JsonObject();
    json.addProperty("instances", instances);
    request.setContent(ChannelBuffers.wrappedBuffer(json.toString().getBytes()));
    programLifecycleHttpHandler.setFlowletInstances(request, responder, namespaceId, applicationId, flowId,
            flowletName);/*from  w ww .  ja v a  2 s. c  om*/
    verifyResponse(HttpResponseStatus.OK, responder.getStatus(), "Set flowlet instances failed");
}

From source file:co.cask.cdap.logging.gateway.handlers.LogReaderCallback.java

License:Apache License

@Override
public void handle(LogEvent event) {
    String log = patternLayout.doLayout(event.getLoggingEvent());
    log = escape ? StringEscapeUtils.escapeHtml(log) : log;

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("log", log);
    jsonObject.addProperty("offset", event.getOffset());
    logResults.add(jsonObject);/*from www.ja  va  2  s .  c  o m*/
}

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 www .j  a v  a2  s. com
    }

    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  .j a va 2s  .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:co.cask.cdap.passport.meta.Account.java

License:Apache License

/**
 * @return {@code JsonElement} Json representation of Account object
 *//*w  ww. j  ava2  s .c om*/
public JsonElement toJson() {
    JsonObject object = new JsonObject();
    object.addProperty("id", getAccountId());
    object.addProperty("first_name", getFirstName());
    object.addProperty("last_name", getLastName());
    object.addProperty("company", getCompany());
    object.addProperty("email_id", getEmailId());
    object.addProperty("api_key", getApiKey());
    return object;
}