List of usage examples for com.google.gson JsonArray addAll
public void addAll(JsonArray array)
From source file:moodleclient.DataClasses.Checkpoint.java
/** * turns this checkpoint into it's JsonObject equivalent with any unchanged * fields removed//from w w w . j a v a 2 s .co m * * @param fileList * @param filePathNameList * @return this object as a JsonObject */ public JsonObject getJsonChange(ArrayList<String> fileList, ArrayList<String> filePathNameList) { JsonObject result = new JsonObject(); if (id == 0) { result.add("id", new JsonPrimitive("n" + ordering)); } else { result.add("id", new JsonPrimitive(id)); } if (changed) { if (changedVars[2]) { result.add("ordering", new JsonPrimitive(ordering)); } if (changedVars[0]) { result.add("description", new JsonPrimitive(description)); } if (changedVars[1]) { result.add("runtimeargs", new JsonPrimitive(runtimeargs)); } if (changedVars[3]) { result.add("marks", new JsonPrimitive(marks)); } } // add tests if they have changed JsonArray testsJA = new JsonArray(); testsJA.addAll(deletedts); boolean hasChangedTests = testsJA.size() != 0; for (CHITest aTest : testsO.values()) { if (aTest.isChanged()) { testsJA.add(aTest.getJsonChange(fileList, filePathNameList)); hasChangedTests = true; } } if (hasChangedTests) { result.add("tests", testsJA); } if (hasChangedTests || changed) { return result; } return null; }
From source file:moodleclient.DataClasses.Codehandin.java
/** * turns this checkpoint into it's JsonObject equivalent with any unchanged * fields removed/*from w ww . j a v a2s . co m*/ * * @return this object as a JsonObject */ public ChangeObject getChangeData() { ArrayList<String> fileList = new ArrayList<>(); ArrayList<String> filePathNameList = new ArrayList<>(); JsonObject result = new JsonObject(); if (id != 0) { result.add("id", new JsonPrimitive(id)); result.add("contextid", new JsonPrimitive(contextid)); } // add checkpoints if they have changed if (clean) { result.add("clean", new JsonPrimitive(true)); } if (changed) { result.add("changed", new JsonPrimitive(true)); // tells it that its the codehandin thats changed if (changedVars[0]) { result.add("assignname", new JsonPrimitive(assignname)); } if (changedVars[1]) { result.add("intro", new JsonPrimitive(intro)); } if (changedVars[2]) { result.add("duedate", new JsonPrimitive(duedate)); } if (changedVars[3]) { result.add("funcpercent", new JsonPrimitive(funcpercent)); } if (changedVars[4]) { result.add("spectestonly", new JsonPrimitive(spectestonly)); } // if (changedVars[5]) { // result.add("spectestruntimeargs", new JsonPrimitive(spectestruntimeargs)); // } // if (changedVars[6]) { // result.add("spectestaruntimeargs", new JsonPrimitive(spectestaruntimeargse)); // } if (changedVars[7]) { result.add("mustattemptcompile", new JsonPrimitive(mustattemptcompile)); } if (changedVars[8]) { result.add("proglangid", new JsonPrimitive(proglangid)); } } JsonArray checkpointsJA = new JsonArray(); checkpointsJA.addAll(deletedcps); boolean hasChangedCheckpoints = checkpointsJA.size() != 0; for (Checkpoint aCheckpoint : checkpointsO.values()) { if (aCheckpoint.isChanged()) { checkpointsJA.add(aCheckpoint.getJsonChange(fileList, filePathNameList)); hasChangedCheckpoints = true; } } if (!fileList.isEmpty()) { result.add("hasfiles", new JsonPrimitive(true)); } if (hasChangedCheckpoints) { result.add("checkpoints", checkpointsJA); } boolean ret = false; if (changed || hasChangedCheckpoints) { ret = true; } File zipFile = null; if (!fileList.isEmpty()) { zipFile = ZipUtility.zipIt(fileList, filePathNameList, baseFolder.substring(0, baseFolder.length() - 2) + "az/" + id + ".zip"); ret = true; } return new ChangeObject(result, zipFile); }
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 w w. j a v a2s .com } 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.ballerinalang.langserver.SourceGen.java
License:Open Source License
@FindbugsSuppressWarnings private void modifyNode(JsonObject node, String parentKind) { String kind = node.get("kind").getAsString(); if (kind.equals("If")) { if (node.getAsJsonObject("elseStatement") != null) { node.addProperty("ladderParent", true); }//from w w w .j av a 2 s .co m 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 (kind.equals("Transaction")) { if (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 ((kind.equals("XmlCommentLiteral") || kind.equals("XmlElementLiteral") || kind.equals("XmlTextLiteral") || kind.equals("XmlPiLiteral")) && 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 (parentKind.equals("XmlElementLiteral") || parentKind.equals("XmlTextLiteral") || parentKind.equals("XmlPiLiteral")) { node.addProperty("inTemplateLiteral", true); } if (kind.equals("XmlPiLiteral") && node.has("ws")) { JsonObject startTagWS = new JsonObject(); startTagWS.addProperty("text", "<?"); startTagWS.addProperty("ws", ""); JsonObject endTagWS = new JsonObject(); endTagWS.addProperty("text", "?>"); endTagWS.addProperty("ws", ""); if (node.has("root") && node.get("root").getAsBoolean() && node.getAsJsonArray("ws").size() > 1) { node.add("ws", addDataToArray(1, startTagWS, node.getAsJsonArray("ws"))); node.add("ws", addDataToArray(2, endTagWS, node.getAsJsonArray("ws"))); } if (!node.has("root") || !(node.has("root") && node.get("root").getAsBoolean())) { node.add("ws", addDataToArray(0, startTagWS, node.getAsJsonArray("ws"))); node.add("ws", addDataToArray(node.getAsJsonArray("ws").size(), endTagWS, node.getAsJsonArray("ws"))); } if (node.has("target") && node.getAsJsonObject("target").has("unescapedValue")) { JsonObject target = node.getAsJsonObject("target"); for (int i = 0; i < target.getAsJsonArray("ws").size(); i++) { if (target.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString() .contains("<?") && target.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString() .contains(target.get("unescapedValue").getAsString())) { target.addProperty("unescapedValue", target.getAsJsonArray("ws").get(i).getAsJsonObject() .get("text").getAsString().replace("<?", "")); } } } } if (kind.equals("AnnotationAttachment") && node.getAsJsonObject("packageAlias").get("value").getAsString().equals("builtin")) { node.addProperty("builtin", true); } if (kind.equals("Identifier")) { if (node.has("literal") && node.get("literal").getAsBoolean()) { node.addProperty("valueWithBar", "^\"" + node.get("value").getAsString() + "\""); } else { node.addProperty("valueWithBar", node.get("value").getAsString()); } } if (kind.equals("Import")) { if (node.getAsJsonObject("alias") != null && node.getAsJsonObject("alias").get("value") != null && node.getAsJsonArray("packageName") != null && node.getAsJsonArray("packageName").size() != 0) { if (!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 (parentKind.equals("CompilationUnit") && (kind.equals("Variable") || kind.equals("Xmlns"))) { node.addProperty("global", true); } if (kind.equals("VariableDef") && 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 (kind.equals("Variable")) { if (parentKind.equals("ObjectType")) { 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").has("async") && node.getAsJsonObject("initialExpression").get("async").getAsBoolean()) { 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("start")) { if (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 (kind.equals("Service")) { if (!node.has("serviceTypeStruct")) { node.addProperty("isServiceTypeUnavailable", 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 (kind.equals("Resource") && node.has("parameters") && node.getAsJsonArray("parameters").size() > 0) { if (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 (kind.equals("ForkJoin")) { 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")); } } // Check if sorrounded by curlies if (kind.equals("MatchPatternClause") || kind.equals("MatchExpressionPatternClause")) { if (node.has("ws") && node.getAsJsonArray("ws").size() > 2) { node.addProperty("withCurlies", true); } } // Check if sorrounded by parantheses if (kind.equals("ValueType")) { 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 (kind.equals("UnionTypeNode") && 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 (kind.equals("Function")) { 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().getAsJsonObject("variable") .addProperty("defaultable", true); } } // Sort and add all the parameters. JsonArray allParamsTemp = node.getAsJsonArray("parameters"); allParamsTemp.addAll(node.getAsJsonArray("defaultableParameters")); List<JsonElement> allParamElements = new ArrayList<>(); allParamsTemp.forEach(jsonElement -> { allParamElements.add(jsonElement); }); Collections.sort(allParamElements, (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(jsonElement -> { allParams.add(jsonElement); }); 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("parameters") && node.getAsJsonArray("parameters").size() > 0) { node.addProperty("hasRestParams", true); } if (node.has("restParameters") && node.getAsJsonObject("restParameters").has("typeNode")) { node.getAsJsonObject("restParameters").getAsJsonObject("typeNode").addProperty("isRestParam", true); } } if (kind.equals("TypeDefinition") && node.has("typeNode")) { if (!node.has("ws")) { node.addProperty("notVisible", true); } if (node.has("name") && node.getAsJsonObject("name").get("value").getAsString().startsWith("$anonType$")) { this.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.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 (kind.equals("ObjectType")) { if (node.has("initFunction")) { if (!node.getAsJsonObject("initFunction").has("ws")) { node.getAsJsonObject("initFunction").addProperty("defaultConstructor", true); } else { node.getAsJsonObject("initFunction").addProperty("isConstructor", true); } } } if (kind.equals("RecordType")) { if (node.has("restFieldType")) { node.addProperty("isRestFieldAvailable", true); } } if (kind.equals("TypeInitExpr")) { 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 (kind.equals("Return")) { if (node.has("expression") && 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); } } } if (kind.equals("Documentation")) { 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 (kind.equals("Function") || kind.equals("Resource")) { if (node.has("restParameters")) { node.getAsJsonObject("restParameters").addProperty("rest", true); } } if (kind.equals("PostIncrement")) { node.addProperty("operator", (node.get("operatorKind").getAsString() + node.get("operatorKind").getAsString())); } if (kind.equals("SelectExpression") && node.has("identifier")) { node.addProperty("identifierAvailable", true); } if (kind.equals("StreamAction") && node.has("invokableBody")) { if (node.getAsJsonObject("invokableBody").has("functionNode")) { node.getAsJsonObject("invokableBody").getAsJsonObject("functionNode").addProperty("isStreamAction", true); } } if (kind.equals("StreamingInput") && node.has("alias")) { node.addProperty("aliasAvailable", true); } if (kind.equals("IntRangeExpr")) { if (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 (kind.equals("FunctionType")) { 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 (kind.equals("Literal") && !parentKind.equals("StringTemplateLiteral")) { 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 (kind.equals("Foreach")) { if (node.has("ws")) { for (JsonElement ws : node.getAsJsonArray("ws")) { if (ws.getAsJsonObject().get("text").getAsString().equals("(")) { node.addProperty("withParantheses", true); break; } } } } if (kind.equals("Endpoint")) { if (node.has("ws")) { for (JsonElement ws : node.getAsJsonArray("ws")) { if (ws.getAsJsonObject().get("text").getAsString().equals("=")) { node.addProperty("isConfigAssignment", true); break; } } } } if (kind.equals("UserDefinedType")) { 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 (kind.equals("ArrayType")) { if (node.has("dimensions") && node.get("dimensions").getAsInt() > 0 && node.has("ws")) { String dimensionAsString = ""; JsonObject startingBracket = null; JsonObject endingBracket = null; 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 += startingBracket.get("text").getAsString() + content.toString() + endingBracket.get("ws").getAsString() + endingBracket.get("text").getAsString(); startingBracket = null; endingBracket = 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); } } if (kind.equals("Block") && node.has("ws") && node.getAsJsonArray("ws").size() > 0 && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("else")) { node.addProperty("isElseBlock", true); } if (kind.equals("FieldBasedAccessExpr") && node.has("ws") && node.getAsJsonArray("ws").size() > 0 && node.getAsJsonArray("ws").get(0).getAsJsonObject().get("text").getAsString().equals("!")) { node.addProperty("errorLifting", true); } if (kind.equals("StringTemplateLiteral")) { if (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 (kind.equals("XmlCommentLiteral") && node.has("ws")) { int length = node.getAsJsonArray("ws").size(); for (int i = 0; i < length; i++) { if (node.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString().contains("-->") && node.getAsJsonArray("ws").get(i).getAsJsonObject().get("text").getAsString() .length() > 3) { JsonObject ws = new JsonObject(); ws.addProperty("text", "-->"); ws.addProperty("ws", ""); node.getAsJsonArray("ws").get(i).getAsJsonObject().addProperty("text", node.getAsJsonArray("ws") .get(i).getAsJsonObject().get("text").getAsString().replace("-->", "")); node.add("ws", addDataToArray(i + 1, ws, node.getAsJsonArray("ws"))); break; } } if (node.has("root") && node.get("root").getAsBoolean()) { literalWSAssignForTemplates(2, 3, node.getAsJsonArray("textFragments"), node.getAsJsonArray("ws"), 4); } else { literalWSAssignForTemplates(1, 2, node.getAsJsonArray("textFragments"), node.getAsJsonArray("ws"), 2); } } }
From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java
License:Open Source License
private JsonElement selectivelyJoinTwoJSONElements(JsonElement baseElement, JsonElement otherElement, String suffix) {//from w ww.j a 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.commoncrawl.util.S3BulkTransferUtil.java
License:Open Source License
public static void main(String[] args) throws IOException { CommandLineParser parser = new GnuParser(); try {//from w w w . j a v a 2 s . c o m // parse the command line arguments CommandLine cmdLine = parser.parse(options, args); String s3AccessKey = cmdLine.getOptionValue("awsKey"); String s3Secret = cmdLine.getOptionValue("awsSecret"); String s3Bucket = cmdLine.getOptionValue("bucket"); Path hdfsOutputPath = new Path(cmdLine.getOptionValue("outputPath")); JsonArray paths = new JsonArray(); if (cmdLine.hasOption("path")) { String values[] = cmdLine.getOptionValues("path"); for (String value : values) { paths.add(new JsonPrimitive(value)); } } if (cmdLine.hasOption("paths")) { JsonParser jsonParser = new JsonParser(); JsonReader reader = new JsonReader(new StringReader(cmdLine.getOptionValue("paths"))); reader.setLenient(true); JsonArray array = jsonParser.parse(reader).getAsJsonArray(); if (array != null) { paths.addAll(array); } } if (paths.size() == 0) { throw new IOException("No Input Paths Specified!"); } LOG.info("Bucket:" + s3Bucket + " Target Paths:" + paths.toString()); S3BulkTransferUtil util = new S3BulkTransferUtil(s3Bucket, s3AccessKey, s3Secret, paths, hdfsOutputPath); } catch (Exception e) { LOG.error(CCStringUtils.stringifyException(e)); printUsage(); } }
From source file:org.eclipse.cdt.build.gcc.core.GCCUserToolChainProvider.java
License:Open Source License
@Override public void removeToolChain(IToolChain toolChain) throws CoreException { if (toolChains != null) { String id = toolChain.getId(); JsonArray copy = new JsonArray(); copy.addAll(toolChains); for (JsonElement element : copy) { JsonObject tc = element.getAsJsonObject(); if (id.equals(tc.get(ID).getAsString())) { toolChains.remove(element); }/* w w w.j a v a 2 s . com*/ } try { saveJsonFile(); } catch (IOException e) { throw new CoreException( new Status(IStatus.ERROR, Activator.getId(), Messages.GCCUserToolChainProvider_Saving1, e)); } } manager.removeToolChain(toolChain); }
From source file:org.kurento.modulecreator.codegen.JsonFusioner.java
License:Apache License
private void addChildren(JsonElement fromElement, JsonElement toElement) { if (fromElement instanceof JsonObject && toElement instanceof JsonObject) { JsonObject fromObject = (JsonObject) fromElement; JsonObject toObject = (JsonObject) toElement; for (Entry<String, JsonElement> entry : fromObject.entrySet()) { toObject.add(entry.getKey(), entry.getValue()); }//from w w w.ja v a 2s .c o m } else if (fromElement instanceof JsonArray && toElement instanceof JsonArray) { JsonArray fromArray = (JsonArray) fromElement; JsonArray toArray = (JsonArray) toElement; toArray.addAll(fromArray); } }
From source file:org.matrix.androidsdk.call.MXJingleCall.java
License:Apache License
/** * create the local stream//from ww w. j a v a 2s .co m */ private void createLocalStream() { Log.d(LOG_TAG, "## createLocalStream(): IN"); // check there is at least one stream to start a call if ((null == mLocalVideoTrack) && (null == mLocalAudioTrack)) { Log.d(LOG_TAG, "## createLocalStream(): CALL_ERROR_CALL_INIT_FAILED"); dispatchOnCallError(CALL_ERROR_CALL_INIT_FAILED); hangup("no_stream"); terminate(IMXCall.END_CALL_REASON_UNDEFINED); return; } // create our local stream to add our audio and video tracks mLocalMediaStream = mPeerConnectionFactory.createLocalMediaStream("ARDAMS"); // add video track to local stream if (null != mLocalVideoTrack) { mLocalMediaStream.addTrack(mLocalVideoTrack); } // add audio track to local stream if (null != mLocalAudioTrack) { mLocalMediaStream.addTrack(mLocalAudioTrack); } // build ICE servers list ArrayList<PeerConnection.IceServer> iceServers = new ArrayList<>(); if (null != mTurnServer) { try { String username = null; String password = null; JsonObject object = mTurnServer.getAsJsonObject(); if (object.has("username")) { username = object.get("username").getAsString(); } if (object.has("password")) { password = object.get("password").getAsString(); } JsonArray uris = object.get("uris").getAsJsonArray(); for (int index = 0; index < uris.size(); index++) { String url = uris.get(index).getAsString(); if ((null != username) && (null != password)) { iceServers.add(new PeerConnection.IceServer(url, username, password)); } else { iceServers.add(new PeerConnection.IceServer(url)); } } } catch (Exception e) { Log.e(LOG_TAG, "## createLocalStream(): Exception in ICE servers list Msg=" + e.getLocalizedMessage()); } } // define at least on server if (iceServers.size() == 0) { iceServers.add(new PeerConnection.IceServer("stun:stun.l.google.com:19302")); } // define constraints MediaConstraints pcConstraints = new MediaConstraints(); pcConstraints.optional.add(new MediaConstraints.KeyValuePair("RtpDataChannels", "true")); // start connecting to the other peer by creating the peer connection mPeerConnection = mPeerConnectionFactory.createPeerConnection(iceServers, pcConstraints, new PeerConnection.Observer() { @Override public void onSignalingChange(PeerConnection.SignalingState signalingState) { Log.d(LOG_TAG, "## mPeerConnection creation: onSignalingChange state=" + signalingState); } @Override public void onIceConnectionChange(final PeerConnection.IceConnectionState iceConnectionState) { Log.d(LOG_TAG, "## mPeerConnection creation: onIceConnectionChange " + iceConnectionState); mUIThreadHandler.post(new Runnable() { @Override public void run() { if (iceConnectionState == PeerConnection.IceConnectionState.CONNECTED) { if ((null != mLocalVideoTrack) && mUsingLargeLocalRenderer && isVideo()) { mLocalVideoTrack.setEnabled(false); VideoRendererGui.remove(mLargeLocalRendererCallbacks); mLocalVideoTrack.removeRenderer(mLargeLocalRenderer); // in conference call, there is no local preview, // the local attendee video is sent by the server among the others conference attendees. if (!isConference()) { // add local preview, only for 1:1 call mLocalVideoTrack.addRenderer(mSmallLocalRenderer); } listenPreviewUpdate(); mLocalVideoTrack.setEnabled(true); mUsingLargeLocalRenderer = false; mCallView.post(new Runnable() { @Override public void run() { if (null != mCallView) { mCallView.invalidate(); } } }); } dispatchOnStateDidChange(IMXCall.CALL_STATE_CONNECTED); } // theses states are ignored // only the matrix hangup event is managed /*else if (iceConnectionState == PeerConnection.IceConnectionState.DISCONNECTED) { // TODO warn the user ? hangup(null); } else if (iceConnectionState == PeerConnection.IceConnectionState.CLOSED) { // TODO warn the user ? terminate(); }*/ else if (iceConnectionState == PeerConnection.IceConnectionState.FAILED) { dispatchOnCallError(CALL_ERROR_ICE_FAILED); hangup("ice_failed"); } } }); } @Override public void onIceConnectionReceivingChange(boolean var1) { Log.d(LOG_TAG, "## mPeerConnection creation: onIceConnectionReceivingChange " + var1); } @Override public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) { Log.d(LOG_TAG, "## mPeerConnection creation: onIceGatheringChange " + iceGatheringState); } @Override public void onIceCandidate(final IceCandidate iceCandidate) { Log.d(LOG_TAG, "## mPeerConnection creation: onIceCandidate " + iceCandidate); mUIThreadHandler.post(new Runnable() { @Override public void run() { if (!isCallEnded()) { JsonObject content = new JsonObject(); content.addProperty("version", 0); content.addProperty("call_id", mCallId); JsonArray candidates = new JsonArray(); JsonObject cand = new JsonObject(); cand.addProperty("sdpMLineIndex", iceCandidate.sdpMLineIndex); cand.addProperty("sdpMid", iceCandidate.sdpMid); cand.addProperty("candidate", iceCandidate.sdp); candidates.add(cand); content.add("candidates", candidates); boolean addIt = true; // merge candidates if (mPendingEvents.size() > 0) { try { Event lastEvent = mPendingEvents.get(mPendingEvents.size() - 1); if (TextUtils.equals(lastEvent.getType(), Event.EVENT_TYPE_CALL_CANDIDATES)) { // return the content cast as a JsonObject // it is not a copy JsonObject lastContent = lastEvent.getContentAsJsonObject(); JsonArray lastContentCandidates = lastContent.get("candidates") .getAsJsonArray(); JsonArray newContentCandidates = content.get("candidates") .getAsJsonArray(); Log.d(LOG_TAG, "Merge candidates from " + lastContentCandidates.size() + " to " + (lastContentCandidates.size() + newContentCandidates.size() + " items.")); lastContentCandidates.addAll(newContentCandidates); // replace the candidates list lastContent.remove("candidates"); lastContent.add("candidates", lastContentCandidates); // don't need to save anything, lastContent is a reference not a copy addIt = false; } } catch (Exception e) { Log.e(LOG_TAG, "## createLocalStream(): createPeerConnection - onIceCandidate() Exception Msg=" + e.getMessage()); } } if (addIt) { Event event = new Event(Event.EVENT_TYPE_CALL_CANDIDATES, content, mSession.getCredentials().userId, mCallSignalingRoom.getRoomId()); mPendingEvents.add(event); sendNextEvent(); } } } }); } @Override public void onAddStream(final MediaStream mediaStream) { Log.d(LOG_TAG, "## mPeerConnection creation: onAddStream " + mediaStream); mUIThreadHandler.post(new Runnable() { @Override public void run() { if ((mediaStream.videoTracks.size() == 1) && !isCallEnded()) { mRemoteVideoTrack = mediaStream.videoTracks.get(0); mRemoteVideoTrack.setEnabled(true); mRemoteVideoTrack.addRenderer(mLargeRemoteRenderer); } } }); } @Override public void onRemoveStream(final MediaStream mediaStream) { Log.d(LOG_TAG, "## mPeerConnection creation: onRemoveStream " + mediaStream); mUIThreadHandler.post(new Runnable() { @Override public void run() { if (null != mRemoteVideoTrack) { mRemoteVideoTrack.dispose(); mRemoteVideoTrack = null; mediaStream.videoTracks.get(0).dispose(); } } }); } @Override public void onDataChannel(DataChannel dataChannel) { Log.d(LOG_TAG, "## mPeerConnection creation: onDataChannel " + dataChannel); } @Override public void onRenegotiationNeeded() { Log.d(LOG_TAG, "## mPeerConnection creation: onRenegotiationNeeded"); } }); // send our local video and audio stream to make it seen by the other part mPeerConnection.addStream(mLocalMediaStream); MediaConstraints constraints = new MediaConstraints(); constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true")); constraints.mandatory .add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", isVideo() ? "true" : "false")); // call createOffer only for outgoing calls if (!isIncoming()) { Log.d(LOG_TAG, "## createLocalStream(): !isIncoming() -> createOffer"); mPeerConnection.createOffer(new SdpObserver() { @Override public void onCreateSuccess(SessionDescription sessionDescription) { Log.d(LOG_TAG, "createOffer onCreateSuccess"); final SessionDescription sdp = new SessionDescription(sessionDescription.type, sessionDescription.description); mUIThreadHandler.post(new Runnable() { @Override public void run() { if (mPeerConnection != null) { // must be done to before sending the invitation message mPeerConnection.setLocalDescription(new SdpObserver() { @Override public void onCreateSuccess(SessionDescription sessionDescription) { Log.d(LOG_TAG, "setLocalDescription onCreateSuccess"); } @Override public void onSetSuccess() { Log.d(LOG_TAG, "setLocalDescription onSetSuccess"); sendInvite(sdp); dispatchOnStateDidChange(IMXCall.CALL_STATE_INVITE_SENT); } @Override public void onCreateFailure(String s) { Log.e(LOG_TAG, "setLocalDescription onCreateFailure " + s); dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED); hangup(null); } @Override public void onSetFailure(String s) { Log.e(LOG_TAG, "setLocalDescription onSetFailure " + s); dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED); hangup(null); } }, sdp); } } }); } @Override public void onSetSuccess() { Log.d(LOG_TAG, "createOffer onSetSuccess"); } @Override public void onCreateFailure(String s) { Log.d(LOG_TAG, "createOffer onCreateFailure " + s); dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED); } @Override public void onSetFailure(String s) { Log.d(LOG_TAG, "createOffer onSetFailure " + s); dispatchOnCallError(CALL_ERROR_CAMERA_INIT_FAILED); } }, constraints); dispatchOnStateDidChange(IMXCall.CALL_STATE_WAIT_CREATE_OFFER); } }
From source file:org.openscore.content.json.actions.MergeArrays.java
License:Open Source License
/** * This operation merge the contents of two JSON arrays. This operation does not modify either of the input arrays. * The result is the contents or array1 and array2, merged into a single array. The merge operation add into the result * the first array and then the second array. * * @param array1 The string representation of a JSON array object. * Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. * Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] * @param array2 The string representation of a JSON array object. * Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. * Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] * @return a map containing the output of the operation. Keys present in the map are: * <p/>/* w w w . ja v a2s.c om*/ * <br><br><b>returnResult</b> - This will contain the string representation of the new JSON array with the contents * of array1 and array2. * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, * this result contains the java stack trace of the runtime exception. * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. */ @Action(name = "Merge Arrays", outputs = { @Output(Constants.OutputNames.RETURN_RESULT), @Output(Constants.OutputNames.RETURN_CODE), @Output(Constants.OutputNames.EXCEPTION) }, responses = { @Response(text = Constants.ResponseNames.SUCCESS, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Constants.ResponseNames.FAILURE, field = Constants.OutputNames.RETURN_CODE, value = Constants.ReturnCodes.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1, @Param(value = Constants.InputNames.ARRAY, required = true) String array2) { Map<String, String> returnResult = new HashMap<>(); JsonParser jsonParser = new JsonParser(); JsonElement parsedArray1; JsonElement parsedArray2; if (isBlank(array1)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", ""); return populateResult(returnResult, exceptionValue, new Exception(exceptionValue)); } if (isBlank(array2)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", ""); return populateResult(returnResult, new Exception(exceptionValue)); } try { parsedArray1 = jsonParser.parse(array1); } catch (JsonSyntaxException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1; return populateResult(returnResult, value, exception); } try { parsedArray2 = jsonParser.parse(array2); } catch (JsonSyntaxException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2; return populateResult(returnResult, value, exception); } final String result; if (parsedArray1.isJsonArray() && parsedArray2.isJsonArray()) { final JsonArray asJsonArray1 = parsedArray1.getAsJsonArray(); final JsonArray asJsonArray2 = parsedArray2.getAsJsonArray(); final JsonArray asJsonArrayResult = new JsonArray(); if (asJsonArray1 != null && asJsonArray2 != null) { asJsonArrayResult.addAll(asJsonArray1); asJsonArrayResult.addAll(asJsonArray2); } result = asJsonArrayResult.toString(); } else { result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2; return populateResult(returnResult, new Exception(result)); } return populateResult(returnResult, result, null); }