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.gateway.handlers.AppFabricHttpHandler.java

License:Apache License

private void runnableStatus(HttpResponder responder, Id.Program id, ProgramType type) {
    try {//from w w  w  . j av  a2 s . c o  m
        ProgramStatus status = getProgramStatus(id, type);
        if (status.getStatus().equals(HttpResponseStatus.NOT_FOUND.toString())) {
            responder.sendStatus(HttpResponseStatus.NOT_FOUND);
        } else {
            JsonObject reply = new JsonObject();
            reply.addProperty("status", status.getStatus());
            responder.sendJson(HttpResponseStatus.OK, reply);
        }
    } 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.AppFabricHttpHandler.java

License:Apache License

/**
 * Returns next scheduled runtime of a workflow.
 *///from   w  w w  .  j a  v  a2s  .  c  o 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.AppFabricHttpHandler.java

License:Apache License

/**
 * Get schedule state./*from  ww  w .j a v a  2s.  c o  m*/
 */
@GET
@Path("/apps/{app-id}/workflows/{workflow-id}/schedules/{schedule-id}/status")
public void getScheuleState(HttpRequest request, HttpResponder responder,
        @PathParam("app-id") final String appId, @PathParam("workflow-id") final String workflowId,
        @PathParam("schedule-id") final String scheduleId) {
    try {
        // get the accountId to catch if there is a security exception
        String accountId = getAuthenticatedAccountId(request);
        JsonObject json = new JsonObject();
        json.addProperty("status", scheduler.scheduleState(scheduleId).toString());
        responder.sendJson(HttpResponseStatus.OK, json);
    } 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.ConsoleSettingsHttpHandler.java

License:Apache License

@Path("/")
@GET/*from  w w w. j a  v a 2s. 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//from  www .  j a v a  2s . com
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/*from  ww w . 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.handlers.MonitorHandler.java

License:Apache License

/**
 * Returns the number of instances of CDAP Services
 *///from  www. j  ava  2  s. c o m
@Path("/system/services/{service-name}/instances")
@GET
public void getServiceInstance(final HttpRequest request, final HttpResponder responder,
        @PathParam("service-name") String serviceName) throws Exception {
    JsonObject reply = new JsonObject();
    if (!serviceManagementMap.containsKey(serviceName)) {
        responder.sendString(HttpResponseStatus.NOT_FOUND,
                String.format("Invalid service name %s", serviceName));
        return;
    }
    MasterServiceManager serviceManager = serviceManagementMap.get(serviceName);
    if (serviceManager.isServiceEnabled()) {
        int actualInstance = serviceManagementMap.get(serviceName).getInstances();
        reply.addProperty("provisioned", actualInstance);
        reply.addProperty("requested", getSystemServiceInstanceCount(serviceName));
        responder.sendJson(HttpResponseStatus.OK, reply);
    } else {
        responder.sendString(HttpResponseStatus.FORBIDDEN,
                String.format("Service %s is not enabled", serviceName));
    }
}

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

License:Apache License

@Path("/system/services/{service-name}/status")
@GET//w  ww .  j  a v a 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   w w  w  .j  a  v  a2 s .  c  om*/

    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//from   w ww .j av  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;
    }
}