Example usage for com.google.gson JsonObject JsonObject

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

Introduction

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

Prototype

JsonObject

Source Link

Usage

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

License:Apache License

@Path("/system/services/{service-name}/status")
@GET/*from  ww w  .  j  a  va  2  s.co  m*/
public void monitor(final HttpRequest request, final HttpResponder responder,
        @PathParam("service-name") final String serviceName) {
    if (!serviceManagementMap.containsKey(serviceName)) {
        responder.sendString(HttpResponseStatus.NOT_FOUND,
                String.format("Invalid service name %s", serviceName));
        return;
    }
    MasterServiceManager masterServiceManager = serviceManagementMap.get(serviceName);
    if (!masterServiceManager.isServiceEnabled()) {
        responder.sendString(HttpResponseStatus.FORBIDDEN,
                String.format("Service %s is not enabled", serviceName));
        return;
    }
    if (masterServiceManager.canCheckStatus() && masterServiceManager.isServiceAvailable()) {
        JsonObject json = new JsonObject();
        json.addProperty("status", STATUSOK);
        responder.sendJson(HttpResponseStatus.OK, json);
    } else if (masterServiceManager.canCheckStatus()) {
        JsonObject json = new JsonObject();
        json.addProperty("status", STATUSNOTOK);
        responder.sendJson(HttpResponseStatus.OK, json);
    } else {
        responder.sendString(HttpResponseStatus.BAD_REQUEST, "Operation not valid for this service");
    }
}

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

License:Apache License

private void getScheduleStatus(HttpResponder responder, String appId, String namespaceId, String scheduleName)
        throws NotFoundException, SchedulerException {
    Id.Application applicationId = Id.Application.from(namespaceId, appId);
    ApplicationSpecification appSpec = store.getApplication(applicationId);
    if (appSpec == null) {
        throw new NotFoundException(applicationId);
    }/*from  www. j  a v a  2  s.c  o  m*/

    ScheduleSpecification scheduleSpec = appSpec.getSchedules().get(scheduleName);
    if (scheduleSpec == null) {
        throw new NotFoundException(scheduleName,
                String.format("Schedule: %s for application: %s", scheduleName, applicationId.getId()));
    }

    String programName = scheduleSpec.getProgram().getProgramName();
    ProgramType programType = ProgramType.valueOfSchedulableType(scheduleSpec.getProgram().getProgramType());
    Id.Program programId = Id.Program.from(namespaceId, appId, programType, programName);
    JsonObject json = new JsonObject();
    json.addProperty("status", scheduler
            .scheduleState(programId, programId.getType().getSchedulableType(), scheduleName).toString());
    responder.sendJson(HttpResponseStatus.OK, json);
}

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 2s.  c  o  m*/
 * @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.internal.app.ApplicationSpecificationCodec.java

License:Apache License

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

    jsonObj.add("name", new JsonPrimitive(src.getName()));
    if (src.getConfiguration() != null) {
        jsonObj.add("configuration", new JsonPrimitive(src.getConfiguration()));
    }/*from  w  w  w.  j a  va 2 s.c  o m*/
    jsonObj.add("artifactId", context.serialize(src.getArtifactId()));
    jsonObj.add("description", new JsonPrimitive(src.getDescription()));
    jsonObj.add("streams", serializeMap(src.getStreams(), context, StreamSpecification.class));
    jsonObj.add("datasetModules", serializeMap(src.getDatasetModules(), context, String.class));
    jsonObj.add("datasetInstances", serializeMap(src.getDatasets(), context, DatasetCreationSpec.class));
    jsonObj.add("flows", serializeMap(src.getFlows(), context, FlowSpecification.class));
    jsonObj.add("mapReduces", serializeMap(src.getMapReduce(), context, MapReduceSpecification.class));
    jsonObj.add("sparks", serializeMap(src.getSpark(), context, SparkSpecification.class));
    jsonObj.add("workflows", serializeMap(src.getWorkflows(), context, WorkflowSpecification.class));
    jsonObj.add("services", serializeMap(src.getServices(), context, ServiceSpecification.class));
    jsonObj.add("schedules", serializeMap(src.getSchedules(), context, ScheduleSpecification.class));
    jsonObj.add("workers", serializeMap(src.getWorkers(), context, WorkerSpecification.class));
    jsonObj.add("plugins", serializeMap(src.getPlugins(), context, Plugin.class));

    return jsonObj;
}

From source file:co.cask.cdap.internal.app.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(), new TypeToken<ResourceSpecification>() {
    }.getType()));/* ww w.  j  a v  a  2 s  .c o  m*/

    return jsonObj;
}

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

License:Apache License

@Override
public JsonElement serialize(FlowSpecification 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("flowlets", serializeMap(src.getFlowlets(), context, FlowletDefinition.class));
    jsonObj.add("connections", serializeList(src.getConnections(), context, FlowletConnection.class));

    return jsonObj;
}

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

License:Apache License

@Override
public JsonElement serialize(MapReduceSpecification 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("mapperMemoryMB", new JsonPrimitive(src.getMapperMemoryMB()));
    jsonObj.add("reducerMemoryMB", new JsonPrimitive(src.getReducerMemoryMB()));
    if (src.getInputDataSet() != null) {
        jsonObj.add("inputDataSet", new JsonPrimitive(src.getInputDataSet()));
    }//from  w  w  w  .  j a va  2  s.c om
    if (src.getOutputDataSet() != null) {
        jsonObj.add("outputDataSet", new JsonPrimitive(src.getOutputDataSet()));
    }
    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.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()));// www  .j  a v  a 2  s  . c  o m
    jsonObj.addProperty("instances", src.getInstances());
    return jsonObj;
}

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

License:Apache License

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

    jsonObj.add("virtualCores", new JsonPrimitive(src.getVirtualCores()));
    jsonObj.add("memoryMB", new JsonPrimitive(src.getMemoryMB()));

    return jsonObj;
}