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.api.dataset.lib.partitioned.PartitionKeyCodec.java

License:Apache License

@Override
public JsonElement serialize(PartitionKey partitionKey, Type type,
        JsonSerializationContext jsonSerializationContext) {
    JsonObject jsonObj = new JsonObject();
    for (Map.Entry<String, Comparable> entry : partitionKey.getFields().entrySet()) {
        jsonObj.add(entry.getKey(), serializeComparable(entry.getValue(), jsonSerializationContext));
    }/*from   w w w.j  ava2 s . com*/
    return jsonObj;
}

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 ww .j  av  a 2  s . c  o  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.etl.common.SetMultimapCodec.java

License:Apache License

@Override
public JsonElement serialize(SetMultimap<K, V> src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject obj = new JsonObject();
    obj.add("map", context.serialize(src.asMap()));
    return obj;//from  w w  w  .  jav a  2s.c  om
}

From source file:co.cask.cdap.etl.spark.batch.DatasetInfoTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(DatasetInfo src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("datasetName", src.getDatasetName());
    jsonObj.add("datasetArgs", context.serialize(src.getDatasetArgs()));
    if (src.getSplits() != null && !src.getSplits().isEmpty()) {
        jsonObj.addProperty("datasetSplitClass", src.getSplits().get(0).getClass().getName());
        jsonObj.add("datasetSplits", context.serialize(src.getSplits()));
    }// w  w w . j  av a2 s.c o m
    return jsonObj;
}

From source file:co.cask.cdap.etl.spark.batch.InputFormatProviderTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(InputFormatProvider src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("inputFormatClass", src.getInputFormatClassName());
    jsonObj.add("inputFormatConfig", context.serialize(src.getInputFormatConfiguration()));
    return jsonObj;
}

From source file:co.cask.cdap.etl.spark.batch.OutputFormatProviderTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(OutputFormatProvider src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("outputFormatClass", src.getOutputFormatClassName());
    jsonObj.add("outputFormatConfig", context.serialize(src.getOutputFormatConfiguration()));
    return jsonObj;
}

From source file:co.cask.cdap.gateway.handlers.ConsoleSettingsHttpHandler.java

License:Apache License

@Path("/")
@GET//from  ww  w.j  a v a2s . c o  m
public void get(HttpRequest request, HttpResponder responder) throws Exception {
    String userId = Objects.firstNonNull(SecurityRequestContext.getUserId(), "");
    Config userConfig;
    try {
        userConfig = store.get(userId);
    } catch (ConfigNotFoundException e) {
        Map<String, String> propMap = ImmutableMap.of(CONFIG_PROPERTY, "{}");
        userConfig = new Config(userId, propMap);
    }

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty(ID, userConfig.getId());

    //We store the serialized JSON string of the properties in ConfigStore and we return a JsonObject back
    jsonObject.add(CONFIG_PROPERTY, JSON_PARSER.parse(userConfig.getProperties().get(CONFIG_PROPERTY)));
    responder.sendJson(HttpResponseStatus.OK, jsonObject);
}

From source file:co.cask.cdap.gateway.handlers.DashboardHttpHandler.java

License:Apache License

@Path("/")
@GET// w ww  . j  av  a 2  s .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.handlers.DashboardHttpHandler.java

License:Apache License

@Path("/{dashboard-id}")
@GET//  www  . ja v  a 2  s  . c  o m
public void get(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespace,
        @PathParam("dashboard-id") String id) throws Exception {
    try {
        Config dashConfig = dashboardStore.get(namespace, id);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(ID, id);

        //Dashboard Config is stored in ConfigStore as serialized JSON string with CONFIG_PROPERTY key.
        //When we send the data back, we send it as JSON object instead of sending the serialized string.
        jsonObject.add(CONFIG_PROPERTY, JSON_PARSER.parse(dashConfig.getProperties().get(CONFIG_PROPERTY)));
        responder.sendJson(HttpResponseStatus.OK, jsonObject);
    } catch (ConfigNotFoundException e) {
        responder.sendString(HttpResponseStatus.NOT_FOUND, "Dashboard not found");
    }
}

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//www .  j a va 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;
    }
}