Example usage for com.google.gson JsonObject has

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

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:com.cloudant.http.interceptors.CookieInterceptor.java

License:Open Source License

private boolean sessionHasStarted(InputStream responseStream) {
    try {//w  w  w  . java  2 s . co  m
        //check the response body
        Gson gson = new Gson();
        JsonObject jsonResponse = gson.fromJson(new InputStreamReader(responseStream, "UTF-8"),
                JsonObject.class);

        // only check for ok:true, https://issues.apache.org/jira/browse/COUCHDB-1356
        // means we cannot check that the name returned is the one we sent.
        return jsonResponse != null && jsonResponse.has("ok") && jsonResponse.get("ok").isJsonPrimitive()
                && jsonResponse.getAsJsonPrimitive("ok").isBoolean()
                && jsonResponse.getAsJsonPrimitive("ok").getAsBoolean();
    } catch (UnsupportedEncodingException e) {
        //UTF-8 should be supported on all JVMs
        throw new RuntimeException(e);
    }
}

From source file:com.collaide.fileuploader.requests.repository.RepositoryRequest.java

/**
 * get infos about a elements of a repository represented by an id
 *
 * @param id the id of the elements//  w  w w  . ja  va 2 s .  c om
 * @return Repository a set of folders and files present on the server
 */
public Repository get(int id) {
    Repository repo = null;
    try {
        JsonObject repoItems = getResponseToJsonElement(
                doGet(getRepoItemUrl(id) + "?" + CurrentUser.getAuthParams())).getAsJsonObject();
        if (repoItems.has("children") && repoItems.get("children").isJsonArray()) {
            repo = getRepository(repoItems.get("children").getAsJsonArray());
            repo.setRepoItem(gson.fromJson(repoItems, RepoItems.class));
        }
    } catch (NotSuccessRequest ex) {
        notSuccesLog("get/" + String.valueOf(id), ex);
    }
    return repo;
}

From source file:com.confighub.api.repository.client.v1.APIPush.java

License:Open Source License

private void pushData(final String postJson, final String appName, final Gson gson, final Store store,
        final boolean forcePushEnabled, final Token token) throws ConfigException {
    JsonObject jsonObject = gson.fromJson(postJson, JsonObject.class);

    String changeComment = jsonObject.has("changeComment") ? jsonObject.get("changeComment").getAsString()
            : null;// ww w.  j  av a2s . c  om

    boolean enableKeyCreation = jsonObject.has("enableKeyCreation")
            ? jsonObject.get("enableKeyCreation").getAsBoolean()
            : false || forcePushEnabled;

    JsonArray arr = jsonObject.getAsJsonArray("data");
    store.begin();

    for (int i = 0; i < arr.size(); i++) {
        JsonObject entry = gson.fromJson(arr.get(i), JsonObject.class);

        //////////////////////////////////////////////////////////////
        // Parse file entry
        //////////////////////////////////////////////////////////////
        if (entry.has("file")) {
            try {
                String absPath = entry.get("file").getAsString();
                String content = entry.has("content") ? entry.get("content").getAsString() : "";
                boolean active = entry.has("active") ? entry.get("active").getAsBoolean() : true;
                String spName = entry.has("securityGroup") ? entry.get("securityGroup").getAsString() : null;
                String spPassword = entry.has("password") ? entry.get("password").getAsString() : null;

                int li = absPath.lastIndexOf("/");

                String path = li > 0 ? absPath.substring(0, li) : "";
                String fileName = li > 0 ? absPath.substring(li + 1, absPath.length()) : absPath;

                String contextString = entry.get("context").getAsString();
                Set<CtxLevel> context = ContextParser.parseAndCreateViaApi(contextString, repository, store,
                        appName, changeComment);

                RepoFile file = store.getRepoFile(repository, absPath, context, null);

                boolean isDelete = entry.has("opp") ? "delete".equalsIgnoreCase(entry.get("opp").getAsString())
                        : false;

                if (null == file) {
                    if (isDelete) {
                        continue;
                    }

                    store.createRepoFile(appName, repository, token, path, fileName, content, context, active,
                            spName, spPassword, changeComment);
                } else {
                    if (isDelete) {
                        store.deleteRepoFile(appName, repository, token, file.getId(), changeComment);
                    } else {
                        store.updateRepoFile(appName, repository, token, file.getId(), path, fileName, content,
                                context, active, spName, spPassword, spPassword, changeComment);
                    }
                }
            } catch (ConfigException e) {
                throw new ConfigException(e.getErrorCode(), entry);
            }
        }
    }

    for (int i = 0; i < arr.size(); i++) {
        JsonObject entry = gson.fromJson(arr.get(i), JsonObject.class);

        //////////////////////////////////////////////////////////////
        // Parse key entry
        //////////////////////////////////////////////////////////////
        if (entry.has("key")) {
            String key = entry.get("key").getAsString();
            PropertyKey.ValueDataType valueDataType = PropertyKey.ValueDataType.Text;
            try {
                valueDataType = entry.has("vdt")
                        ? PropertyKey.ValueDataType.valueOf(entry.get("vdt").getAsString())
                        : PropertyKey.ValueDataType.Text;
            } catch (Exception ignore) {
            }

            boolean isDeleteKey = entry.has("opp") ? "delete".equalsIgnoreCase(entry.get("opp").getAsString())
                    : false;

            PropertyKey propertyKey = store.getKey(repository, key);
            if (null == propertyKey) {
                if (isDeleteKey) {
                    continue;
                }

                if (!enableKeyCreation) {
                    throw new ConfigException(Error.Code.KEY_CREATION_VIA_API_DISABLED, entry);
                }

                propertyKey = new PropertyKey(repository, key, valueDataType);
            } else if (!propertyKey.isPushValueEnabled() && !forcePushEnabled) {
                JsonObject ej = new JsonObject();
                ej.addProperty("key", key);
                ej.addProperty("push", false);
                throw new ConfigException(Error.Code.PUSH_DISABLED, ej);
            } else if (repository.isValueTypeEnabled()) {
                propertyKey.setValueDataType(valueDataType);
            }

            if (entry.has("securityGroup") && entry.has("password")) {
                String spName = entry.get("securityGroup").getAsString();
                String password = entry.get("password").getAsString();

                passwords.put(spName, password);

                if (!Utils.anyBlank(spName, password)) {
                    SecurityProfile sp = store.getSecurityProfile(repository, null, spName);
                    if (null == sp) {
                        JsonObject ej = new JsonObject();
                        ej.addProperty("securityGroup", spName);
                        throw new ConfigException(Error.Code.MISSING_SECURITY_PROFILE, ej);
                    }

                    propertyKey.setSecurityProfile(sp, password);
                }
            }

            if (isDeleteKey) {
                String pass = propertyKey.isSecure() ? passwords.get(propertyKey.getSecurityProfile().getName())
                        : null;

                store.deleteKeyAndProperties(appName, repository, token, key, pass, changeComment);
                continue;
            }

            if (entry.has("readme") && !entry.get("readme").isJsonNull()) {
                propertyKey.setReadme(entry.get("readme").getAsString());
            }

            if (entry.has("deprecated")) {
                propertyKey.setDeprecated(entry.get("deprecated").getAsBoolean());
            }

            if (entry.has("push")) {
                propertyKey.setPushValueEnabled(entry.get("push").getAsBoolean());
            }

            if (entry.has("values")) {
                JsonArray values = gson.fromJson(entry.get("values"), JsonArray.class);

                for (int j = 0; j < values.size(); j++) {
                    JsonObject valueJson = gson.fromJson(values.get(j), JsonObject.class);

                    if (!valueJson.has("context")) {
                        JsonObject ej = new JsonObject();
                        ej.addProperty("key", key);
                        ej.addProperty("push", false);

                        throw new ConfigException(Error.Code.CONTEXT_NOT_SPECIFIED, ej);
                    }

                    try {
                        String context = valueJson.get("context").getAsString();
                        Set<CtxLevel> ctxLevels = ContextParser.parseAndCreateViaApi(context, repository, store,
                                appName, changeComment);

                        Property property = propertyKey.getPropertyForContext(ctxLevels);

                        boolean isDelete = valueJson.has("opp")
                                ? "delete".equalsIgnoreCase(valueJson.get("opp").getAsString())
                                : false;

                        if (null == property) {
                            if (isDelete) {
                                continue;
                            }

                            property = new Property(repository);
                            property.setPropertyKey(propertyKey);
                            property.setActive(true);
                        } else if (isDelete) {
                            String pass = propertyKey.isSecure()
                                    ? passwords.get(propertyKey.getSecurityProfile().getName())
                                    : null;

                            store.deleteProperty(appName, repository, token, property.getId(), pass,
                                    changeComment);
                            continue;
                        }

                        if (valueJson.has("value")) {
                            String pass = propertyKey.isSecure()
                                    ? passwords.get(propertyKey.getSecurityProfile().getName())
                                    : null;

                            String value = "";
                            switch (propertyKey.getValueDataType()) {
                            case FileEmbed:
                            case FileRef:
                                if (valueJson.get("value").isJsonNull()) {
                                    throw new ConfigException(Error.Code.FILE_NOT_FOUND, entry);
                                }

                                value = valueJson.get("value").getAsString();
                                AbsoluteFilePath absoluteFilePath = store.getAbsFilePath(repository, value,
                                        null);
                                if (null == absoluteFilePath) {
                                    throw new ConfigException(Error.Code.FILE_NOT_FOUND, entry);
                                }

                                property.setAbsoluteFilePath(absoluteFilePath);
                                break;

                            case List:
                            case Map:
                                if (valueJson.get("value").isJsonNull()) {
                                    property.setValue(null, pass);
                                } else {
                                    property.setValue(valueJson.get("value").getAsString(), pass);
                                }
                                break;

                            default:
                                if (valueJson.get("value").isJsonNull()) {
                                    property.setValue(null, pass);
                                } else {
                                    property.setValue(valueJson.get("value").getAsString(), pass);
                                }
                                break;
                            }
                        }

                        if (valueJson.has("active")) {
                            property.setActive(valueJson.get("active").getAsBoolean());
                        }

                        property.setContext(ctxLevels);
                        store.saveProperty(appName, repository, token, property, changeComment);
                    } catch (ConfigException e) {
                        throw new ConfigException(e.getErrorCode(), entry);
                    }
                }
            }

            if (propertyKey.dirty) {
                store.savePropertyKey(appName, repository, token, propertyKey, changeComment);
            }
        }
    }

    store.commit();
}

From source file:com.confighub.core.repository.AContextAwarePersistent.java

License:Open Source License

public Map<String, LevelCtx> getDepthMap() throws ConfigException {
    if (null == depthMap) {
        depthMap = new HashMap<>();

        JsonArray json = getContextJsonObj();

        for (int i = 0; i < json.size(); i++) {
            JsonObject vo = json.get(i).getAsJsonObject();
            if (vo.has("w")) {
                CtxLevel.LevelType type;
                switch (vo.get("t").getAsInt()) {
                case 1:
                    type = CtxLevel.LevelType.Member;
                    break;
                case 2:
                    type = CtxLevel.LevelType.Group;
                    break;
                default:
                    type = CtxLevel.LevelType.Standalone;
                    break;
                }//from ww w.ja  v  a 2  s. c  o  m

                depthMap.put(vo.get("p").getAsString(), new LevelCtx(vo.get("n").getAsString(), type));
            }
        }
    }

    return depthMap;
}

From source file:com.continuuity.loom.codec.json.current.ResourceCollectionCodec.java

License:Apache License

@Override
public JsonElement serialize(ResourceCollection src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject out = new JsonObject();
    out.add("automatortypes", new JsonObject());
    out.add("providertypes", new JsonObject());

    /*/*from   www.j  a  v  a2 s.c  om*/
     * Transform it into something like:
     *
     * "resources": {
     *   "automatortypes": {
     *     "chef-solo": {
     *       "cookbooks": {
     *         "format": "archive|file",
     *         "active": [
     *           {
     *             "name":"reactor",
     *             "version":9
     *           }
     *         ]
     *       }
     *     },
     *     ...
     *   },
     * }
     */
    for (ImmutablePair<ResourceType, ResourceTypeFormat> key : src.getResources().keySet()) {
        ResourceType resourceType = key.getFirst();
        ResourceTypeFormat format = key.getSecond();
        String pluginTypeStr = pluginTypeToStr(resourceType.getPluginType());
        String pluginName = resourceType.getPluginName();
        String resourceTypeStr = resourceType.getTypeName();
        // ex: json object for automatortypes
        JsonObject pluginTypeObj = out.getAsJsonObject(pluginTypeStr);
        if (!pluginTypeObj.has(pluginName)) {
            pluginTypeObj.add(pluginName, new JsonObject());
        }
        // ex: json object for chef-solo
        JsonObject pluginObj = pluginTypeObj.getAsJsonObject(pluginName);
        if (!pluginObj.has(resourceTypeStr)) {
            pluginObj.add(resourceTypeStr, new JsonObject());
        }
        // ex: json object for cookbooks
        JsonObject resourceListObj = pluginObj.getAsJsonObject(resourceTypeStr);
        // write the format
        resourceListObj.add("format", context.serialize(format));
        // write the list of active resources
        JsonArray activeList = new JsonArray();
        for (ResourceMeta meta : src.getResources().get(key)) {
            JsonObject metaObj = new JsonObject();
            metaObj.addProperty("name", meta.getName());
            metaObj.addProperty("version", meta.getVersion());
            activeList.add(metaObj);
        }
        resourceListObj.add("active", activeList);
    }

    return out;
}

From source file:com.continuuity.loom.codec.json.upgrade.ProviderUpgradeCodec.java

License:Apache License

private Map<String, String> deserializeProvisionerFields(JsonObject jsonObj,
        JsonDeserializationContext context) {
    if (!jsonObj.has("provisioner")) {
        return Maps.newHashMap();
    }/*from   ww w .  jav  a  2 s  . c o m*/

    JsonObject fields = jsonObj.get("provisioner").getAsJsonObject();
    // if its the old type
    if (fields.has("auth")) {
        JsonElement authElement = fields.get("auth");
        if (authElement.isJsonObject()) {
            fields = authElement.getAsJsonObject();
        }
    }
    return context.deserialize(fields, new TypeToken<Map<String, String>>() {
    }.getType());
}

From source file:com.continuuity.loom.codec.json.upgrade.ServiceActionUpgradeCodec.java

License:Apache License

@Override
public ServiceAction deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String actionType = context.deserialize(jsonObj.get("type"), String.class);
    Map<String, String> fields = context.deserialize(jsonObj.get("fields"),
            new TypeToken<Map<String, String>>() {
            }.getType());/*  w  ww . j  ava 2s .  co  m*/
    // For backwards compatibility.
    if (jsonObj.has("script")) {
        if (fields == null) {
            fields = Maps.newHashMap();
        }
        fields.put("script", jsonObj.get("script").getAsString());
    }
    if (jsonObj.has("data")) {
        if (fields == null) {
            fields = Maps.newHashMap();
        }
        fields.put("data", jsonObj.get("data").getAsString());
    }

    return new ServiceAction(actionType, fields);
}

From source file:com.continuuity.loom.http.handler.LoomClusterHandler.java

License:Apache License

/**
 * Changes a cluster parameter like lease time.
 *
 * @param request Request to change cluster parameter.
 * @param responder Responder to send the response.
 * @param clusterId Id of the cluster to change.
 *///from  w ww .j a v  a 2s  .c o  m
@POST
@Path("/{cluster-id}")
public void changeClusterParameter(HttpRequest request, HttpResponder responder,
        @PathParam("cluster-id") String clusterId) {
    Account account = getAndAuthenticateAccount(request, responder);
    if (account == null) {
        return;
    }

    try {
        JsonObject jsonObject = gson.fromJson(request.getContent().toString(Charsets.UTF_8), JsonObject.class);
        if (jsonObject == null || !jsonObject.has("expireTime")) {
            responder.sendError(HttpResponseStatus.BAD_REQUEST, "expire time not specified");
            return;
        }

        long expireTime = jsonObject.get("expireTime").getAsLong();

        clusterService.changeExpireTime(clusterId, account, expireTime);
        responder.sendStatus(HttpResponseStatus.OK);
    } catch (IllegalArgumentException e) {
        responder.sendError(HttpResponseStatus.BAD_REQUEST, e.getMessage());
    } catch (JsonSyntaxException e) {
        LOG.error("Exception while parsing JSON.", e);
        responder.sendError(HttpResponseStatus.BAD_REQUEST, "Invalid JSON");
    } catch (IllegalAccessException e) {
        responder.sendError(HttpResponseStatus.FORBIDDEN,
                "User does not have permission to change cluster parameter.");
    } catch (IOException e) {
        responder.sendError(HttpResponseStatus.INTERNAL_SERVER_ERROR, "Exception changing cluster parameter.");
    }
}

From source file:com.continuuity.loom.http.handler.LoomRPCHandler.java

License:Apache License

/**
 * Get properties of nodes from a specific cluster visible to the user. POST body is a JSON object that
 * must contain "clusterId", and may contain "properties" and "services". The "properties" key maps to an array
 * of node properties like "ipaddress" and "hostname" to return in the response. The "services" key maps to an
 * array of service names, indicating that all nodes returned by have all services given in the array. The response
 * is a JSON object with node ids as keys and JSON objects as values, where the value contains the properties passed
 * in, or all properties if none were passed in.
 *
 * @param request Request for node properties in a cluster.
 * @param responder Responder for sending the response.
 * @throws Exception/*from w ww. j  ava 2  s  . com*/
 */
@POST
@Path("/getNodeProperties")
public void getNodeProperties(HttpRequest request, HttpResponder responder) throws Exception {
    Account account = getAndAuthenticateAccount(request, responder);
    if (account == null) {
        return;
    }
    Reader reader = new InputStreamReader(new ChannelBufferInputStream(request.getContent()), Charsets.UTF_8);
    NodePropertiesRequest nodeRequest;
    try {
        nodeRequest = GSON.fromJson(reader, NodePropertiesRequest.class);
    } catch (IllegalArgumentException e) {
        responder.sendError(HttpResponseStatus.BAD_REQUEST, e.getMessage());
        return;
    } catch (Exception e) {
        responder.sendError(HttpResponseStatus.BAD_REQUEST,
                "Invalid request body. Must be a valid JSON Object.");
        return;
    }

    Map<String, JsonObject> output = Maps.newHashMap();
    Set<Node> clusterNodes = clusterStoreService.getView(account).getClusterNodes(nodeRequest.getClusterId());
    Set<String> properties = nodeRequest.getProperties();
    Set<String> requiredServices = nodeRequest.getServices();

    for (Node node : clusterNodes) {
        Set<String> nodeServices = Sets.newHashSet();
        for (Service service : node.getServices()) {
            nodeServices.add(service.getName());
        }

        // if the node has all services needed
        if (nodeServices.containsAll(requiredServices)) {
            JsonObject outputProperties;
            JsonObject nodeProperties = GSON.toJsonTree(node.getProperties()).getAsJsonObject();
            // if the request contains a list of properties, just include those properties
            if (properties.size() > 0) {
                outputProperties = new JsonObject();
                // add all requested node properties
                for (String property : properties) {
                    if (nodeProperties.has(property)) {
                        outputProperties.add(property, nodeProperties.get(property));
                    }
                }
            } else {
                // request did not contain a list of properties, include them all
                outputProperties = nodeProperties;
            }
            output.put(node.getId(), outputProperties);
        }
    }

    responder.sendJson(HttpResponseStatus.OK, output);
}

From source file:com.couchbase.cbadmin.client.CouchbaseAdminImpl.java

License:Open Source License

private JsonObject mergeViews(JsonObject design, JsonObject definition) {
    JsonObject views = definition.get("views").getAsJsonObject();
    JsonObject currentViews = design != null ? design.get("views").getAsJsonObject() : new JsonObject();
    for (Entry<String, JsonElement> entry : currentViews.entrySet()) {
        if (views.has(entry.getKey())) {
            views.remove(entry.getKey());
        }/*from   w ww. ja  v  a 2 s  .  c  o  m*/

        views.add(entry.getKey(), entry.getValue());
    }
    return definition;
}