Example usage for com.google.gson JsonObject remove

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

Introduction

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

Prototype

public JsonElement remove(String property) 

Source Link

Document

Removes the property from this JsonObject .

Usage

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog222.java

License:Apache License

protected void updateAlerts() {
    LOG.info("Updating alert definitions.");
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    AlertDefinitionDAO alertDefinitionDAO = injector.getInstance(AlertDefinitionDAO.class);
    Clusters clusters = ambariManagementController.getClusters();

    Map<String, Cluster> clusterMap = getCheckedClusterMap(clusters);
    for (final Cluster cluster : clusterMap.values()) {
        long clusterID = cluster.getClusterId();

        final AlertDefinitionEntity regionserverHealthSummaryDefinitionEntity = alertDefinitionDAO
                .findByName(clusterID, "regionservers_health_summary");

        final AlertDefinitionEntity atsWebAlert = alertDefinitionDAO.findByName(clusterID,
                "yarn_app_timeline_server_webui");

        if (regionserverHealthSummaryDefinitionEntity != null) {
            alertDefinitionDAO.remove(regionserverHealthSummaryDefinitionEntity);
        }//w w  w .  j  a va 2s.c o  m

        if (atsWebAlert != null) {
            String source = atsWebAlert.getSource();
            JsonObject sourceJson = new JsonParser().parse(source).getAsJsonObject();

            JsonObject uriJson = sourceJson.get("uri").getAsJsonObject();
            uriJson.remove("http");
            uriJson.remove("https");
            uriJson.addProperty("http", "{{yarn-site/yarn.timeline-service.webapp.address}}/ws/v1/timeline");
            uriJson.addProperty("https",
                    "{{yarn-site/yarn.timeline-service.webapp.https.address}}/ws/v1/timeline");

            atsWebAlert.setSource(sourceJson.toString());
            alertDefinitionDAO.merge(atsWebAlert);
        }

        //update Atlas alert
        final AlertDefinitionEntity atlasMetadataServerWebUI = alertDefinitionDAO.findByName(clusterID,
                "metadata_server_webui");
        if (atlasMetadataServerWebUI != null) {
            String source = atlasMetadataServerWebUI.getSource();
            JsonObject sourceJson = new JsonParser().parse(source).getAsJsonObject();

            JsonObject uriJson = sourceJson.get("uri").getAsJsonObject();
            uriJson.remove("http");
            uriJson.remove("https");
            uriJson.addProperty("http", "{{application-properties/atlas.server.http.port}}");
            uriJson.addProperty("https", "{{application-properties/atlas.server.https.port}}");

            atlasMetadataServerWebUI.setSource(sourceJson.toString());
            alertDefinitionDAO.merge(atlasMetadataServerWebUI);
        }

    }

}

From source file:org.ballerinalang.composer.service.workspace.rest.datamodel.BLangFragmentParser.java

License:Open Source License

protected static JsonObject getJsonNodeForFragment(JsonObject jsonModel, BLangSourceFragment fragment) {
    JsonObject fragmentNode = null;
    JsonArray jsonArray = jsonModel.getAsJsonArray(BLangJSONModelConstants.ROOT);
    JsonObject functionObj = jsonArray.get(1).getAsJsonObject(); // 0 is package def
    switch (fragment.getExpectedNodeType()) {
    case BLangFragmentParserConstants.EXPRESSION:
        // 0 & 1 are function args and return types, 2 is the var def stmt
        JsonObject varDef = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(2)
                .getAsJsonObject();/*from w w w . ja v a 2s.c  o m*/
        // 0th child is the var ref expression of var def stmt
        fragmentNode = varDef.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(1).getAsJsonObject();
        break;
    case BLangFragmentParserConstants.VARIABLE_REFERENCE_LIST:
        // 0 & 1 are function args and return types, 2 is the assignment statement
        JsonObject assignmentStmt = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(2)
                .getAsJsonObject();
        // 0th child is the var ref list expression of assignment stmt
        fragmentNode = assignmentStmt.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject();
        break;
    case BLangFragmentParserConstants.STATEMENT:
        // 0 & 1 are function args and return types, 2 is the statement came from source fragment
        fragmentNode = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(2).getAsJsonObject();
        break;
    case BLangFragmentParserConstants.JOIN_CONDITION:
        fragmentNode = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(2).getAsJsonObject()
                .getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject();
        fragmentNode.remove(BLangJSONModelConstants.CHILDREN);
        fragmentNode.remove(BLangJSONModelConstants.JOIN_PARAMETER);
        break;
    case BLangFragmentParserConstants.ARGUMENT_PARAMETER:
        fragmentNode = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject()
                .getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject();
        break;
    case BLangFragmentParserConstants.RETURN_PARAMETER:
        fragmentNode = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(1).getAsJsonObject()
                .getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject();
        break;
    case BLangFragmentParserConstants.TRANSACTION_FAILED:
        fragmentNode = functionObj.getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(2).getAsJsonObject()
                .getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(1).getAsJsonObject()
                .getAsJsonArray(BLangJSONModelConstants.CHILDREN).get(0).getAsJsonObject();
        break;
    default:
        fragmentNode = new JsonObject();
        fragmentNode.addProperty(ERROR, "cannot find node for given fragment");
    }
    return fragmentNode;
}

From source file:org.ballerinalang.langserver.formatting.FormattingSourceGen.java

License:Open Source License

private static void modifyNode(JsonObject node, String parentKind) {
    String kind = node.get("kind").getAsString();

    if ("CompilationUnit".equals(kind)) {
        if (node.has("ws")) {
            node.getAsJsonArray("ws").get(0).getAsJsonObject().addProperty("text", "");
        }/*from   w  ww .j  a v  a 2  s .co  m*/
    }

    if ("If".equals(kind)) {
        if (node.getAsJsonObject("elseStatement") != null) {
            node.addProperty("ladderParent", true);
        }

        if (node.has("ws") && node.getAsJsonArray("ws").size() > 1
                && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("else")
                && node.getAsJsonArray("ws").get(1).getAsJsonObject().get("text").getAsString().equals("if")) {
            node.addProperty("isElseIfBlock", true);
        }
    }

    if ("Transaction".equals(kind) && node.has("condition") && node.getAsJsonObject("condition").has("value")) {
        JsonObject retry = null;
        if (node.has("failedBody") && node.getAsJsonObject("failedBody").has("statements")) {
            for (JsonElement statement : node.getAsJsonObject("failedBody").get("statements")
                    .getAsJsonArray()) {
                if (statement.isJsonObject() && statement.getAsJsonObject().has("kind")
                        && statement.getAsJsonObject().get("kind").getAsString().equals("retry")) {
                    retry = statement.getAsJsonObject();
                }
            }
        }

        if (node.has("committedBody") && node.getAsJsonObject("committedBody").has("statements")) {
            for (JsonElement statement : node.getAsJsonObject("committedBody").get("statements")
                    .getAsJsonArray()) {
                if (statement.isJsonObject() && statement.getAsJsonObject().has("kind")
                        && statement.getAsJsonObject().get("kind").getAsString().equals("retry")) {
                    retry = statement.getAsJsonObject();
                }
            }
        }

        if (node.has("transactionBody") && node.getAsJsonObject("transactionBody").has("statements")) {
            for (JsonElement statement : node.getAsJsonObject("transactionBody").get("statements")
                    .getAsJsonArray()) {
                if (statement.isJsonObject() && statement.getAsJsonObject().has("kind")
                        && statement.getAsJsonObject().get("kind").getAsString().equals("retry")) {
                    retry = statement.getAsJsonObject();
                }
            }
        }

        if (retry != null) {
            retry.addProperty("count", node.getAsJsonObject("condition").get("value").getAsString());
        }
    }

    if (("XmlCommentLiteral".equals(kind) || "XmlElementLiteral".equals(kind) || "XmlTextLiteral".equals(kind)
            || "XmlPiLiteral".equals(kind)) && node.has("ws") && node.getAsJsonArray("ws").get(0) != null
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().contains("xml")
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().contains("`")) {
        node.addProperty("root", true);
        node.addProperty("startLiteral",
                node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
    }

    if ("XmlElementLiteral".equals(parentKind) || "XmlTextLiteral".equals(parentKind)
            || "XmlPiLiteral".equals(parentKind)) {
        node.addProperty("inTemplateLiteral", true);
    }

    if ("Annotation".equals(kind) && node.has("attachmentPoints")
            && node.getAsJsonArray("attachmentPoints").size() <= 0) {
        node.addProperty("noAttachmentPoints", true);
    }

    if ("Identifier".equals(kind)) {
        if (node.has("literal") && node.get("literal").getAsBoolean()) {
            node.addProperty("valueWithBar", "^\"" + node.get("value").getAsString() + "\"");
        } else {
            node.addProperty("valueWithBar", node.get("value").getAsString());
        }
    }

    if ("Import".equals(kind)) {
        if (node.getAsJsonObject("alias") != null && node.getAsJsonObject("alias").get("value") != null
                && node.getAsJsonArray("packageName") != null && node.getAsJsonArray("packageName").size() != 0
                && !node.getAsJsonObject("alias").get("value").getAsString()
                        .equals(node.getAsJsonArray("packageName")
                                .get(node.getAsJsonArray("packageName").size() - 1).getAsJsonObject()
                                .get("value").getAsString())) {
            node.addProperty("userDefinedAlias", true);
        }

        if ((node.getAsJsonArray("packageName") != null && node.getAsJsonArray("packageName").size() == 2
                && node.getAsJsonArray("packageName").get(0).getAsJsonObject().get("value").getAsString()
                        .equals("transactions")
                && node.getAsJsonArray("packageName").get(1).getAsJsonObject().get("value").getAsString()
                        .equals("coordinator"))
                || (node.getAsJsonObject("alias") != null && node.getAsJsonObject("alias").get("value") != null
                        && node.getAsJsonObject("alias").get("value").getAsString().startsWith("."))) {
            node.addProperty("isInternal", true);
        }
    }

    if ("CompilationUnit".equals(parentKind) && ("Variable".equals(kind) || "Xmlns".equals(kind))) {
        node.addProperty("global", true);
    }

    if ("VariableDef".equals(kind)) {
        // TODO: refactor variable def whitespace.
        // Temporary remove variable def ws and add it to variable whitespaces.
        if (node.has("variable") && node.has(FormattingConstants.WS)
                && node.getAsJsonObject("variable").has(FormattingConstants.WS)
                && !(node.getAsJsonObject("variable").get("kind").getAsString().equals("TupleVariable")
                        || (node.getAsJsonObject("variable").has("symbolType")
                                && node.getAsJsonObject("variable").getAsJsonArray("symbolType").size() > 0
                                && node.getAsJsonObject("variable").getAsJsonArray("symbolType").get(0)
                                        .getAsString().equals("service")))) {
            node.getAsJsonObject("variable").getAsJsonArray(FormattingConstants.WS)
                    .addAll(node.getAsJsonArray(FormattingConstants.WS));
            node.remove(FormattingConstants.WS);
        }

        if (node.getAsJsonObject("variable") != null
                && node.getAsJsonObject("variable").getAsJsonObject("typeNode") != null
                && node.getAsJsonObject("variable").getAsJsonObject("typeNode").get("kind").getAsString()
                        .equals("EndpointType")) {
            node.getAsJsonObject("variable").addProperty("endpoint", true);
            node.addProperty("endpoint", true);
        }
    }

    if ("Variable".equals(kind)) {
        if ("ObjectType".equals(parentKind)) {
            node.addProperty("inObject", true);
        }

        if (node.has("typeNode") && node.getAsJsonObject("typeNode").has("isAnonType")
                && node.getAsJsonObject("typeNode").get("isAnonType").getAsBoolean()) {
            node.addProperty("isAnonType", true);
        }

        if (node.has("initialExpression")) {
            node.getAsJsonObject("initialExpression").addProperty("isExpression", true);

            if (node.getAsJsonObject("initialExpression").has("async")
                    && node.getAsJsonObject("initialExpression").get("async").getAsBoolean()
                    && node.has("ws")) {
                JsonArray ws = node.getAsJsonArray("ws");
                for (int i = 0; i < ws.size(); i++) {
                    if (ws.get(i).getAsJsonObject().get("text").getAsString().equals("start")
                            && node.getAsJsonObject("initialExpression").has("ws")) {
                        node.getAsJsonObject("initialExpression").add("ws",
                                addDataToArray(0, node.getAsJsonArray("ws").get(i),
                                        node.getAsJsonObject("initialExpression").getAsJsonArray("ws")));
                        node.getAsJsonArray("ws").remove(i);
                    }
                }
            }
        }

        if (node.has("typeNode") && node.getAsJsonObject("typeNode").has("nullable")
                && node.getAsJsonObject("typeNode").get("nullable").getAsBoolean()
                && node.getAsJsonObject("typeNode").has("ws")) {
            JsonArray ws = node.getAsJsonObject("typeNode").get("ws").getAsJsonArray();
            for (int i = 0; i < ws.size(); i++) {
                if (ws.get(i).getAsJsonObject().get("text").getAsString().equals("?")) {
                    node.getAsJsonObject("typeNode").addProperty("nullableOperatorAvailable", true);
                    break;
                }
            }
        }

        if (node.has("typeNode") && node.getAsJsonObject("typeNode").has("ws") && !node.has("ws")) {
            node.addProperty("noVisibleName", true);
        }

        if (node.has("ws")) {
            JsonArray ws = node.getAsJsonArray("ws");
            for (int i = 0; i < ws.size(); i++) {
                if (ws.get(i).getAsJsonObject().get("text").getAsString().equals(";")) {
                    node.addProperty("endWithSemicolon", true);
                }

                if (ws.get(i).getAsJsonObject().get("text").getAsString().equals(",")) {
                    node.addProperty("endWithComma", true);
                }
            }
        }

        if (node.has("service") && node.get("service").getAsBoolean() && node.has("noVisibleName")
                && node.get("noVisibleName").getAsBoolean()) {
            node.addProperty("skip", true);
        }

        if (node.has("name") && node.getAsJsonObject("name").get("value").getAsString().startsWith("0")) {
            node.addProperty("worker", true);
        }
    }

    if ("Service".equals(kind)) {
        if (!node.has("serviceTypeStruct")) {
            node.addProperty("isServiceTypeUnavailable", true);
        }

        if (node.has("resources")) {
            if (node.has("typeDefinition")) {
                JsonObject typeDefinition = node.getAsJsonObject("typeDefinition");
                JsonObject typeNode = typeDefinition.getAsJsonObject("typeNode");
                if (typeNode.has("symbolType")
                        && typeNode.getAsJsonArray("symbolType").get(0).getAsString().equals("service")) {
                    JsonArray functions = typeNode.getAsJsonArray("functions");
                    for (JsonElement func : functions) {
                        JsonObject function = func.getAsJsonObject();
                        if (function.has("resource") && function.get("resource").getAsBoolean()) {
                            function.addProperty("skip", true);
                        }
                    }
                }
            }
        }

        if (!node.has("anonymousEndpointBind") && node.has("boundEndpoints")
                && node.getAsJsonArray("boundEndpoints").size() <= 0) {
            boolean bindAvailable = false;
            for (JsonElement ws : node.getAsJsonArray("ws")) {
                if (ws.getAsJsonObject().get("text").getAsString().equals("bind")) {
                    bindAvailable = true;
                    break;
                }
            }

            if (!bindAvailable) {
                node.addProperty("bindNotAvailable", true);
            }
        }

        if (node.has("userDefinedTypeNode")
                && node.getAsJsonObject("userDefinedTypeNode").has(FormattingConstants.WS)) {
            node.getAsJsonObject("userDefinedTypeNode").remove(FormattingConstants.WS);
        }
    }

    if ("Resource".equals(kind) && node.has("parameters") && node.getAsJsonArray("parameters").size() > 0
            && node.getAsJsonArray("parameters").get(0).getAsJsonObject().has("ws")) {
        for (JsonElement ws : node.getAsJsonArray("parameters").get(0).getAsJsonObject().getAsJsonArray("ws")) {
            if (ws.getAsJsonObject().get("text").getAsString().equals("endpoint")) {
                JsonObject endpointParam = node.getAsJsonArray("parameters").get(0).getAsJsonObject();
                String valueWithBar = endpointParam.get("name").getAsJsonObject().has("valueWithBar")
                        ? endpointParam.get("name").getAsJsonObject().get("valueWithBar").getAsString()
                        : endpointParam.get("name").getAsJsonObject().get("value").getAsString();

                endpointParam.addProperty("serviceEndpoint", true);
                endpointParam.get("name").getAsJsonObject().addProperty("value", endpointParam.get("name")
                        .getAsJsonObject().get("value").getAsString().replace("$", ""));
                endpointParam.get("name").getAsJsonObject().addProperty("valueWithBar",
                        valueWithBar.replace("$", ""));
                break;
            }
        }
    }

    if ("ForkJoin".equals(kind)) {
        if (node.getAsJsonObject("joinBody") != null) {
            node.getAsJsonObject("joinBody").add("position",
                    node.getAsJsonObject("joinResultVar").getAsJsonObject("position"));
        }

        if (node.getAsJsonObject("timeoutBody") != null) {
            node.getAsJsonObject("timeoutBody").add("position",
                    node.getAsJsonObject("timeOutExpression").getAsJsonObject("position"));
        }
    }

    if ("Match".equals(kind)) {
        if (node.has("structuredPatternClauses")) {
            JsonArray structuredPatternClauses = node.getAsJsonArray("structuredPatternClauses");
            for (JsonElement pattern : structuredPatternClauses) {
                pattern.getAsJsonObject().addProperty("skip", true);
            }
        }

        if (node.has("staticPatternClauses")) {
            JsonArray staticPatternClauses = node.getAsJsonArray("staticPatternClauses");
            for (JsonElement pattern : staticPatternClauses) {
                pattern.getAsJsonObject().addProperty("skip", true);
            }
        }
    }

    // Check if sorrounded by curlies
    if (("MatchStructuredPatternClause".equals(kind) || "MatchStaticPatternClause".equals(kind)
            || "MatchTypedPatternClause".equals(kind)) && node.has("ws")) {

        for (JsonElement wsItem : node.getAsJsonArray(FormattingConstants.WS)) {
            JsonObject currentWS = wsItem.getAsJsonObject();
            String text = currentWS.get(FormattingConstants.TEXT).getAsString();
            if (text.equals("{")) {
                node.addProperty("withCurlies", true);
                break;
            }
        }
    }

    // Check if sorrounded by parantheses
    if ("ValueType".equals(kind)) {
        if (node.has("ws") && node.getAsJsonArray("ws").size() > 2) {
            node.addProperty("withParantheses", true);
        }

        if (node.has("typeKind") && node.get("typeKind").getAsString().equals("nil") && node.has("ws")) {
            node.addProperty("emptyParantheses", true);
        }

        if (node.has("nullable") && node.get("nullable").getAsBoolean() && node.has("ws")) {
            for (int i = 0; i < node.get("ws").getAsJsonArray().size(); i++) {
                if (node.get("ws").getAsJsonArray().get(i).getAsJsonObject().get("text").getAsString()
                        .equals("?")) {
                    node.addProperty("nullableOperatorAvailable", true);
                    break;
                }
            }
        }
    }

    if ("UnionTypeNode".equals(kind) && node.has("ws")) {
        if (node.getAsJsonArray("ws").size() > 2) {
            for (JsonElement ws : node.getAsJsonArray("ws")) {
                if (ws.getAsJsonObject().get("text").getAsString().equals("(")) {
                    node.addProperty("withParantheses", true);
                    break;
                }
            }
        }

        JsonArray memberTypeNodes = node.get("memberTypeNodes").getAsJsonArray();
        for (int i = 0; i < memberTypeNodes.size(); i++) {
            if (memberTypeNodes.get(i).getAsJsonObject().has("nullable")
                    && memberTypeNodes.get(i).getAsJsonObject().get("nullable").getAsBoolean()) {
                for (JsonElement ws : node.getAsJsonArray("ws")) {
                    if (ws.getAsJsonObject().get("text").getAsString().equals("?")) {
                        memberTypeNodes.get(i).getAsJsonObject().addProperty("nullableOperatorAvailable", true);
                        break;
                    }
                }
            }
        }
    }

    if ("Function".equals(kind)) {
        if (node.has("returnTypeNode") && node.getAsJsonObject("returnTypeNode").has("ws")
                && node.getAsJsonObject("returnTypeNode").getAsJsonArray("ws").size() > 0) {
            node.addProperty("hasReturns", true);
        }

        if (node.has("defaultableParameters")) {
            JsonArray defaultableParameters = node.getAsJsonArray("defaultableParameters");
            for (int i = 0; i < defaultableParameters.size(); i++) {
                defaultableParameters.get(i).getAsJsonObject().addProperty("defaultable", true);
                defaultableParameters.get(i).getAsJsonObject().addProperty("param", true);
                defaultableParameters.get(i).getAsJsonObject().getAsJsonObject("variable")
                        .addProperty("defaultable", true);
            }
        }

        if (node.has("parameters")) {
            JsonArray parameters = node.getAsJsonArray("parameters");
            for (int i = 0; i < parameters.size(); i++) {
                parameters.get(i).getAsJsonObject().addProperty("param", true);
            }
        }

        if (!(node.has("resource") && node.get("resource").getAsBoolean())) {
            // Sort and add all the parameters.
            JsonArray allParamsTemp = node.getAsJsonArray("parameters");
            allParamsTemp.addAll(node.getAsJsonArray("defaultableParameters"));
            List<JsonElement> allParamElements = new ArrayList<>();
            allParamsTemp.forEach(allParamElements::add);

            allParamElements.sort((a, b) -> {
                int comparator = 0;
                comparator = (((a.getAsJsonObject().getAsJsonObject("position").get("endColumn").getAsInt() > b
                        .getAsJsonObject().getAsJsonObject("position").get("startColumn").getAsInt())
                        && (a.getAsJsonObject().getAsJsonObject("position").get("endLine").getAsInt() == b
                                .getAsJsonObject().getAsJsonObject("position").get("endLine").getAsInt()))
                        || (a.getAsJsonObject().getAsJsonObject("position").get("endLine").getAsInt() > b
                                .getAsJsonObject().getAsJsonObject("position").get("endLine").getAsInt())) ? 1
                                        : -1;
                return comparator;
            });

            JsonArray allParams = new JsonArray();
            allParamElements.forEach(allParams::add);
            node.add("allParams", allParams);
        }

        if (node.has("receiver") && !node.getAsJsonObject("receiver").has("ws")) {
            if (node.getAsJsonObject("receiver").has("typeNode")
                    && node.getAsJsonObject("receiver").getAsJsonObject("typeNode").has("ws")
                    && node.getAsJsonObject("receiver").getAsJsonObject("typeNode").getAsJsonArray("ws")
                            .size() > 0) {
                for (JsonElement ws : node.get("ws").getAsJsonArray()) {
                    if (ws.getAsJsonObject().get("text").getAsString().equals("::")) {
                        node.addProperty("objectOuterFunction", true);
                        if (node.getAsJsonObject("receiver").getAsJsonObject("typeNode").getAsJsonArray("ws")
                                .get(0).getAsJsonObject().get("text").getAsString().equals("function")) {
                            node.getAsJsonObject("receiver").getAsJsonObject("typeNode").getAsJsonArray("ws")
                                    .remove(0);
                        }
                        node.add("objectOuterFunctionTypeName", node.getAsJsonObject("receiver")
                                .getAsJsonObject("typeNode").getAsJsonObject("typeName"));
                        break;
                    }
                }
            } else {
                node.addProperty("noVisibleReceiver", true);
            }
        }

        if (node.has("restParameters")
                && (node.has("allParams") && node.getAsJsonArray("allParams").size() > 0)) {
            node.addProperty("hasRestParams", true);
        }

        if (node.has("restParameters")) {
            node.getAsJsonObject("restParameters").addProperty("param", true);
            if (node.getAsJsonObject("restParameters").has("typeNode")) {
                node.getAsJsonObject("restParameters").getAsJsonObject("typeNode").addProperty("isRestParam",
                        true);
            }
        }
    }

    if ("TypeDefinition".equals(kind) && node.has("typeNode")) {
        if (!node.has("ws")) {
            node.addProperty("notVisible", true);
        }

        if (node.has("name")
                && node.getAsJsonObject("name").get("value").getAsString().startsWith("$anonType$")) {
            anonTypes.put(node.getAsJsonObject("name").get("value").getAsString(),
                    node.getAsJsonObject("typeNode"));
        }

        if (node.getAsJsonObject("typeNode").get("kind").getAsString().equals("ObjectType")) {
            node.addProperty("isObjectType", true);
            if (node.has("ws")) {
                JsonArray typeDefWS = node.getAsJsonArray("ws");
                for (int i = 0; i < typeDefWS.size(); i++) {
                    if (typeDefWS.get(i).getAsJsonObject().get("text").getAsString().equals("abstract")) {
                        node.addProperty("isAbstractKeywordAvailable", true);
                    }
                }
            }
        }

        if (node.getAsJsonObject("typeNode").get("kind").getAsString().equals("RecordType")) {
            node.addProperty("isRecordType", true);
            if (node.has("ws")) {
                for (int i = 0; i < node.getAsJsonArray("ws").size(); i++) {
                    if (node.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString()
                            .equals("record")) {
                        node.addProperty("isRecordKeywordAvailable", true);
                    }
                }
            }
        }

        if (node.has("service") && node.get("service").getAsBoolean() && parentKind.equals("CompilationUnit")) {
            node.addProperty("skip", true);
        }
    }

    if ("ObjectType".equals(kind) && node.has("initFunction")) {
        if (!node.getAsJsonObject("initFunction").has("ws")) {
            node.getAsJsonObject("initFunction").addProperty("defaultConstructor", true);
        } else {
            node.getAsJsonObject("initFunction").addProperty("isConstructor", true);
        }
    }

    if ("RecordType".equals(kind) && node.has("restFieldType")) {
        node.addProperty("isRestFieldAvailable", true);
    }

    if ("TypeInitExpr".equals(kind)) {
        if (node.getAsJsonArray("expressions").size() <= 0) {
            node.addProperty("noExpressionAvailable", true);
        }

        if (node.has("ws")) {
            for (int i = 0; i < node.getAsJsonArray("ws").size(); i++) {
                if (node.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString().equals("(")) {
                    node.addProperty("hasParantheses", true);
                    break;
                }
            }
        }

        if (!node.has("type")) {
            node.addProperty("noTypeAttached", true);
        } else {
            node.add("typeName", node.getAsJsonObject("type").get("typeName"));
        }
    }

    if ("Return".equals(kind) && node.has("expression")) {
        if (node.getAsJsonObject("expression").get("kind").getAsString().equals("Literal")) {
            if (node.getAsJsonObject("expression").get("value").getAsString().equals("()")) {
                node.addProperty("noExpressionAvailable", true);
            }

            if (node.getAsJsonObject("expression").get("value").getAsString().equals("null")) {
                node.getAsJsonObject("expression").addProperty("emptyParantheses", true);
            }
        }
        node.getAsJsonObject("expression").addProperty("isExpression", "true");
    }

    if ("Documentation".equals(kind)) {
        if (node.has("ws") && node.getAsJsonArray("ws").size() > 1) {
            node.addProperty("startDoc",
                    node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
        }

        for (int j = 0; j < node.getAsJsonArray("attributes").size(); j++) {
            JsonObject attribute = node.getAsJsonArray("attributes").get(j).getAsJsonObject();
            if (attribute.has("ws")) {
                for (int i = 0; i < attribute.getAsJsonArray("ws").size(); i++) {
                    String text = attribute.getAsJsonArray("ws").get(i).getAsJsonObject().get("text")
                            .getAsString();
                    if (text.contains("{{") && !attribute.has("paramType")) {
                        int lastIndex = text.lastIndexOf("{{");
                        String paramType = text.substring(0, lastIndex);
                        String startCurl = text.substring(lastIndex, text.length());
                        attribute.getAsJsonArray("ws").get(i).getAsJsonObject().addProperty("text", paramType);
                        attribute.addProperty("paramType", paramType);

                        JsonObject ws = new JsonObject();
                        ws.addProperty("text", startCurl);
                        ws.addProperty("ws", "");
                        ws.addProperty("static", false);
                        attribute.add("ws", addDataToArray(++i, ws, attribute.getAsJsonArray("ws")));
                    }
                }
            }
        }
    }

    // Tag rest variable nodes
    if (("Function".equals(kind) || "Resource".equals(kind)) && node.has("restParameters")) {
        node.getAsJsonObject("restParameters").addProperty("rest", true);
    }

    if ("PostIncrement".equals(kind)) {
        node.addProperty("operator",
                (node.get("operatorKind").getAsString() + node.get("operatorKind").getAsString()));
    }

    if ("SelectExpression".equals(kind) && node.has("identifier")) {
        node.addProperty("identifierAvailable", true);
    }

    if ("StreamAction".equals(kind) && node.has("invokableBody")
            && node.getAsJsonObject("invokableBody").has("functionNode")) {
        node.getAsJsonObject("invokableBody").getAsJsonObject("functionNode").addProperty("isStreamAction",
                true);
    }

    if ("StreamingInput".equals(kind) && node.has("alias")) {
        node.addProperty("aliasAvailable", true);
    }

    if ("IntRangeExpr".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0) {
        if (node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("[")) {
            node.addProperty("isWrappedWithBracket", true);
        } else if (node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("(")) {
            node.addProperty("isWrappedWithParenthesis", true);
        }
    }

    if ("FunctionType".equals(kind)) {
        if (node.has("returnTypeNode") && node.getAsJsonObject("returnTypeNode").has("ws")) {
            node.addProperty("hasReturn", true);
        }

        if (node.has("ws") && node.getAsJsonArray("ws").size() > 0
                && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("(")) {
            node.addProperty("withParantheses", true);
        }
    }

    if ("Literal".equals(kind) && !"StringTemplateLiteral".equals(parentKind)) {
        if (node.has("ws") && node.getAsJsonArray("ws").size() == 1
                && node.getAsJsonArray("ws").get(0).getAsJsonObject().has("text")) {
            node.addProperty("value",
                    node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
        }

        if ((node.get("value").getAsString().equals("nil") || node.get("value").getAsString().equals("null"))
                && node.has("ws") && node.getAsJsonArray("ws").size() < 3
                && node.getAsJsonArray("ws").get(0) != null
                && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("(")) {
            node.addProperty("emptyParantheses", true);
        }
    }

    if ("Foreach".equals(kind) && node.has("ws")) {
        for (JsonElement ws : node.getAsJsonArray("ws")) {
            if (ws.getAsJsonObject().get("text").getAsString().equals("(")) {
                node.addProperty("withParantheses", true);
                break;
            }
        }
    }

    if ("Endpoint".equals(kind) && node.has("ws")) {
        for (JsonElement ws : node.getAsJsonArray("ws")) {
            if (ws.getAsJsonObject().get("text").getAsString().equals("=")) {
                node.addProperty("isConfigAssignment", true);
                break;
            }
        }
    }

    if ("UserDefinedType".equals(kind)) {
        if (node.has("ws") && node.has("nullable") && node.get("nullable").getAsBoolean()) {
            for (JsonElement ws : node.getAsJsonArray("ws")) {
                if (ws.getAsJsonObject().get("text").getAsString().equals("?")) {
                    node.addProperty("nullableOperatorAvailable", true);
                    break;
                }
            }
        }

        if (node.has("typeName") && node.getAsJsonObject("typeName").has("value")
                && anonTypes.containsKey(node.getAsJsonObject("typeName").get("value").getAsString())) {
            node.addProperty("isAnonType", true);
            node.add("anonType", anonTypes.get(node.getAsJsonObject("typeName").get("value").getAsString()));
            anonTypes.remove(node.getAsJsonObject("typeName").get("value").getAsString());
        }
    }

    if ("ArrayType".equals(kind) && node.has("dimensions") && node.get("dimensions").getAsInt() > 0
            && node.has("ws")) {
        StringBuilder dimensionAsString = new StringBuilder();
        JsonObject startingBracket = null;
        JsonObject endingBracket;
        StringBuilder content = new StringBuilder();
        JsonArray ws = node.getAsJsonArray("ws");

        for (int j = 0; j < ws.size(); j++) {
            if (ws.get(j).getAsJsonObject().get("text").getAsString().equals("[")) {
                startingBracket = ws.get(j).getAsJsonObject();
            } else if (ws.get(j).getAsJsonObject().get("text").getAsString().equals("]")) {
                endingBracket = ws.get(j).getAsJsonObject();

                dimensionAsString.append(startingBracket.get("text").getAsString()).append(content.toString())
                        .append(endingBracket.get("ws").getAsString())
                        .append(endingBracket.get("text").getAsString());

                startingBracket = null;
                content = new StringBuilder();
            } else if (startingBracket != null) {
                content.append(ws.get(j).getAsJsonObject().get("ws").getAsString())
                        .append(ws.get(j).getAsJsonObject().get("text").getAsString());
            }
        }

        node.addProperty("dimensionAsString", dimensionAsString.toString());
    }

    if ("Block".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("else")) {
        node.addProperty("isElseBlock", true);
    }

    if ("FieldBasedAccessExpr".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("!")) {
        node.addProperty("errorLifting", true);
    }

    if ("StringTemplateLiteral".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().contains("string")
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().contains("`")) {
        node.addProperty("startTemplate",
                node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
        literalWSAssignForTemplates(1, 2, node.getAsJsonArray("expressions"), node.getAsJsonArray("ws"), 2);
    }

    if ("ArrowExpr".equals(kind)) {
        if (node.has("ws") && node.getAsJsonArray("ws").size() > 0
                && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("(")) {
            node.addProperty("hasParantheses", true);
        }

        if (node.has("parameters")) {
            JsonArray parameters = node.getAsJsonArray("parameters");
            for (int i = 0; i < parameters.size(); i++) {
                JsonObject parameter = parameters.get(i).getAsJsonObject();
                parameter.addProperty("arrowExprParam", true);
            }
        }
    }

    if ("PatternStreamingInput".equals(kind) && node.has("ws")
            && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("(")) {
        node.addProperty("enclosedInParenthesis", true);
    }

    if ("SelectClause".equals(kind) && !node.has("ws")) {
        node.addProperty("notVisible", true);
    }

    if ("OrderByVariable".equals(kind)) {
        if (!node.has("ws")) {
            node.addProperty("noVisibleType", true);
        } else {
            node.addProperty("typeString",
                    node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
        }
    }

    if ("Deprecated".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0) {
        node.addProperty("deprecatedStart",
                node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
    }

    if ("TypedescExpression".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0) {
        JsonArray typeDescWS = node.getAsJsonArray("ws");
        if (typeDescWS.get(0).getAsJsonObject().get("text").getAsString().equals("object")) {
            node.addProperty("isObject", true);
        } else if (typeDescWS.get(0).getAsJsonObject().get("text").getAsString().equals("record")) {
            node.addProperty("isRecord", true);
        }
    }

    if ("CompoundAssignment".equals(kind) && node.has("ws") && node.getAsJsonArray("ws").size() > 0) {
        node.addProperty("compoundOperator",
                node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString());
    }

    if ("Assignment".equals(kind) && node.has("expression")) {
        node.getAsJsonObject("expression").addProperty("isExpression", true);
    }
}

From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java

License:Open Source License

private void cleanBufferViewEntryInJSONFile(File expectedOutputFile) {
    // Replace the "bufferViews" object with a blank dictionary (collada2gltf erroneously drops 2 unused buffer views into the structure on an empty file).
    JsonElement root = readFileAsJSON(expectedOutputFile);
    // If it's valid (and it should be), clean up the mess collada2gltf leaves.
    if (root.isJsonObject()) {
        // Get the root object.
        JsonObject rootObject = root.getAsJsonObject();
        // If it has bufferViews, 
        if (rootObject.has("bufferViews")) {
            // Get the bufferViews object, with the intention of making a copy only of the ones that have a byte length greater than zero.
            JsonObject bufferViewsObject = rootObject.get("bufferViews").getAsJsonObject();
            JsonObject newBufferViewsObject = new JsonObject();
            // Entry set yields key like: bufferView_2
            for (Map.Entry<String, JsonElement> entry : bufferViewsObject.entrySet()) {
                // Get: "bufferView_22", { "buffer": "P1", ... }
                String propertyName = entry.getKey();
                JsonElement bufferViewElement = entry.getValue();
                // Cast to dictionary.
                JsonObject bufferObject = bufferViewElement.getAsJsonObject();
                // Only include buffer view objects that aren't empty (because empty ones aren't referenced by collada2gltf, but collada2gltf erroneously includes them anyway even if there's no geometry or buffers).
                if (bufferObject.get("byteLength").getAsInt() > 0) {
                    // Add the existing buffer to the replacement.
                    newBufferViewsObject.add(propertyName, bufferViewElement);
                }//  w  w  w .  j  a  v  a  2s . c om
            }
            rootObject.remove("bufferViews");
            rootObject.add("bufferViews", newBufferViewsObject);
        }
    }
    writeFileUsingJsonElement(expectedOutputFile, root);
}

From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java

License:Open Source License

private JsonElement selectivelyJoinTwoJSONElements(JsonElement baseElement, JsonElement otherElement,
        String suffix) {/*  w ww .  ja v a 2 s. c  o m*/
    JsonObject base = baseElement.getAsJsonObject();
    JsonObject other = otherElement.getAsJsonObject();
    //
    if (other.has("accessors")) {
        JsonElement accesssorsElement = getOrCreateJSONElement(base, "accessors");
        JsonObject accesssorsObject = accesssorsElement.getAsJsonObject();
        JsonObject joining = other.get("accessors").getAsJsonObject();
        // Entry set yields key like: accessor_16.
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "accessor_16", { "bufferView": "bufferView_22", ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            // Cast to dictionary object.
            JsonObject joiningObject = joiningElement.getAsJsonObject();
            // Convert: accessor_16 to accessor_16_suffix.
            String safePropertyName = String.format("%s_%s", propertyName, suffix);
            // Get the element of the bufferView, which is in form "bufferView_22".
            JsonElement bufferViewElement = joiningObject.get("bufferView");
            String bufferViewName = bufferViewElement.getAsString();
            // Create a new bufferView name: bufferView_22_suffix.
            String safeBufferViewName = String.format("%s_%s", bufferViewName, suffix);
            // Remove the existing path element.
            joiningObject.remove("bufferView");
            // Add the new one, containing the safety name: bufferView_22_suffix.
            joiningObject.addProperty("bufferView", safeBufferViewName);
            // "accesor_16_suffix": { "bufferView": "bufferView_22_suffix", ... }
            accesssorsObject.add(safePropertyName, joiningElement);
        }
    }
    if (other.has("bufferViews")) {
        JsonElement bufferViewsElement = getOrCreateJSONElement(base, "bufferViews");
        JsonObject bufferViewsObject = bufferViewsElement.getAsJsonObject();
        JsonObject joining = other.get("bufferViews").getAsJsonObject();
        // Entry set yields key like: bufferView_22
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "bufferView_22", { "buffer": "P1", ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            // Cast to dictionary.
            JsonObject joiningObject = joiningElement.getAsJsonObject();
            // Only include buffer view objects that aren't empty (because empty ones aren't referenced by collada2gltf, but collada2gltf erroneously includes them anyway during Open3DGC compression).
            if (joiningObject.get("byteLength").getAsInt() > 0) {
                // Convert: bufferView_22 to bufferView_22_suffix.
                String safePropertyName = String.format("%s_%s", propertyName, suffix);
                // Get the element of the buffer; value is a key to look up data beneath the "buffers" dictionary. 
                JsonElement bufferElement = joiningObject.get("buffer");
                // Get the buffer name: compression.
                String bufferName = bufferElement.getAsString();
                // Convert: compression to compression_suffix.
                String safeBufferName = (bufferName.equalsIgnoreCase("compression"))
                        ? String.format("%s_%s", bufferName, suffix)
                        : bufferName;
                // Remove the existing buffer element. 
                joiningObject.remove("buffer");
                // Add the new one, containing the safety name(s): bufferView_22_suffix and P1_suffix.
                joiningObject.addProperty("buffer", safeBufferName);
                // "bufferView_22_suffix": { "buffer": "P1_suffix", ... }
                bufferViewsObject.add(safePropertyName, joiningElement);
            }
        }
    }
    if (other.has("buffers")) {
        JsonElement buffersElement = getOrCreateJSONElement(base, "buffers");
        JsonObject buffersObject = buffersElement.getAsJsonObject();
        JsonObject joining = other.get("buffers").getAsJsonObject();
        // Entry set yields key like: P1 (name of converted file) or "compression" (if using Open3DGC compression).
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "P1", { "path": "P1.bin", ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            // Cast to dictionary object.
            JsonObject joiningObject = joiningElement.getAsJsonObject();
            // Only include buffer view objects that aren't empty (because empty ones aren't referenced by collada2gltf, but collada2gltf erroneously includes them anyway during Open3DGC compression).
            if (joiningObject.get("byteLength").getAsInt() > 0) {
                if (propertyName.equalsIgnoreCase("compression")) {
                    // Convert: compression to compression_suffix.
                    String safePropertyName = String.format("%s_%s", propertyName, suffix);
                    // Get the element of the path to file, which is in form "P1.bin" or "compression.bin".
                    JsonElement pathElement = joiningObject.get("path");
                    String pathName = pathElement.getAsString();
                    // Extract the file without the extension: P1.
                    String basePathName = FilenameUtils.removeExtension(pathName);
                    // Extract the extension: bin.
                    String fileExtension = FilenameUtils.getExtension(pathName);
                    // Create a new file name: P1_suffix.bin.
                    String safePathName = String.format("%s_%s.%s", basePathName, suffix, fileExtension);
                    // Remove the existing path element.
                    joiningObject.remove("path");
                    // Add the new one, containing the safety name: P1_suffix.bin.
                    joiningObject.addProperty("path", safePathName);
                    // "P1_suffix": { "path": "P1_suffix.bin", ... }
                    buffersObject.add(safePropertyName, joiningElement);
                } else
                    buffersObject.add(propertyName, joiningElement);
            }
        }
    }
    // Prepare a place to store technique rewrites to be used only in the material definitions.
    List<SimpleEntry<String, String>> techniqueReplacementTable = new ArrayList<SimpleEntry<String, String>>();
    //
    List<SimpleEntry<String, String>> programReplacementTable = new ArrayList<SimpleEntry<String, String>>();
    // Techniques must happen before materials.
    if (other.has("techniques")) {
        JsonElement techniquesElement = getOrCreateJSONElement(base, "techniques");
        JsonObject techniquesObject = techniquesElement.getAsJsonObject();
        JsonObject joining = other.get("techniques").getAsJsonObject();
        // Entry set yields key like: technique0.
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "technique0", { ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            JsonObject techniqueObject = joiningElement.getAsJsonObject();
            // Look for existing technique/program.
            String equivalentTechnique = nameOfEquivalentTechniqueInBaseObject(base, other, propertyName);
            if (equivalentTechnique != null)
                techniqueReplacementTable
                        .add(new SimpleEntry<String, String>(propertyName, equivalentTechnique));
            else {
                // If not equivalent, count number of techniques; return that count + 1 as safeTechniqueNumber.
                int safeTechniqueNumber = nextSafeTechniqueNumber(techniquesObject);
                // Then, write a replacement technique object with key: "technique%d" where %d is safeTechniqueNumber.
                String safeTechniqueName = String.format("technique%d", safeTechniqueNumber);
                techniqueReplacementTable.add(new SimpleEntry<String, String>(propertyName, safeTechniqueName));
                // Then, count number of programs; return that count + 1 as firstSafeProgramNumber.
                JsonElement baseProgramsElement = getOrCreateJSONElement(base, "programs");
                JsonObject baseProgramsObject = baseProgramsElement.getAsJsonObject();
                int firstSafeProgramNumber = nextSafeProgramNumber(baseProgramsObject);
                // Then, rewrite the object's "passes" -> pass -> "instanceProgram" -> "program" to be "program_%d" where %d is firstSafeProgramNumber.
                JsonObject passesObject = techniqueObject.get("passes").getAsJsonObject();
                JsonObject programsObject = other.get("programs").getAsJsonObject();
                JsonObject shadersObject = other.get("shaders").getAsJsonObject();
                JsonObject baseShadersObject = getOrCreateJSONElement(base, "shaders").getAsJsonObject();
                for (Entry<String, JsonElement> passEntry : passesObject.entrySet()) {
                    JsonObject passObject = passEntry.getValue().getAsJsonObject();
                    JsonObject instanceProgramObject = passObject.get("instanceProgram").getAsJsonObject();
                    // Get existing program name.
                    String programNameToRewrite = instanceProgramObject.get("program").getAsString();
                    //
                    SimpleEntry<String, String> equivalentProgramReplacementEntry = getEntryByKey(
                            programNameToRewrite, programReplacementTable);
                    String safeProgramName;
                    if (equivalentProgramReplacementEntry != null) {
                        // If the program can request an equivalent program, just rewrite the name in the pass.
                        safeProgramName = equivalentProgramReplacementEntry.getValue();
                    } else {
                        // If the program cannot request an equivalent program, rewrite the name in the pass
                        // Get a safe name for the program.
                        safeProgramName = String.format("program_%d", firstSafeProgramNumber);
                        firstSafeProgramNumber++;
                        // Mark the existing program name to be rewritten as the safe program name.
                        programReplacementTable
                                .add(new SimpleEntry<String, String>(programNameToRewrite, safeProgramName));
                        // Get the existing program object.
                        JsonObject programObject = programsObject.get(programNameToRewrite).getAsJsonObject();
                        // Add applicable shaders to the base object.
                        for (String shaderCategory : Arrays.asList("fragmentShader", "vertexShader",
                                "geometryShader", "tessellationShader", "computeShader")) {
                            if (programObject.has(shaderCategory)) {
                                String shaderName = programObject.get(shaderCategory).getAsString();
                                JsonElement shaderElement = shadersObject.get(shaderName);
                                // TODO: Optionally, rename shader files.
                                // Add shaders to base object.
                                baseShadersObject.add(shaderName, shaderElement);
                            }
                        }
                        // Add the program to the base object under the safe program name.
                        baseProgramsObject.add(safeProgramName, programObject);
                    }
                    // Update the program in the pass's "instanceProgram" -> "program" from: program_0 to program_safeProgramNumber
                    instanceProgramObject.remove("program");
                    instanceProgramObject.addProperty("program", safeProgramName);
                }
                // Add technique to base object.
                techniquesObject.add(safeTechniqueName, joiningElement);
            }
        }
    }
    if (other.has("materials")) {
        JsonElement materialsElement = getOrCreateJSONElement(base, "materials");
        JsonObject materialsObject = materialsElement.getAsJsonObject();
        JsonObject joining = other.get("materials").getAsJsonObject();
        // Entry set yields key like: IfcSlab-fx.
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "IfcSlab-fx", { ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            if (!materialsObject.has(propertyName)) {
                JsonObject otherSpecificMaterialObject = joiningElement.getAsJsonObject();
                JsonObject otherInstanceTechniqueObject = otherSpecificMaterialObject.get("instanceTechnique")
                        .getAsJsonObject();
                String techniqueRequest = otherInstanceTechniqueObject.get("technique").getAsString();
                // Check if there's an existing replacement entry to translate requests for technique0 to techniqueX.
                SimpleEntry<String, String> replacementEntry = getEntryByKey(techniqueRequest,
                        techniqueReplacementTable);
                if (replacementEntry != null) {
                    String newTechnique = replacementEntry.getValue();
                    otherInstanceTechniqueObject.remove("technique");
                    otherInstanceTechniqueObject.addProperty("technique", newTechnique);
                }
                // Otherwise, see if there's an one available in the base object.
                else {
                    String newTechnique = nameOfEquivalentTechniqueInBaseObject(base, other, techniqueRequest);
                    if (newTechnique != null) {
                        otherInstanceTechniqueObject.remove("technique");
                        otherInstanceTechniqueObject.addProperty("technique", newTechnique);
                    }
                }
                materialsObject.add(propertyName, joiningElement);
            }
        }
    }
    if (other.has("meshes")) {
        JsonElement meshesElement = getOrCreateJSONElement(base, "meshes");
        JsonObject meshesObject = meshesElement.getAsJsonObject();
        JsonObject joining = other.get("meshes").getAsJsonObject();
        // Entry set yields key like: "geom-131696".
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "geom-131696", { "primitives": [{ "attributes": { "NORMAL": "accessor_20", ... }, "indices": "accesor_16", ... }, ], ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            if (!meshesObject.has(propertyName)) {
                // Cast to dictionary object.
                JsonObject joiningObject = joiningElement.getAsJsonObject();
                // Get primitives array element.
                JsonElement primitivesArrayElement = joiningObject.get("primitives");
                JsonArray primitivesArray = primitivesArrayElement.getAsJsonArray();
                Iterator<JsonElement> iterator = primitivesArray.iterator();
                while (iterator.hasNext()) {
                    JsonElement dictionaryElement = iterator.next();
                    JsonObject dictionaryObject = dictionaryElement.getAsJsonObject();
                    // Get "attributes" sub-section.
                    JsonElement attributesElement = dictionaryObject.get("attributes");
                    JsonObject attributesObject = attributesElement.getAsJsonObject();
                    JsonObject newAttributesObject = new JsonObject();
                    // Yields keys like: "NORMAL", "POSITION", etc.
                    for (Entry<String, JsonElement> thisEntry : attributesObject.entrySet()) {
                        String thisKey = thisEntry.getKey();
                        JsonElement thisElement = thisEntry.getValue();
                        String accessorName = thisElement.getAsString();
                        String safeAccessorName = String.format("%s_%s", accessorName, suffix);
                        newAttributesObject.addProperty(thisKey, safeAccessorName);
                    }
                    dictionaryObject.remove("attributes");
                    dictionaryObject.add("attributes", newAttributesObject);
                    // Get "indices" entry.
                    JsonElement indicesElement = dictionaryObject.get("indices");
                    String indicesAccessorName = indicesElement.getAsString();
                    String safeIndicesAccessorName = String.format("%s_%s", indicesAccessorName, suffix);
                    dictionaryObject.remove("indices");
                    dictionaryObject.addProperty("indices", safeIndicesAccessorName);
                }
                if (joiningObject.has("extensions")) {
                    // Get extensions dictionary. Iterate keys.
                    JsonObject extensionsObject = joiningObject.get("extensions").getAsJsonObject();
                    // Yields things like: Open3DGC-compression
                    for (Entry<String, JsonElement> extension : extensionsObject.entrySet()) {
                        JsonElement payload = extension.getValue();
                        if (payload instanceof JsonObject) {
                            JsonObject payloadObject = payload.getAsJsonObject();
                            // Get "compressedData"?
                            for (Entry<String, JsonElement> payloadElement : payloadObject.entrySet()) {
                                JsonElement itemElement = payloadElement.getValue();
                                // 
                                if (itemElement instanceof JsonObject) {
                                    //
                                    JsonObject itemObject = itemElement.getAsJsonObject();
                                    if (itemObject.has("bufferView")) {
                                        String bufferViewName = itemObject.get("bufferView").getAsString();
                                        String safeBufferViewName = String.format("%s_%s", bufferViewName,
                                                suffix);
                                        itemObject.remove("bufferView");
                                        itemObject.addProperty("bufferView", safeBufferViewName);
                                    }
                                }
                            }
                        }
                    }
                }
                // "P1_suffix": { "path": "P1_suffix.bin", ... }
                meshesObject.add(propertyName, joiningElement);
            }
        }
    }
    if (other.has("nodes")) {
        JsonElement nodesElement = getOrCreateJSONElement(base, "nodes");
        JsonObject nodesObject = nodesElement.getAsJsonObject();
        JsonObject joining = other.get("nodes").getAsJsonObject();
        // Entry set yields key like: node-131696.
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "node-131696", { ... }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            if (!nodesObject.has(propertyName))
                nodesObject.add(propertyName, joiningElement);
        }
    }
    if (other.has("scenes")) {
        JsonElement scenesElement = getOrCreateJSONElement(base, "scenes");
        JsonObject scenesObject = scenesElement.getAsJsonObject();
        JsonObject joining = other.get("scenes").getAsJsonObject();
        // Entry set yields key like: defaultScene.
        for (Map.Entry<String, JsonElement> entry : joining.entrySet()) {
            // Get: "defaultScene", { "nodes": [ "node-131696", ... ], }
            String propertyName = entry.getKey();
            JsonElement joiningElement = entry.getValue();
            // Scene key not found in the base, so add the whole thing.
            if (!scenesObject.has(propertyName))
                scenesObject.add(propertyName, joiningElement);
            // Scene key is found in the base, so append the values.
            else {
                // Get the base propertyName (dictionary) -> "nodes" array.
                JsonElement baseScene = scenesObject.get(propertyName);
                JsonObject baseSceneObject = baseScene.getAsJsonObject();
                JsonElement baseNodesElement = baseSceneObject.get("nodes");
                JsonArray baseNodesArray = baseNodesElement.getAsJsonArray();
                // Get the joining propertyName (dictionary) -> "nodes" array.
                JsonObject joiningObject = joiningElement.getAsJsonObject();
                JsonElement nodesElement = joiningObject.get("nodes");
                JsonArray nodesArray = nodesElement.getAsJsonArray();
                // Add the values.
                baseNodesArray.addAll(nodesArray);
            }
        }
    }
    return baseElement;
}

From source file:org.cgiar.ccafs.marlo.utils.AutoSaveReader.java

License:Open Source License

private HashMap<String, Object> convertJSONFormat(String json) {

    HashMap<String, Object> jsonNew = new HashMap<>();
    Gson gson = new Gson();
    LinkedTreeMap<String, Object> result = gson.fromJson(json, LinkedTreeMap.class);
    HashMap<String, Object> onetoMany = new HashMap<>();
    JsonObject jobj = new Gson().fromJson(json, JsonObject.class);
    for (Map.Entry<String, Object> entry : result.entrySet()) {
        String value = entry.getValue().toString();
        String key = entry.getKey();
        if (!key.contains("[")) {
            String oneToManys[] = key.split("\\.");
            if (oneToManys.length > 1) {
                onetoMany.put(key, entry.getValue());
                jobj.remove(key);
            } else {
                if (!key.contains("__")) {
                    jsonNew.put(key, value);
                    jobj.remove(key);// w ww  .  j  ava  2  s . c  om
                }

            }
        }
    }

    if (!onetoMany.isEmpty()) {
        jsonNew.putAll(this.getOneToMany(gson.toJson(onetoMany)));
    }

    result = gson.fromJson(jobj, LinkedTreeMap.class);
    Set<String> listNames = new HashSet<>();
    for (Map.Entry<String, Object> entry : result.entrySet()) {
        String key = entry.getKey();
        String keys[] = key.split("\\.");
        String keyList = keys[0];
        keyList = keyList.split("\\[")[0];
        listNames.add(keyList);
    }
    for (String keyList : listNames) {

        HashMap<String, Object> list = this.getListJsonParent(keyList, jobj);
        if (list.size() > 0) {
            jsonNew.putAll(list);
        }
    }

    return jsonNew;
}

From source file:org.cgiar.ccafs.marlo.utils.AutoSaveReader.java

License:Open Source License

private HashMap<String, Object> getListJson(String keyParent, JsonObject jobj, int i) {
    HashMap<String, Object> jsonNew = new HashMap<>();
    Gson gson = new Gson();
    HashMap<String, Object> relations = new HashMap<>();
    HashMap<String, Object> onetoMany = new HashMap<>();

    LinkedTreeMap<String, Object> result = gson.fromJson(jobj, LinkedTreeMap.class);
    for (Map.Entry<String, Object> entry : result.entrySet()) {
        String key = entry.getKey().split("\\.")[0];
        if (key.equals(keyParent + "[" + i + "]")) {
            String newKey = entry.getKey().replace(keyParent + "[" + i + "].", "");

            if (!newKey.contains("[")) {
                String oneToManys[] = newKey.split("\\.");
                if (oneToManys.length > 1) {
                    onetoMany.put(newKey, entry.getValue());
                } else {
                    jsonNew.put(entry.getKey().replace(keyParent + "[" + i + "].", ""), entry.getValue());
                    jobj.remove(key);
                }/*  w w w  .jav a  2s .c om*/

            } else {

                relations.put(newKey, entry.getValue());
                jobj.remove(key);
            }
        }
    }
    if (!onetoMany.isEmpty()) {
        jsonNew.putAll(this.getOneToMany(gson.toJson(onetoMany)));
    }
    if (!relations.isEmpty()) {
        jsonNew.putAll(this.convertJSONFormat(gson.toJson(relations)));
    }
    return jsonNew;
}

From source file:org.cgiar.ccafs.marlo.utils.AutoSaveReader.java

License:Open Source License

private HashMap<String, Object> getOneToMany(String json) {
    Gson gson = new Gson();
    JsonObject jobj = gson.fromJson(json, JsonObject.class);
    HashMap<String, Object> jsonNew = new HashMap<>();
    LinkedTreeMap<String, Object> result = gson.fromJson(jobj, LinkedTreeMap.class);
    Set<String> listNames = new HashSet<>();
    HashMap<String, Object> onetoMany = new HashMap<>();
    for (Map.Entry<String, Object> entry : result.entrySet()) {
        String key = entry.getKey();
        String keys[] = key.split("\\.");
        String keyList = keys[0];

        listNames.add(keyList);//from   ww  w.  ja  v  a  2 s  .  c  o  m
    }
    for (String name : listNames) {
        HashMap<String, Object> relation = new HashMap<>();
        for (Map.Entry<String, Object> entry : result.entrySet()) {
            String key = entry.getKey();
            String keys[] = key.split("\\.");
            String keyList = keys[0];
            if (keys.length >= 3) {
                onetoMany = new HashMap<>();
                onetoMany.put(key.replaceAll(keyList + "\\." + keys[1] + "\\.", ""), entry.getValue());
                relation.put(keys[1], this.convertJSONFormat(gson.toJson(onetoMany)));
            } else {
                if (keyList.equals(name)) {

                    relation.put(keys[1], entry.getValue());
                    jobj.remove(key);

                }
            }
        }

        jsonNew.put(name, relation);

    }
    return jsonNew;
}

From source file:org.cgiar.ccafs.marlo.utils.AutoSaveReader.java

License:Open Source License

public Object readFromJson(JsonObject jobj) {

    Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(Integer.class, new IntegerTypeAdapter())
            .registerTypeAdapter(Long.class, new LongTypeAdapter())
            .registerTypeAdapter(Double.class, new DoubleTypeAdapter())
            .registerTypeAdapter(Float.class, new FloatTypeAdapter())
            .registerTypeAdapter(Number.class, new IntegerTypeAdapter())
            .registerTypeAdapter(BigDecimal.class, new BigDecimalTypeAdapter())
            .registerTypeAdapter(Date.class, new DateTypeAdapter())
            .registerTypeAdapter(String.class, new StringTypeAdapter()).create();
    HashMap<String, Object> jsonNew = this.convertJSONFormat(gson.toJson(jobj));

    jobj = gson.fromJson(gson.toJson(jsonNew), JsonObject.class);

    String className = jobj.get("className").getAsString();

    jobj.remove("className");
    try {/*from  w  w w  .j a  v  a 2  s  .c  o m*/
        Object obj = gson.fromJson(jobj, Class.forName(className));
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e.getLocalizedMessage());

    }
    return null;

}

From source file:org.commoncrawl.mapred.ec2.parser.ParserMapper.java

License:Open Source License

private static void safeAppendLinksFromFeed(JsonObject feedOrItemObj,
        ImmutableMap<String, String> validLinkTypes, List<FeedLink> feedMetaLinks, List links)
        throws IOException {
    for (Object link : links) {
        com.sun.syndication.feed.atom.Link linkObj = (com.sun.syndication.feed.atom.Link) link;
        if (linkObj.getHref() != null && linkObj.getRel() != null) {

            if (validLinkTypes.keySet().contains(linkObj.getRel())) {
                JsonObject jsonLink = new JsonObject();
                FeedLink metaLink = new FeedLink();

                safeSetString(jsonLink, "type", linkObj.getType());
                if (linkObj.getType() != null)
                    metaLink.setType(linkObj.getType());
                safeSetString(jsonLink, "href", linkObj.getHref());
                if (linkObj.getHref() != null)
                    metaLink.setHref(linkObj.getHref());
                safeSetString(jsonLink, "rel", linkObj.getRel());
                if (linkObj.getRel() != null)
                    metaLink.setRel(linkObj.getRel());

                safeSetString(jsonLink, "title", linkObj.getTitle());
                if (linkObj.getTitle() != null)
                    metaLink.setTitle(linkObj.getTitle());

                feedMetaLinks.add(metaLink);

                String linkName = validLinkTypes.get(linkObj.getRel());

                JsonElement existing = feedOrItemObj.get(linkName);
                if (existing != null) {
                    JsonArray array = null;
                    if (!existing.isJsonArray()) {
                        array = new JsonArray();
                        array.add(existing);
                        feedOrItemObj.remove(linkName);
                        feedOrItemObj.add(linkName, array);
                    } else {
                        array = existing.getAsJsonArray();
                    }//from www.  j  av  a2s. co m
                    array.add(jsonLink);
                } else {
                    feedOrItemObj.add(linkName, jsonLink);
                }
            }
        }
    }
}