List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString
public String toString()
From source file:org.activiti.app.rest.editor.ModelsResource.java
@RequestMapping(value = "/rest/models", method = RequestMethod.POST, produces = "application/json") public ModelRepresentation createModel(@RequestBody ModelRepresentation modelRepresentation) { modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", "")); ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(null, modelRepresentation.getModelType(), modelRepresentation.getKey()); if (modelKeyInfo.isKeyAlreadyExists()) { throw new BadRequestException("Provided model key already exists: " + modelRepresentation.getKey()); }/*ww w . j av a 2 s .c o m*/ String json = null; if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_FORM)) { try { json = objectMapper.writeValueAsString(new FormModel()); } catch (Exception e) { logger.error("Error creating form model", e); throw new InternalServerErrorException("Error creating form"); } } else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_DECISION_TABLE)) { try { DecisionTableDefinitionRepresentation decisionTableDefinition = new DecisionTableDefinitionRepresentation(); String decisionTableDefinitionKey = modelRepresentation.getName().replaceAll(" ", ""); decisionTableDefinition.setKey(decisionTableDefinitionKey); json = objectMapper.writeValueAsString(decisionTableDefinition); } catch (Exception e) { logger.error("Error creating decision table model", e); throw new InternalServerErrorException("Error creating decision table"); } } else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_APP)) { try { json = objectMapper.writeValueAsString(new AppDefinition()); } catch (Exception e) { logger.error("Error creating app definition", e); throw new InternalServerErrorException("Error creating app definition"); } } else { ObjectNode editorNode = objectMapper.createObjectNode(); editorNode.put("id", "canvas"); editorNode.put("resourceId", "canvas"); ObjectNode stencilSetNode = objectMapper.createObjectNode(); stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#"); editorNode.put("stencilset", stencilSetNode); ObjectNode propertiesNode = objectMapper.createObjectNode(); propertiesNode.put("process_id", modelRepresentation.getKey()); propertiesNode.put("name", modelRepresentation.getName()); if (StringUtils.isNotEmpty(modelRepresentation.getDescription())) { propertiesNode.put("documentation", modelRepresentation.getDescription()); } editorNode.put("properties", propertiesNode); ArrayNode childShapeArray = objectMapper.createArrayNode(); editorNode.put("childShapes", childShapeArray); ObjectNode childNode = objectMapper.createObjectNode(); childShapeArray.add(childNode); ObjectNode boundsNode = objectMapper.createObjectNode(); childNode.put("bounds", boundsNode); ObjectNode lowerRightNode = objectMapper.createObjectNode(); boundsNode.put("lowerRight", lowerRightNode); lowerRightNode.put("x", 130); lowerRightNode.put("y", 193); ObjectNode upperLeftNode = objectMapper.createObjectNode(); boundsNode.put("upperLeft", upperLeftNode); upperLeftNode.put("x", 100); upperLeftNode.put("y", 163); childNode.put("childShapes", objectMapper.createArrayNode()); childNode.put("dockers", objectMapper.createArrayNode()); childNode.put("outgoing", objectMapper.createArrayNode()); childNode.put("resourceId", "startEvent1"); ObjectNode stencilNode = objectMapper.createObjectNode(); childNode.put("stencil", stencilNode); stencilNode.put("id", "StartNoneEvent"); json = editorNode.toString(); } Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject()); return new ModelRepresentation(newModel); }
From source file:org.flowable.app.rest.editor.ModelsResource.java
@RequestMapping(value = "/rest/models", method = RequestMethod.POST, produces = "application/json") public ModelRepresentation createModel(@RequestBody ModelRepresentation modelRepresentation) { modelRepresentation.setKey(modelRepresentation.getKey().replaceAll(" ", "")); ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(null, modelRepresentation.getModelType(), modelRepresentation.getKey()); if (modelKeyInfo.isKeyAlreadyExists()) { throw new BadRequestException("Provided model key already exists: " + modelRepresentation.getKey()); }/*from w w w . jav a 2s . co m*/ String json = null; if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_FORM)) { try { json = objectMapper.writeValueAsString(new FormModel()); } catch (Exception e) { logger.error("Error creating form model", e); throw new InternalServerErrorException("Error creating form"); } } else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_DECISION_TABLE)) { try { DecisionTableDefinitionRepresentation decisionTableDefinition = new DecisionTableDefinitionRepresentation(); String decisionTableDefinitionKey = modelRepresentation.getName().replaceAll(" ", ""); decisionTableDefinition.setKey(decisionTableDefinitionKey); json = objectMapper.writeValueAsString(decisionTableDefinition); } catch (Exception e) { logger.error("Error creating decision table model", e); throw new InternalServerErrorException("Error creating decision table"); } } else if (modelRepresentation.getModelType() != null && modelRepresentation.getModelType().equals(AbstractModel.MODEL_TYPE_APP)) { try { json = objectMapper.writeValueAsString(new AppDefinition()); } catch (Exception e) { logger.error("Error creating app definition", e); throw new InternalServerErrorException("Error creating app definition"); } } else { ObjectNode editorNode = objectMapper.createObjectNode(); editorNode.put("id", "canvas"); editorNode.put("resourceId", "canvas"); ObjectNode stencilSetNode = objectMapper.createObjectNode(); stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#"); editorNode.set("stencilset", stencilSetNode); ObjectNode propertiesNode = objectMapper.createObjectNode(); propertiesNode.put("process_id", modelRepresentation.getKey()); propertiesNode.put("name", modelRepresentation.getName()); if (StringUtils.isNotEmpty(modelRepresentation.getDescription())) { propertiesNode.put("documentation", modelRepresentation.getDescription()); } editorNode.set("properties", propertiesNode); ArrayNode childShapeArray = objectMapper.createArrayNode(); editorNode.set("childShapes", childShapeArray); ObjectNode childNode = objectMapper.createObjectNode(); childShapeArray.add(childNode); ObjectNode boundsNode = objectMapper.createObjectNode(); childNode.set("bounds", boundsNode); ObjectNode lowerRightNode = objectMapper.createObjectNode(); boundsNode.set("lowerRight", lowerRightNode); lowerRightNode.put("x", 130); lowerRightNode.put("y", 193); ObjectNode upperLeftNode = objectMapper.createObjectNode(); boundsNode.set("upperLeft", upperLeftNode); upperLeftNode.put("x", 100); upperLeftNode.put("y", 163); childNode.set("childShapes", objectMapper.createArrayNode()); childNode.set("dockers", objectMapper.createArrayNode()); childNode.set("outgoing", objectMapper.createArrayNode()); childNode.put("resourceId", "startEvent1"); ObjectNode stencilNode = objectMapper.createObjectNode(); childNode.set("stencil", stencilNode); stencilNode.put("id", "StartNoneEvent"); json = editorNode.toString(); } Model newModel = modelService.createModel(modelRepresentation, json, SecurityUtils.getCurrentUserObject()); return new ModelRepresentation(newModel); }
From source file:controllers.CommentController.java
public Result getMentions(String email) { Long userId = userRepository.getUserIdByEmail(email); String username = userRepository.getUsernameByEmail(email); List<BigInteger> commentIds = mentionRepository.findAllCommentIdByUsername(username); ArrayNode commentArray = JsonNodeFactory.instance.arrayNode(); Long total_comment = 0L;/*from ww w .j a v a 2s . c o m*/ ObjectNode response = Json.newObject(); ObjectNode result = Json.newObject(); ObjectNode user = Json.newObject(); // User node if (userId == null) { user.put("user_id", -1); user.put("fullname", "Visitor"); user.put("is_logged_in", false); user.put("is_add_allowed", false); user.put("is_edit_allowed", false); } else { user.put("user_id", userId); user.put("fullname", username); user.put("is_logged_in", true); user.put("is_add_allowed", true); user.put("is_edit_allowed", true); } user.put("picture", "/assets/images/user_blank_picture.png"); for (BigInteger commentId : commentIds) { //Long commentId = ((BigInteger)commentIds[i]).longValue(); Comment comment = commentRepository.findCommentById(commentId.longValue()); ObjectNode oneComment = JsonNodeFactory.instance.objectNode(); oneComment.put("comment_id", comment.getCommentId()); oneComment.put("parent_id", 0); oneComment.put("in_reply_to", comment.getInReplyTo()); oneComment.put("element_id", comment.getElementId()); oneComment.put("created_by", comment.getCreatedBy()); oneComment.put("fullname", comment.getFullname()); oneComment.put("picture", comment.getPicture()); oneComment.put("posted_date", timeFormat.format(comment.getPostedDate())); oneComment.put("text", comment.getText()); oneComment.put("attachments", JsonNodeFactory.instance.arrayNode()); oneComment.put("childrens", JsonNodeFactory.instance.arrayNode()); commentArray.add(oneComment); total_comment++; } // result result.put("comments", commentArray); result.put("total_comment", total_comment); result.put("user", user); // response response.put("results", result); return ok(response.toString()); }
From source file:org.bimserver.geometry.GeometryRunner.java
@Override public void run() { Thread.currentThread().setName("GeometryRunner"); long start = System.nanoTime(); job.setStartNanos(start);/*from ww w .ja va 2s . c o m*/ try { HashMapVirtualObject next = objectProvider.next(); Query query = new Query("Double buffer query " + eClass.getName(), this.streamingGeometryGenerator.packageMetaData); QueryPart queryPart = query.createQueryPart(); while (next != null) { long oid = next.getOid(); queryPart.addOid(oid); if (eClass.isSuperTypeOf(next.eClass())) { if (originalQuery.getQueryParts().get(0).getOids().contains(oid)) { job.addObject(next.getOid(), next.eClass().getName()); } } next = objectProvider.next(); } objectProvider = new QueryObjectProvider(databaseSession, this.streamingGeometryGenerator.bimServer, query, Collections.singleton(queryContext.getRoid()), this.streamingGeometryGenerator.packageMetaData); StreamingSerializer serializer = ifcSerializerPlugin.createSerializer(new PluginConfiguration()); RenderEngine renderEngine = null; byte[] bytes = null; try { final Set<HashMapVirtualObject> objects = new LinkedHashSet<>(); ObjectProviderProxy proxy = new ObjectProviderProxy(objectProvider, new ObjectListener() { @Override public void newObject(HashMapVirtualObject next) { if (eClass.isSuperTypeOf(next.eClass())) { if (next.eGet( GeometryRunner.this.streamingGeometryGenerator.representationFeature) != null) { if (originalQuery.getQueryParts().get(0).getOids().contains(next.getOid())) { objects.add(next); } } } } }); serializer.init(proxy, null, null, this.streamingGeometryGenerator.bimServer.getPluginManager(), this.streamingGeometryGenerator.packageMetaData); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(serializer.getInputStream(), baos); bytes = baos.toByteArray(); InputStream in = new ByteArrayInputStream(bytes); Map<Integer, HashMapVirtualObject> notFoundObjects = new HashMap<>(); Set<Range> reusableGeometryData = new HashSet<>(); Map<Long, TemporaryGeometryData> productToData = new HashMap<>(); try { if (!objects.isEmpty()) { renderEngine = renderEnginePool.borrowObject(); try (RenderEngineModel renderEngineModel = renderEngine.openModel(in, bytes.length)) { renderEngineModel.setSettings(renderEngineSettings); renderEngineModel.setFilter(renderEngineFilter); try { renderEngineModel.generateGeneralGeometry(); } catch (RenderEngineException e) { if (e.getCause() instanceof java.io.EOFException) { if (objects.isEmpty() || eClass.getName().equals("IfcAnnotation")) { // SKIP } else { StreamingGeometryGenerator.LOGGER.error("Error in " + eClass.getName(), e); } } } OidConvertingSerializer oidConvertingSerializer = (OidConvertingSerializer) serializer; Map<Long, Integer> oidToEid = oidConvertingSerializer.getOidToEid(); Map<Long, DebuggingInfo> debuggingInfo = new HashMap<>(); for (HashMapVirtualObject ifcProduct : objects) { if (!this.streamingGeometryGenerator.running) { return; } Integer expressId = oidToEid.get(ifcProduct.getOid()); try { RenderEngineInstance renderEngineInstance = renderEngineModel .getInstanceFromExpressId(expressId); RenderEngineGeometry geometry = renderEngineInstance.generateGeometry(); boolean translate = true; // if (geometry == null || // geometry.getIndices().length == 0) { // LOGGER.info("Running again..."); // renderEngineModel.setFilter(renderEngineFilterTransformed); // geometry = // renderEngineInstance.generateGeometry(); // if (geometry != null) { // translate = false; // } // renderEngineModel.setFilter(renderEngineFilter); // } if (geometry != null && geometry.getNrIndices() > 0) { HashMapVirtualObject geometryInfo = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryInfo()); HashMapWrappedVirtualObject bounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getBounds()); HashMapWrappedVirtualObject minBounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); HashMapWrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); minBounds.set("x", Double.POSITIVE_INFINITY); minBounds.set("y", Double.POSITIVE_INFINITY); minBounds.set("z", Double.POSITIVE_INFINITY); maxBounds.set("x", -Double.POSITIVE_INFINITY); maxBounds.set("y", -Double.POSITIVE_INFINITY); maxBounds.set("z", -Double.POSITIVE_INFINITY); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductOid(), ifcProduct.getOid()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Bounds(), bounds); bounds.setAttribute(GeometryPackage.eINSTANCE.getBounds_Min(), minBounds); bounds.setAttribute(GeometryPackage.eINSTANCE.getBounds_Max(), maxBounds); HashMapWrappedVirtualObject boundsUntransformed = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getBounds()); WrappedVirtualObject minBoundsUntranslated = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject maxBoundsUntranslated = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); minBoundsUntranslated.set("x", Double.POSITIVE_INFINITY); minBoundsUntranslated.set("y", Double.POSITIVE_INFINITY); minBoundsUntranslated.set("z", Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("x", -Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("y", -Double.POSITIVE_INFINITY); maxBoundsUntranslated.set("z", -Double.POSITIVE_INFINITY); boundsUntransformed.setAttribute(GeometryPackage.eINSTANCE.getBounds_Min(), minBoundsUntranslated); boundsUntransformed.setAttribute(GeometryPackage.eINSTANCE.getBounds_Max(), maxBoundsUntranslated); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_BoundsUntransformed(), boundsUntransformed); double volume = 0; ObjectNode additionalData = renderEngineInstance.getAdditionalData(); if (streamingGeometryGenerator.isCalculateQuantities()) { if (additionalData != null) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_AdditionalData(), additionalData.toString()); if (additionalData.has("TOTAL_SURFACE_AREA")) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Area(), additionalData.get("TOTAL_SURFACE_AREA").asDouble()); } if (additionalData.has("TOTAL_SHAPE_VOLUME")) { volume = additionalData.get("TOTAL_SHAPE_VOLUME").asDouble(); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Volume(), volume); } } } HashMapVirtualObject geometryData = new HashMapVirtualObject(queryContext, GeometryPackage.eINSTANCE.getGeometryData()); geometryData.set("type", databaseSession.getCid(eClass)); ByteBuffer indices = geometry.getIndices(); IntBuffer indicesAsInt = indices.order(ByteOrder.LITTLE_ENDIAN) .asIntBuffer(); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_Reused(), 1); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_Indices(), createBuffer(queryContext, indices)); geometryData.set("nrIndices", indicesAsInt.capacity()); ByteBuffer vertices = geometry.getVertices(); DoubleBuffer verticesAsDouble = vertices.order(ByteOrder.LITTLE_ENDIAN) .asDoubleBuffer(); geometryData.set("nrVertices", verticesAsDouble.capacity()); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_Vertices(), createBuffer(queryContext, vertices)); ByteBuffer normals = geometry.getNormals(); FloatBuffer normalsAsFloat = normals.order(ByteOrder.LITTLE_ENDIAN) .asFloatBuffer(); geometryData.set("nrNormals", normalsAsFloat.capacity()); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_Normals(), createBuffer(queryContext, normals)); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), indicesAsInt.capacity() / 3); job.setTrianglesGenerated(indicesAsInt.capacity() / 3); job.getReport().incrementTriangles(indicesAsInt.capacity() / 3); streamingGeometryGenerator.cacheGeometryData(geometryData, vertices); ColorMap colorMap = new ColorMap(); ByteBuffer colors = ByteBuffer.wrap(new byte[0]); IntBuffer materialIndices = geometry.getMaterialIndices() .order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); if (materialIndices != null && materialIndices.capacity() > 0) { FloatBuffer materialsAsFloat = geometry.getMaterials() .order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer(); boolean hasMaterial = false; colors = ByteBuffer.allocate((verticesAsDouble.capacity() / 3) * 4); double[] triangle = new double[9]; for (int i = 0; i < materialIndices.capacity(); ++i) { int c = materialIndices.get(i); if (c > -1) { Color4f color = new Color4f(); for (int l = 0; l < 4; ++l) { float val = fixColor(materialsAsFloat.get(4 * c + l)); color.set(l, val); } for (int j = 0; j < 3; ++j) { int k = indicesAsInt.get(i * 3 + j); triangle[j * 3 + 0] = verticesAsDouble.get(3 * k); triangle[j * 3 + 1] = verticesAsDouble.get(3 * k + 1); triangle[j * 3 + 2] = verticesAsDouble.get(3 * k + 2); hasMaterial = true; for (int l = 0; l < 4; ++l) { float val = fixColor(materialsAsFloat.get(4 * c + l)); colors.put(4 * k + l, UnsignedBytes.checkedCast((int) (val * 255))); } } colorMap.addTriangle(triangle, color); } } if (hasMaterial) { ColorMap2 colorMap2 = new ColorMap2(); byte[] colorB = new byte[4]; for (int i = 0; i < colors.capacity(); i += 4) { colors.get(colorB); colorMap2.addColor(colorB); } HashMapVirtualObject colorPack = new HashMapVirtualObject( queryContext, GeometryPackage.eINSTANCE.getColorPack()); colorPack.set(GeometryPackage.eINSTANCE.getColorPack_Data(), colorMap2.toByteArray()); colorPack.save(); geometryData.setReference( GeometryPackage.eINSTANCE.getGeometryData_ColorPack(), colorPack.getOid(), 0); } if (colorMap.usedColors() == 0) { } else if (colorMap.usedColors() == 1) { WrappedVirtualObject color = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector4f()); Color4f firstColor = colorMap.getFirstColor(); color.set("x", firstColor.getR()); color.set("y", firstColor.getG()); color.set("z", firstColor.getB()); color.set("w", firstColor.getA()); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_Color(), color); // This tells the code further on to not store this geometry, as it can be easily generated hasMaterial = false; } else { Color4f mostUsed = colorMap.getMostUsedColor(); WrappedVirtualObject color = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector4f()); color.set("x", mostUsed.getR()); color.set("y", mostUsed.getG()); color.set("z", mostUsed.getB()); color.set("w", mostUsed.getA()); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_MostUsedColor(), color); } if (hasMaterial) { geometryData.set("nrColors", colors.capacity()); geometryData.set( GeometryPackage.eINSTANCE.getGeometryData_ColorsQuantized(), createBuffer(queryContext, colors)); } else { geometryData.set("nrColors", 0); } } else { geometryData.set("nrColors", 0); } boolean hasTransparency = colorMap.hasTransparency(); double[] productTranformationMatrix = new double[16]; if (translate && renderEngineInstance.getTransformationMatrix() != null) { productTranformationMatrix = renderEngineInstance .getTransformationMatrix(); } else { Matrix.setIdentityM(productTranformationMatrix, 0); } geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_NrColors(), colors.capacity()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_NrVertices(), verticesAsDouble.capacity()); geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), geometryData.getOid(), 0); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_HasTransparency(), hasTransparency); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_HasTransparency(), hasTransparency); long size = this.streamingGeometryGenerator.getSize(geometryData); for (int i = 0; i < indicesAsInt.capacity(); i++) { this.streamingGeometryGenerator.processExtends(minBounds, maxBounds, productTranformationMatrix, verticesAsDouble, indicesAsInt.get(i) * 3, generateGeometryResult); this.streamingGeometryGenerator.processExtendsUntranslated(geometryInfo, verticesAsDouble, indicesAsInt.get(i) * 3, generateGeometryResult); } HashMapWrappedVirtualObject boundsUntransformedMm = createMmBounds( geometryInfo, boundsUntransformed, generateGeometryResult.getMultiplierToMm()); geometryInfo.set("boundsUntransformedMm", boundsUntransformedMm); HashMapWrappedVirtualObject boundsMm = createMmBounds(geometryInfo, bounds, generateGeometryResult.getMultiplierToMm()); geometryInfo.set("boundsMm", boundsMm); ByteBuffer normalsQuantized = quantizeNormals(normalsAsFloat); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_NormalsQuantized(), createBuffer(queryContext, normalsQuantized)); HashMapWrappedVirtualObject geometryDataBounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getBounds()); WrappedVirtualObject geometryDataBoundsMin = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject geometryDataBoundsMax = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); geometryDataBoundsMin.set("x", ((HashMapWrappedVirtualObject) boundsMm.get("min")).get("x")); geometryDataBoundsMin.set("y", ((HashMapWrappedVirtualObject) boundsMm.get("min")).get("y")); geometryDataBoundsMin.set("z", ((HashMapWrappedVirtualObject) boundsMm.get("min")).get("z")); geometryDataBoundsMax.set("x", ((HashMapWrappedVirtualObject) boundsMm.get("max")).get("x")); geometryDataBoundsMax.set("y", ((HashMapWrappedVirtualObject) boundsMm.get("max")).get("y")); geometryDataBoundsMax.set("z", ((HashMapWrappedVirtualObject) boundsMm.get("max")).get("z")); geometryDataBounds.setAttribute(GeometryPackage.eINSTANCE.getBounds_Min(), geometryDataBoundsMin); geometryDataBounds.setAttribute(GeometryPackage.eINSTANCE.getBounds_Max(), geometryDataBoundsMax); geometryData.setAttribute( GeometryPackage.eINSTANCE.getGeometryData_BoundsMm(), geometryDataBounds); if (volume == 0) { volume = getVolumeFromBounds(boundsUntransformed); } float nrTriangles = geometry.getNrIndices() / 3; Density density = new Density(eClass.getName(), (float) volume, getBiggestFaceFromBounds(boundsUntransformedMm), (long) nrTriangles, geometryInfo.getOid()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Density(), density.getDensityValue()); generateGeometryResult.addDensity(density); double[] mibu = new double[] { (double) minBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_X()), (double) minBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_Y()), (double) minBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_Z()), 1d }; double[] mabu = new double[] { (double) maxBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_X()), (double) maxBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_Y()), (double) maxBoundsUntranslated .eGet(GeometryPackage.eINSTANCE.getVector3f_Z()), 1d }; if (reuseGeometry) { /* TODO It still happens that geometry that should be reused is not reused, one of the reasons is still concurrency: * - When the same geometry is processed concurrently they could both do the hash check at a time when there is no cached version, then they both think it's non-reused geometry */ int hash = this.streamingGeometryGenerator.hash(indices, vertices, normals, colors); int firstIndex = indicesAsInt.get(0); int lastIndex = indicesAsInt.get(indicesAsInt.capacity() - 1); double[] firstVertex = new double[] { verticesAsDouble.get(firstIndex), verticesAsDouble.get(firstIndex + 1), verticesAsDouble.get(firstIndex + 2) }; double[] lastVertex = new double[] { verticesAsDouble.get(lastIndex * 3), verticesAsDouble.get(lastIndex * 3 + 1), verticesAsDouble.get(lastIndex * 3 + 2) }; Range range = new Range(firstVertex, lastVertex); Long referenceOid = this.streamingGeometryGenerator.hashes.get(hash); if (referenceOid != null) { HashMapVirtualObject referencedData = databaseSession .getFromCache(referenceOid); if (referencedData == null) { LOGGER.error("Object not found in cache: " + referenceOid + " (hash: " + hash + ")"); } synchronized (referencedData) { Integer currentValue = (Integer) referencedData.get("reused"); referencedData.set("reused", currentValue + 1); } HashMapWrappedVirtualObject dataBounds = (HashMapWrappedVirtualObject) referencedData .get("boundsMm"); extendBounds(boundsMm, dataBounds); referencedData.saveOverwrite(); geometryInfo.setReference( GeometryPackage.eINSTANCE.getGeometryInfo_Data(), referenceOid, 0); this.streamingGeometryGenerator.bytesSavedByHash.addAndGet(size); } else if (geometryReused) { // This is true when this geometry is part of a mapped item mapping (and used more than once) boolean found = false; // for (Range r : // reusableGeometryData) { // if (r.isSimilar(range)) { // geometryInfo.setReference(GeometryPackage.eINSTANCE.getGeometryInfo_Data(), // r.getGeometryDataOid(), 0); // float[] offset = // r.getOffset(range); // ProductDef productDef = // map.get(ifcProduct.getOid()); // double[] mappedItemMatrix = // null; // if (productDef != null && // productDef.getMatrix() != // null) { // mappedItemMatrix = // productDef.getMatrix(); // } else { // Matrix.translateM(mappedItemMatrix, // 0, offset[0], offset[1], // offset[2]); // } // double[] result = new // double[16]; // Matrix.multiplyMM(result, 0, // mappedItemMatrix, 0, // productTranformationMatrix, // 0); // setTransformationMatrix(geometryInfo, // result); // Overwritten? // bytesSavedByTransformation.addAndGet(size); // found = true; // break; // } // } if (!found) { range.setGeometryDataOid(geometryData.getOid()); reusableGeometryData.add(range); if (streamingGeometryGenerator.isCalculateQuantities()) { if (additionalData != null) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE .getGeometryInfo_AdditionalData(), additionalData.toString()); if (additionalData.has("SURFACE_AREA_ALONG_Z")) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE .getGeometryInfo_Area(), additionalData.get("SURFACE_AREA_ALONG_Z") .asDouble()); } if (additionalData.has("TOTAL_SHAPE_VOLUME")) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE .getGeometryInfo_Volume(), additionalData.get("TOTAL_SHAPE_VOLUME") .asDouble()); } } } geometryInfo.setAttribute( GeometryPackage.eINSTANCE .getGeometryInfo_PrimitiveCount(), indicesAsInt.capacity() / 3); productToData.put(ifcProduct.getOid(), new TemporaryGeometryData(geometryData.getOid(), additionalData, indicesAsInt.capacity() / 3, size, mibu, mabu, indicesAsInt, verticesAsDouble, hasTransparency, colors.capacity())); geometryData.save(); databaseSession.cache((HashMapVirtualObject) geometryData); } } else { // if (sizes.containsKey(size) // && sizes.get(size).eClass() // == ifcProduct.eClass()) { // LOGGER.info("More reuse might // be possible " + size + " " + // ifcProduct.eClass().getName() // + ":" + ifcProduct.getOid() + // " / " + // sizes.get(size).eClass().getName() // + ":" + // sizes.get(size).getOid()); // } // if (geometryReused) { // range.setGeometryDataOid(geometryData.getOid()); // reusableGeometryData.add(range); // productToData.put(ifcProduct.getOid(), new TemporaryGeometryData(geometryData.getOid(), renderEngineInstance.getArea(), renderEngineInstance.getVolume(), indices.length / 3, size, mibu, mabu, indices, vertices)); // } // TODO else?? // So reuse is on, the data was not found by hash, and this item is not in a mapped item // By saving it before putting it in the cache/hashmap, we make sure we won't get a BimserverConcurrentModificationException geometryData.save(); // TODO Why?? databaseSession.cache((HashMapVirtualObject) geometryData); this.streamingGeometryGenerator.hashes.put(hash, geometryData.getOid()); // sizes.put(size, ifcProduct); } } else { geometryData.save(); databaseSession.cache((HashMapVirtualObject) geometryData); } this.streamingGeometryGenerator.setTransformationMatrix(geometryInfo, productTranformationMatrix); debuggingInfo.put(ifcProduct.getOid(), new DebuggingInfo(productTranformationMatrix, indices.asIntBuffer(), vertices.asFloatBuffer())); geometryInfo.save(); this.streamingGeometryGenerator.totalBytes.addAndGet(size); ifcProduct.setReference(this.streamingGeometryGenerator.geometryFeature, geometryInfo.getOid(), 0); ifcProduct.saveOverwrite(); // Doing a sync here because probably // writing large amounts of data, and db // only syncs every 100.000 writes by // default // databaseSession.getKeyValueStore().sync(); } else { // TODO } } catch (EntityNotFoundException e) { // e.printStackTrace(); // As soon as we find a representation that // is not Curve2D, then we should show a // "INFO" message in the log to indicate // there could be something wrong boolean ignoreNotFound = eClass.getName().equals("IfcAnnotation"); // for (Object rep : representations) { // if (rep instanceof // IfcShapeRepresentation) { // IfcShapeRepresentation // ifcShapeRepresentation = // (IfcShapeRepresentation)rep; // if // (!"Curve2D".equals(ifcShapeRepresentation.getRepresentationType())) // { // ignoreNotFound = false; // } // } // } if (!ignoreNotFound) { // LOGGER.warn("Entity not found " + // ifcProduct.eClass().getName() + " " + // (expressId) + "/" + // ifcProduct.getOid()); notFoundObjects.put(expressId, ifcProduct); } } catch (BimserverDatabaseException | RenderEngineException e) { StreamingGeometryGenerator.LOGGER.error("", e); } } if (geometryReused && map != null) { // We pick the first product and use that product to try and get the original data long firstKey = map.keySet().iterator().next(); ProductDef masterProductDef = map.get(firstKey); for (long key : map.keySet()) { if (key != firstKey) { ProductDef productDef = map.get(key); HashMapVirtualObject ifcProduct = productDef.getObject(); TemporaryGeometryData masterGeometryData = productToData .get(productDef.getMasterOid()); if (masterGeometryData != null) { HashMapVirtualObject geometryInfo = new HashMapVirtualObject( queryContext, GeometryPackage.eINSTANCE.getGeometryInfo()); HashMapWrappedVirtualObject bounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getBounds()); HashMapWrappedVirtualObject minBounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); HashMapWrappedVirtualObject maxBounds = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Bounds(), bounds); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_HasTransparency(), masterGeometryData.hasTransparancy()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_NrColors(), masterGeometryData.getNrColors()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_NrVertices(), masterGeometryData.getNrVertices()); bounds.set("min", minBounds); bounds.set("max", maxBounds); minBounds.set("x", Double.POSITIVE_INFINITY); minBounds.set("y", Double.POSITIVE_INFINITY); minBounds.set("z", Double.POSITIVE_INFINITY); maxBounds.set("x", -Double.POSITIVE_INFINITY); maxBounds.set("y", -Double.POSITIVE_INFINITY); maxBounds.set("z", -Double.POSITIVE_INFINITY); double[] mibu = masterGeometryData.getMibu(); double[] mabu = masterGeometryData.getMabu(); HashMapWrappedVirtualObject boundsUntransformed = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getBounds()); WrappedVirtualObject minBoundsUntransformed = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); WrappedVirtualObject maxBoundsUntransformed = new HashMapWrappedVirtualObject( GeometryPackage.eINSTANCE.getVector3f()); minBoundsUntransformed.set("x", mibu[0]); minBoundsUntransformed.set("y", mibu[1]); minBoundsUntransformed.set("z", mibu[2]); maxBoundsUntransformed.set("x", mabu[0]); maxBoundsUntransformed.set("y", mabu[1]); maxBoundsUntransformed.set("z", mabu[2]); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_IfcProductOid(), ifcProduct.getOid()); boundsUntransformed.setAttribute( GeometryPackage.eINSTANCE.getBounds_Min(), minBoundsUntransformed); boundsUntransformed.setAttribute( GeometryPackage.eINSTANCE.getBounds_Max(), maxBoundsUntransformed); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_BoundsUntransformed(), boundsUntransformed); ObjectNode additionalData = masterGeometryData.getAdditionalData(); double volume = 0; if (additionalData != null) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_AdditionalData(), additionalData.toString()); if (additionalData.has("SURFACE_AREA_ALONG_Z")) { geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Area(), additionalData.get("SURFACE_AREA_ALONG_Z").asDouble()); } if (additionalData.has("TOTAL_SHAPE_VOLUME")) { volume = additionalData.get("TOTAL_SHAPE_VOLUME").asDouble(); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Volume(), volume); } } geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_PrimitiveCount(), masterGeometryData.getNrPrimitives()); job.getReport() .incrementTriangles(masterGeometryData.getNrPrimitives()); this.streamingGeometryGenerator.bytesSavedByMapping .addAndGet(masterGeometryData.getSize()); this.streamingGeometryGenerator.totalBytes .addAndGet(masterGeometryData.getSize()); // First, invert the master's mapping matrix double[] inverted = Matrix.identity(); if (!Matrix.invertM(inverted, 0, masterProductDef.getMappingMatrix(), 0)) { LOGGER.info( "No inverse, this should not be able to happen at this time, please report"); continue; } double[] finalMatrix = Matrix.identity(); double[] totalTranformationMatrix = Matrix.identity(); // Apply the mapping matrix of the product Matrix.multiplyMM(finalMatrix, 0, productDef.getMappingMatrix(), 0, inverted, 0); // Apply the product matrix of the product Matrix.multiplyMM(totalTranformationMatrix, 0, productDef.getProductMatrix(), 0, finalMatrix, 0); if (geometryGenerationDebugger != null) { // if (debuggingInfo.containsKey(ifcProduct.getOid())) { // DebuggingInfo debuggingInfo2 = debuggingInfo.get(ifcProduct.getOid()); // DebuggingInfo debuggingInfo3 = debuggingInfo.get(productDef.getMasterOid()); // // if (debuggingInfo2.getIndices().length != debuggingInfo3.getIndices().length) { // LOGGER.error("Different sizes for indices, weird..."); // LOGGER.error(ifcProduct.getOid() + " / " + productDef.getMasterOid()); // } else { // for (int i=0; i<debuggingInfo2.getIndices().length; i++) { // int index = debuggingInfo2.getIndices()[i]; // float[] vertex = new float[]{debuggingInfo2.getVertices()[index * 3], debuggingInfo2.getVertices()[index * 3 + 1], debuggingInfo2.getVertices()[index * 3 + 2], 1}; // float[] transformedOriginal = new float[4]; // Matrix.multiplyMV(transformedOriginal, 0, debuggingInfo2.getProductTranformationMatrix(), 0, vertex, 0); // float[] transformedNew = new float[4]; // int index2 = debuggingInfo3.getIndices()[i]; // float[] vertex2 = new float[]{debuggingInfo3.getVertices()[index2 * 3], debuggingInfo3.getVertices()[index2 * 3 + 1], debuggingInfo3.getVertices()[index2 * 3 + 2], 1}; // Matrix.multiplyMV(transformedNew, 0, totalTranformationMatrix, 0, vertex2, 0); // // // TODO margin should depend on bb of complete model // if (!almostTheSame((String)ifcProduct.get("GlobalId"), transformedNew, transformedOriginal, 0.05F)) { // geometryGenerationDebugger.transformedVertexNotMatching(ifcProduct, transformedOriginal, transformedNew, debuggingInfo2.getProductTranformationMatrix(), totalTranformationMatrix); // } // } // } // almostTheSame((String)ifcProduct.get("GlobalId"), debuggingInfo2.getProductTranformationMatrix(), totalTranformationMatrix, 0.01D); // } } IntBuffer indices = masterGeometryData.getIndices(); for (int i = 0; i < indices.capacity(); i++) { this.streamingGeometryGenerator.processExtends(minBounds, maxBounds, totalTranformationMatrix, masterGeometryData.getVertices(), indices.get(i) * 3, generateGeometryResult); } HashMapWrappedVirtualObject boundsUntransformedMm = createMmBounds( geometryInfo, boundsUntransformed, generateGeometryResult.getMultiplierToMm()); geometryInfo.set("boundsUntransformedMm", boundsUntransformedMm); HashMapWrappedVirtualObject boundsMm = createMmBounds(geometryInfo, bounds, generateGeometryResult.getMultiplierToMm()); geometryInfo.set("boundsMm", boundsMm); float nrTriangles = masterGeometryData.getNrPrimitives(); Density density = new Density(eClass.getName(), (float) volume, getBiggestFaceFromBounds(boundsUntransformedMm), (long) nrTriangles, geometryInfo.getOid()); geometryInfo.setAttribute( GeometryPackage.eINSTANCE.getGeometryInfo_Density(), density.getDensityValue()); generateGeometryResult.addDensity(density); HashMapVirtualObject referencedData = databaseSession .getFromCache(masterGeometryData.getOid()); Integer currentValue = (Integer) referencedData.get("reused"); referencedData.set("reused", currentValue + 1); HashMapWrappedVirtualObject dataBounds = (HashMapWrappedVirtualObject) referencedData .get("boundsMm"); extendBounds(boundsMm, dataBounds); // TODO this keeping track of the amount of reuse, takes it's toll on memory usage. Basically all geometry ends up in memory by the time the Geometry generation is done // We should try to see whether we can use BDB's mechanism to do partial retrievals/updates of a records here, because we only need to update just one value // Another, simpler option would be to introduce another layer between GeometryInfo and GeometryData, so we don't have to cache the actual data (vertices etc... the bulk) // In that case however the BinarySerializer would increase in complexity // This seems to have been partially solved now since GeometryData does not contain the bulk of the data anymore (the byte[]s are now in "Buffer"). referencedData.saveOverwrite(); geometryInfo.setReference( GeometryPackage.eINSTANCE.getGeometryInfo_Data(), masterGeometryData.getOid(), 0); // for (int i = 0; i < // indices.length; i++) { // processExtends(geometryInfo, // productTranformationMatrix, // vertices, indices[i] * 3, // generateGeometryResult); // processExtendsUntranslated(geometryInfo, // vertices, indices[i] * 3, // generateGeometryResult); // } // calculateObb(geometryInfo, // productTranformationMatrix, // indices, vertices, // generateGeometryResult); this.streamingGeometryGenerator.setTransformationMatrix(geometryInfo, totalTranformationMatrix); geometryInfo.save(); // totalBytes.addAndGet(size); ifcProduct.setReference(this.streamingGeometryGenerator.geometryFeature, geometryInfo.getOid(), 0); ifcProduct.saveOverwrite(); } } } } } } } finally { if (renderEngine != null) { renderEnginePool.returnObject(renderEngine); } try { if (!notFoundObjects.isEmpty()) { writeDebugFile(bytes, false, notFoundObjects); StringBuilder sb = new StringBuilder(); for (Integer key : notFoundObjects.keySet()) { sb.append(key + " (" + notFoundObjects.get(key).getOid() + ")"); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); job.setException(new Exception("Missing objects in model (" + sb.toString() + ")")); } else if (writeOutputFiles) { writeDebugFile(bytes, false, null); } in.close(); } catch (Throwable e) { } finally { } this.streamingGeometryGenerator.jobsDone.incrementAndGet(); this.streamingGeometryGenerator.updateProgress(); } } catch (Exception e) { StreamingGeometryGenerator.LOGGER.error("", e); writeDebugFile(bytes, true, null); job.setException(e); // LOGGER.error("Original query: " + originalQuery, e); } } catch (Exception e) { StreamingGeometryGenerator.LOGGER.error("", e); // LOGGER.error("Original query: " + originalQuery, e); } long end = System.nanoTime(); job.setEndNanos(end); }
From source file:com.ikanow.aleph2.graph.titan.utils.TestTitanGraphBuildingUtils.java
@Test public void test_validateMergedElement() { // Graph schema (currently ignored) final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class).done().get(); // Valid object: final ObjectNode base_test = _mapper.createObjectNode(); base_test.put(GraphAnnotationBean.label, "test_label"); base_test.put(GraphAnnotationBean.type, GraphAnnotationBean.ElementType.vertex.toString()); // 1) Check it validates: {// w w w . j av a2s .c o m final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(base_test, graph_schema); assertTrue("Should be valid: " + ret_val.validation(fail -> fail.message(), success -> ""), ret_val.isSuccess()); assertEquals("Should return the inserted object: " + ret_val.success() + " vs " + base_test, base_test.toString(), ret_val.success().toString()); } // 2) Couple of other valid incarnations: { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.label, "test_label"); test.put(GraphAnnotationBean.type, GraphAnnotationBean.ElementType.edge.toString()); test.set(GraphAnnotationBean.properties, _mapper.createObjectNode()); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertTrue("Should be valid: " + ret_val.validation(fail -> fail.message(), success -> ""), ret_val.isSuccess()); assertEquals("Should return the inserted object: " + ret_val.success() + " vs " + test, test.toString(), ret_val.success().toString()); } // 3.1) No type: { final ObjectNode test = base_test.deepCopy(); test.remove(GraphAnnotationBean.type); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 3.2) Type not a string { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.type, 4L); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 3.3) Type the wrong string { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.type, "banana"); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 4.1) No label: { final ObjectNode test = base_test.deepCopy(); test.remove(GraphAnnotationBean.label); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 4.2) label not a string { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.label, 4L); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 5) Properties not an object { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.properties, 4L); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateMergedElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } }
From source file:com.marklogic.client.impl.CombinedQueryBuilderImpl.java
@SuppressWarnings("rawtypes") private String makeJSONCombinedQuery(CombinedQueryDefinitionImpl qdef) { try {// w w w . j av a2 s.co m ObjectMapper mapper = new ObjectMapper().configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) .configure(Feature.ALLOW_SINGLE_QUOTES, true); ObjectNode rootNode = mapper.createObjectNode(); ObjectNode searchNode = mapper.createObjectNode(); rootNode.replace("search", searchNode); if (qdef.sparql != null) searchNode.put("sparql", qdef.sparql); if (qdef.qtext != null) searchNode.put("qtext", qdef.qtext); if (qdef.options != null) { HandleImplementation optionsBase = HandleAccessor.as(qdef.options); if (Format.JSON != optionsBase.getFormat()) { throw new IllegalStateException("Cannot combine a JSON-format structured " + "query with " + optionsBase.getFormat() + "-format options"); } String json = HandleAccessor.contentAsString(qdef.options); JsonNode optionsNode = mapper.readTree(json); searchNode.replace("options", optionsNode.get("options")); } if (qdef.rawQuery != null) { String json = HandleAccessor.contentAsString(qdef.rawQuery.getHandle()); JsonNode rawQueryNode = mapper.readTree(json); JsonNode queryNode = rawQueryNode.get("query"); if (queryNode == null) queryNode = rawQueryNode.path("search").get("query"); if (queryNode != null) searchNode.replace("query", queryNode); if (qdef.options == null) { JsonNode optionsNode = rawQueryNode.path("search").get("options"); if (optionsNode != null) searchNode.replace("options", optionsNode); } if (qdef.qtext == null) { JsonNode qtextNode = rawQueryNode.path("search").get("qtext"); if (qtextNode != null) searchNode.replace("qtext", qtextNode); } if (qdef.sparql == null) { JsonNode sparqlNode = rawQueryNode.path("search").get("sparql"); if (sparqlNode != null) searchNode.replace("sparql", sparqlNode); } } return rootNode.toString(); } catch (Exception e) { throw new MarkLogicIOException(e); } }
From source file:com.ikanow.aleph2.graph.titan.utils.TestTitanGraphBuildingUtils.java
@Test public void test_validateUserElement() { // Graph schema final GraphSchemaBean graph_schema = BeanTemplateUtils.build(GraphSchemaBean.class) .with(GraphSchemaBean::deduplication_fields, Arrays.asList(GraphAnnotationBean.name, GraphAnnotationBean.type)) .done().get();//from w w w . j a v a2s.c om // Valid object: final ObjectNode base_test = _mapper.createObjectNode(); base_test.put(GraphAnnotationBean.label, "test_label"); base_test.put(GraphAnnotationBean.type, GraphAnnotationBean.ElementType.vertex.toString()); base_test.put(GraphAnnotationBean.id, 0L); // 1.1) Check it validates: { final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(base_test, graph_schema); assertTrue("Should be valid: " + ret_val.validation(fail -> fail.message(), success -> ""), ret_val.isSuccess()); assertEquals("Should return the inserted object: " + ret_val.success() + " vs " + base_test, base_test.toString(), ret_val.success().toString()); } // 1.2) Other valid incarnations { final ObjectNode test = base_test.deepCopy(); test.set(GraphAnnotationBean.id, _mapper.createObjectNode().put("name", "a").put("type", "b")); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertEquals("Should return the inserted object: " + ret_val.success() + " vs " + test, test.toString(), ret_val.success().toString()); } //(edge) { final ObjectNode test = base_test.deepCopy(); test.remove(GraphAnnotationBean.id); test.put(GraphAnnotationBean.type, GraphAnnotationBean.ElementType.edge.toString()); test.set(GraphAnnotationBean.inV, _mapper.createObjectNode().put("name", "a").put("type", "b")); test.put(GraphAnnotationBean.outV, 0L); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertEquals("Should return the inserted object: " + ret_val.success() + " vs " + test, test.toString(), ret_val.success().toString()); } // 2) Check fails out if the "validateMergedElement" bit fails { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.type, "rabbit"); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 3.1) id not present { final ObjectNode test = base_test.deepCopy(); test.remove(GraphAnnotationBean.id); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 3.2) id not a long/object { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.id, 1.5); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } // 3.3) id is an object but doesn't match the dedup fields { final ObjectNode test = base_test.deepCopy(); test.put(GraphAnnotationBean.type, GraphAnnotationBean.ElementType.edge.toString()); test.set(GraphAnnotationBean.inV, _mapper.createObjectNode().put("name", "a")); test.put(GraphAnnotationBean.outV, 0L); final Validation<BasicMessageBean, ObjectNode> ret_val = TitanGraphBuildingUtils .validateUserElement(test, graph_schema); assertFalse("Should be invalid", ret_val.isSuccess()); } }
From source file:com.googlecode.jsonrpc4j.JsonRpcClient.java
/** * Writes a request./* w w w. j av a 2 s. com*/ * @param methodName the method name * @param arguments the arguments * @param ops the stream * @param id the optional id * @throws IOException on error */ private void internalWriteRequest(String methodName, Object arguments, OutputStream ops, String id) throws IOException { // create the request ObjectNode request = mapper.createObjectNode(); // add id if (id != null) { request.put("id", id); } // add protocol and method request.put("jsonrpc", JSON_RPC_VERSION); request.put("method", methodName); // object array args if (arguments != null && arguments.getClass().isArray()) { Object[] args = Object[].class.cast(arguments); if (args.length > 0) { // serialize every param for itself so jackson can determine // right serializer ArrayNode paramsNode = new ArrayNode(mapper.getNodeFactory()); for (Object arg : args) { JsonNode argNode = mapper.valueToTree(arg); paramsNode.add(argNode); } request.put("params", paramsNode); } // collection args } else if (arguments != null && Collection.class.isInstance(arguments)) { Collection<?> args = Collection.class.cast(arguments); if (!args.isEmpty()) { // serialize every param for itself so jackson can determine // right serializer ArrayNode paramsNode = new ArrayNode(mapper.getNodeFactory()); for (Object arg : args) { JsonNode argNode = mapper.valueToTree(arg); paramsNode.add(argNode); } request.put("params", paramsNode); } // map args } else if (arguments != null && Map.class.isInstance(arguments)) { if (!Map.class.cast(arguments).isEmpty()) { request.put("params", mapper.valueToTree(arguments)); } // other args } else if (arguments != null) { request.put("params", mapper.valueToTree(arguments)); } // show to listener if (this.requestListener != null) { this.requestListener.onBeforeRequestSent(this, request); } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "JSON-PRC Request: " + request.toString()); } // post the json data; writeAndFlushValue(ops, request); }
From source file:com.ikanow.aleph2.graph.titan.utils.TestTitanGraphBuildingUtils.java
@Test public void test_insertIntoObjectNode() { final TitanGraph titan = getSimpleTitanGraph(); final TitanTransaction tx = titan.buildTransaction().start(); Vertex v = tx.addVertex("test"); v.property("long", 3L); v.property("integer", 3); v.property("boolean", true); v.property("double", 3.1); v.property("str", "string"); final ObjectNode graphson = _mapper.createObjectNode(); TitanGraphBuildingUtils.insertIntoObjectNode("long", v.property("long"), graphson); TitanGraphBuildingUtils.insertIntoObjectNode("integer", v.property("integer"), graphson); TitanGraphBuildingUtils.insertIntoObjectNode("boolean", v.property("boolean"), graphson); TitanGraphBuildingUtils.insertIntoObjectNode("double", v.property("double"), graphson); TitanGraphBuildingUtils.insertIntoObjectNode("str", v.property("str"), graphson); final ObjectNode user_graphson = _mapper.createObjectNode(); user_graphson.put("long", 3L); user_graphson.put("integer", 3); user_graphson.put("boolean", true); user_graphson.put("double", 3.1); user_graphson.put("str", "string"); assertEquals(graphson.toString(), user_graphson.toString()); tx.commit();//w w w . j a v a 2 s. c om }
From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java
private static void exec(final String src, final String dst) throws XMLStreamException, IOException { XMLStreamWriter writer = new PrettyPrintXMLStreamWriter( OUTPUT_FACTORY.createXMLStreamWriter(new FileWriter(dst)), 2); writer.writeStartDocument("UTF-8", "1.0"); writer.writeStartElement("dataset"); StringWriter reporterSW = new StringWriter(); XMLStreamWriter reporter = new PrettyPrintXMLStreamWriter(OUTPUT_FACTORY.createXMLStreamWriter(reporterSW), 2);//from www. ja va2 s .co m reporter.writeStartDocument("UTF-8", "1.0"); reporter.writeStartElement("dataset"); InputStream inputStream = Files.newInputStream(Paths.get(src)); XMLStreamReader reader = INPUT_FACTORY.createXMLStreamReader(inputStream); reader.nextTag(); // root reader.nextTag(); // dataset writer.writeStartElement("AnyType"); writer.writeAttribute("id", "USER"); writer.writeAttribute("kind", "USER"); writer.writeEndElement(); writer.writeStartElement("AnyTypeClass"); writer.writeAttribute("id", "BaseUser"); writer.writeEndElement(); writer.writeStartElement("AnyType_AnyTypeClass"); writer.writeAttribute("anyType_id", "USER"); writer.writeAttribute("anyTypeClass_id", "BaseUser"); writer.writeEndElement(); writer.writeStartElement("AnyType"); writer.writeAttribute("id", "GROUP"); writer.writeAttribute("kind", "GROUP"); writer.writeEndElement(); writer.writeStartElement("AnyTypeClass"); writer.writeAttribute("id", "BaseGroup"); writer.writeEndElement(); writer.writeStartElement("AnyType_AnyTypeClass"); writer.writeAttribute("anyType_id", "GROUP"); writer.writeAttribute("anyTypeClass_id", "BaseGroup"); writer.writeEndElement(); writer.writeStartElement("AnyTypeClass"); writer.writeAttribute("id", "BaseUMembership"); writer.writeEndElement(); Set<String> connInstanceCapabilities = new HashSet<>(); String lastUUID; String syncopeConf = UUID.randomUUID().toString(); Map<String, String> cPlainAttrs = new HashMap<>(); Map<String, String> policies = new HashMap<>(); Map<String, String> connInstances = new HashMap<>(); Map<String, String> provisions = new HashMap<>(); Map<String, String> mappings = new HashMap<>(); Map<String, String> tasks = new HashMap<>(); Map<String, String> notifications = new HashMap<>(); Map<String, String> reports = new HashMap<>(); String globalAccountPolicy = null; String globalPasswordPolicy = null; while (reader.hasNext()) { if (reader.isStartElement()) { switch (reader.getLocalName().toLowerCase()) { case "syncopeconf": writer.writeStartElement("SyncopeConf"); writer.writeAttribute("id", syncopeConf); writer.writeEndElement(); break; case "cschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("PlainSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeEndElement(); break; case "cattr": writer.writeStartElement("CPlainAttr"); copyAttrs(reader, writer, "owner_id", "schema_name"); lastUUID = UUID.randomUUID().toString(); writer.writeAttribute("id", lastUUID); writer.writeAttribute("owner_id", syncopeConf); writer.writeAttribute("schema_id", getAttributeValue(reader, "schema_name")); writer.writeEndElement(); cPlainAttrs.put(getAttributeValue(reader, "id"), lastUUID); break; case "cattrvalue": writer.writeStartElement("CPlainAttrValue"); copyAttrs(reader, writer, "attribute_id"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("attribute_id", cPlainAttrs.get(getAttributeValue(reader, "attribute_id"))); writer.writeEndElement(); break; case "uschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("PlainSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseUser"); writer.writeEndElement(); break; case "uderschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("DerSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseUser"); writer.writeEndElement(); break; case "uvirschema": reporter.writeStartElement("VirSchema"); copyAttrs(reader, reporter); reporter.writeAttribute("key", getAttributeValue(reader, "name")); reporter.writeEndElement(); break; case "rschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("PlainSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseGroup"); writer.writeEndElement(); break; case "rderschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("DerSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseGroup"); writer.writeEndElement(); break; case "rvirschema": reporter.writeStartElement("VirSchema"); reporter.writeAttribute("key", getAttributeValue(reader, "name")); copyAttrs(reader, reporter); reporter.writeEndElement(); break; case "mschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("PlainSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseUMembership"); writer.writeEndElement(); break; case "mderschema": writer.writeStartElement("SyncopeSchema"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeStartElement("DerSchema"); copyAttrs(reader, writer); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("anyTypeClass_id", "BaseUMembership"); writer.writeEndElement(); break; case "mvirschema": reporter.writeStartElement("VirSchema"); copyAttrs(reader, reporter); reporter.writeAttribute("key", getAttributeValue(reader, "name")); reporter.writeEndElement(); break; case "policy": String policyId = getAttributeValue(reader, "id"); lastUUID = UUID.randomUUID().toString(); policies.put(policyId, lastUUID); ObjectNode specification = (ObjectNode) OBJECT_MAPPER .readTree(getAttributeValue(reader, "specification")); switch (getAttributeValue(reader, "DTYPE")) { case "SyncPolicy": writer.writeStartElement("PullPolicy"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("description", getAttributeValue(reader, "description")); writer.writeEndElement(); break; case "PasswordPolicy": writer.writeStartElement("PasswordPolicy"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("description", getAttributeValue(reader, "description")); if ("GLOBAL_PASSWORD".equalsIgnoreCase(getAttributeValue(reader, "type"))) { globalPasswordPolicy = lastUUID; } JsonNode allowNullPassword = specification.get("allowNullPassword"); if (allowNullPassword != null) { writer.writeAttribute("allowNullPassword", allowNullPassword.asBoolean() ? "1" : "0"); specification.remove("allowNullPassword"); } JsonNode historyLength = specification.get("historyLength"); if (historyLength != null) { writer.writeAttribute("historyLength", historyLength.asText()); specification.remove("historyLength"); } specification.put("@class", "org.apache.syncope.common.lib.policy.DefaultPasswordRuleConf"); writer.writeEndElement(); writer.writeStartElement("PasswordRuleConfInstance"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("passwordPolicy_id", lastUUID); writer.writeAttribute("serializedInstance", specification.toString()); writer.writeEndElement(); break; case "AccountPolicy": writer.writeStartElement("AccountPolicy"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("description", getAttributeValue(reader, "description")); if ("GLOBAL_ACCOUNT".equalsIgnoreCase(getAttributeValue(reader, "type"))) { globalAccountPolicy = lastUUID; } JsonNode propagateSuspension = specification.get("propagateSuspension"); if (propagateSuspension != null) { writer.writeAttribute("propagateSuspension", propagateSuspension.asBoolean() ? "1" : "0"); specification.remove("propagateSuspension"); } JsonNode permittedLoginRetries = specification.get("permittedLoginRetries"); if (permittedLoginRetries != null) { writer.writeAttribute("maxAuthenticationAttempts", permittedLoginRetries.asText()); specification.remove("permittedLoginRetries"); } specification.put("@class", "org.apache.syncope.common.lib.policy.DefaultAccountRuleConf"); writer.writeEndElement(); writer.writeStartElement("AccountRuleConfInstance"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("accountPolicy_id", lastUUID); writer.writeAttribute("serializedInstance", specification.toString()); writer.writeEndElement(); break; default: } break; case "conninstance": lastUUID = UUID.randomUUID().toString(); connInstances.put(getAttributeValue(reader, "id"), lastUUID); writer.writeStartElement("ConnInstance"); copyAttrs(reader, writer); writer.writeAttribute("id", lastUUID); writer.writeEndElement(); break; case "conninstance_capabilities": String connInstanceId = getAttributeValue(reader, "connInstance_id"); String connInstanceKey = connInstances.get(connInstanceId); String capabilities = getAttributeValue(reader, "capabilities"); if (capabilities.startsWith("ONE_PHASE_")) { capabilities = capabilities.substring(10); } else if (capabilities.startsWith("TWO_PHASES_")) { capabilities = capabilities.substring(11); } if (!connInstanceCapabilities.contains(connInstanceId + capabilities)) { writer.writeStartElement("ConnInstance_capabilities"); writer.writeAttribute("connInstance_id", connInstanceKey); writer.writeAttribute("capability", capabilities); writer.writeEndElement(); connInstanceCapabilities.add(connInstanceId + capabilities); } break; case "externalresource": writer.writeStartElement("ExternalResource"); copyAttrs(reader, writer, "syncTraceLevel", "userializedSyncToken", "rserializedSyncToken", "propagationMode", "propagationPrimary", "connector_id", "syncPolicy_id", "passwordPolicy_id", "creator", "lastModifier", "creationDate", "lastChangeDate"); writer.writeAttribute("id", getAttributeValue(reader, "name")); writer.writeAttribute("connector_id", connInstances.get(getAttributeValue(reader, "connector_id"))); writer.writeAttribute("provisioningTraceLevel", getAttributeValue(reader, "syncTraceLevel")); String syncPolicyKey = policies.get(getAttributeValue(reader, "syncPolicy_id")); if (StringUtils.isNotBlank(syncPolicyKey)) { writer.writeAttribute("pullPolicy_id", syncPolicyKey); } String passwordPolicyKey = policies.get(getAttributeValue(reader, "passwordPolicy_id")); if (StringUtils.isNotBlank(passwordPolicyKey)) { writer.writeAttribute("passwordPolicy_id", passwordPolicyKey); } writer.writeEndElement(); break; case "externalresource_propactions": writer.writeStartElement("ExternalResource_PropActions"); writer.writeAttribute("resource_id", getAttributeValue(reader, "externalResource_name")); String propActionClassName = getAttributeValue(reader, "element"); switch (propActionClassName) { case "org.apache.syncope.core.propagation.impl.LDAPMembershipPropagationActions": propActionClassName = "org.apache.syncope.core.provisioning.java.propagation." + "LDAPMembershipPropagationActions"; break; case "org.apache.syncope.core.propagation.impl.LDAPPasswordPropagationActions": propActionClassName = "org.apache.syncope.core.provisioning.java.propagation." + "LDAPPasswordPropagationActions"; break; case "org.apache.syncope.core.propagation.impl.DBPasswordPropagationActions": propActionClassName = "org.apache.syncope.core.provisioning.java.propagation." + "DBPasswordPropagationActions"; break; default: } writer.writeAttribute("actionClassName", propActionClassName); writer.writeEndElement(); break; case "policy_externalresource": writer.writeStartElement("AccountPolicy_ExternalResource"); writer.writeAttribute("accountPolicy_id", policies.get(getAttributeValue(reader, "account_policy_id"))); writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name")); writer.writeEndElement(); break; case "umapping": String umappingId = getAttributeValue(reader, "id"); lastUUID = UUID.randomUUID().toString(); provisions.put(umappingId, lastUUID); writer.writeStartElement("Provision"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name")); writer.writeAttribute("anyType_id", "USER"); writer.writeAttribute("objectClass", "__ACCOUNT__"); writer.writeEndElement(); lastUUID = UUID.randomUUID().toString(); mappings.put(umappingId, lastUUID); writer.writeStartElement("Mapping"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("provision_id", provisions.get(umappingId)); String uaccountLink = getAttributeValue(reader, "accountlink"); if (StringUtils.isNotBlank(uaccountLink)) { writer.writeAttribute("connObjectLink", uaccountLink); } writer.writeEndElement(); break; case "umappingitem": String uIntMappingType = getAttributeValue(reader, "intMappingType"); if (uIntMappingType.endsWith("VirtualSchema")) { reporter.writeStartElement("MappingItem"); copyAttrs(reader, reporter, "accountid", "intMappingType"); reporter.writeEndElement(); } else { writer.writeStartElement("MappingItem"); copyAttrs(reader, writer, "accountid", "intMappingType", "mapping_id", "intMappingType", "intAttrName"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("mapping_id", mappings.get(getAttributeValue(reader, "mapping_id"))); writer.writeAttribute("connObjectKey", getAttributeValue(reader, "accountid")); writeIntAttrName(uIntMappingType, "intAttrName", mappings.get(getAttributeValue(reader, "intAttrName")), writer); writer.writeEndElement(); } break; case "rmapping": String rmappingId = "10" + getAttributeValue(reader, "id"); lastUUID = UUID.randomUUID().toString(); provisions.put(rmappingId, lastUUID); writer.writeStartElement("Provision"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("resource_id", getAttributeValue(reader, "resource_name")); writer.writeAttribute("anyType_id", "GROUP"); writer.writeAttribute("objectClass", "__GROUP__"); writer.writeEndElement(); lastUUID = UUID.randomUUID().toString(); mappings.put(rmappingId, lastUUID); writer.writeStartElement("Mapping"); writer.writeAttribute("id", lastUUID); writer.writeAttribute("provision_id", provisions.get(rmappingId)); String raccountLink = getAttributeValue(reader, "accountlink"); if (StringUtils.isNotBlank(raccountLink)) { writer.writeAttribute("connObjectLink", raccountLink); } writer.writeEndElement(); break; case "rmappingitem": String rIntMappingType = getAttributeValue(reader, "intMappingType"); if (rIntMappingType.endsWith("VirtualSchema")) { reporter.writeStartElement("MappingItem"); copyAttrs(reader, reporter, "accountid", "intMappingType"); reporter.writeEndElement(); } else { writer.writeStartElement("MappingItem"); copyAttrs(reader, writer, "accountid", "intMappingType", "mapping_id", "intAttrName"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("mapping_id", mappings.get("10" + getAttributeValue(reader, "mapping_id"))); writer.writeAttribute("connObjectKey", getAttributeValue(reader, "accountid")); writeIntAttrName(rIntMappingType, "intAttrName", mappings.get(getAttributeValue(reader, "intAttrName")), writer); writer.writeEndElement(); } break; case "task": writer.writeStartElement("Task"); copyAttrs(reader, writer, "DTYPE", "propagationMode", "subjectType", "subjectId", "xmlAttributes", "jobClassName", "userTemplate", "roleTemplate", "userFilter", "roleFilter", "propagationOperation", "syncStatus", "fullReconciliation", "resource_name"); lastUUID = UUID.randomUUID().toString(); tasks.put(getAttributeValue(reader, "id"), lastUUID); writer.writeAttribute("id", lastUUID); String resourceName = getAttributeValue(reader, "resource_name"); if (StringUtils.isNotBlank(resourceName)) { writer.writeAttribute("resource_id", resourceName); } String name = getAttributeValue(reader, "name"); if (StringUtils.isNotBlank(name)) { writer.writeAttribute("name", name); } switch (getAttributeValue(reader, "DTYPE")) { case "PropagationTask": writer.writeAttribute("DTYPE", "PropagationTask"); writer.writeAttribute("anyTypeKind", getAttributeValue(reader, "subjectType")); writer.writeAttribute("anyKey", getAttributeValue(reader, "subjectId")); writer.writeAttribute("attributes", getAttributeValue(reader, "xmlAttributes")); writer.writeAttribute("operation", getAttributeValue(reader, "propagationOperation")); writer.writeEndElement(); break; case "SyncTask": writer.writeAttribute("DTYPE", "PullTask"); writer.writeAttribute("syncStatus", getAttributeValue(reader, "syncStatus")); String fullReconciliation = getAttributeValue(reader, "fullReconciliation"); if ("1".equals(fullReconciliation)) { writer.writeAttribute("pullMode", "FULL_RECONCILIATION"); } else if ("0".equals(fullReconciliation)) { writer.writeAttribute("pullMode", "INCREMENTAL"); } writer.writeEndElement(); String userTemplate = getAttributeValue(reader, "userTemplate"); if (StringUtils.isNotBlank(userTemplate)) { ObjectNode template = (ObjectNode) OBJECT_MAPPER.readTree(userTemplate); JsonNode plainAttrs = template.remove("attrs"); template.set("plainAttrs", plainAttrs); writer.writeStartElement("AnyTemplatePullTask"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("pullTask_id", lastUUID); writer.writeAttribute("anyType_id", "USER"); writer.writeAttribute("template", template.toString()); writer.writeEndElement(); } String roleTemplate = getAttributeValue(reader, "roleTemplate"); if (StringUtils.isNotBlank(roleTemplate)) { ObjectNode template = (ObjectNode) OBJECT_MAPPER.readTree(roleTemplate); JsonNode plainAttrs = template.remove("attrs"); template.set("plainAttrs", plainAttrs); writer.writeStartElement("AnyTemplatePullTask"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("pullTask_id", lastUUID); writer.writeAttribute("anyType_id", "GROUP"); writer.writeAttribute("template", template.toString()); writer.writeEndElement(); } break; case "SchedTask": writer.writeAttribute("DTYPE", "SchedTask"); writer.writeAttribute("jobDelegateClassName", getAttributeValue(reader, "jobClassName")); writer.writeEndElement(); break; case "NotificationTask": writer.writeAttribute("DTYPE", "NotificationTask"); writer.writeEndElement(); break; case "PushTask": writer.writeAttribute("DTYPE", "PushTask"); writer.writeEndElement(); String userFilter = getAttributeValue(reader, "userFilter"); if (StringUtils.isNotBlank(userFilter)) { writer.writeStartElement("PushTaskAnyFilter"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("pushTask_id", lastUUID); writer.writeAttribute("anyType_id", "USER"); writer.writeAttribute("fiql", userFilter); writer.writeEndElement(); } String roleFilter = getAttributeValue(reader, "roleFilter"); if (StringUtils.isNotBlank(roleFilter)) { writer.writeStartElement("PushTaskAnyFilter"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("pushTask_id", lastUUID); writer.writeAttribute("anyType_id", "GROUP"); writer.writeAttribute("fiql", roleFilter); writer.writeEndElement(); } break; default: } break; case "taskexec": writer.writeStartElement("TaskExec"); copyAttrs(reader, writer, "task_id"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("task_id", tasks.get(getAttributeValue(reader, "task_id"))); writer.writeEndElement(); break; case "synctask_actionsclassnames": writer.writeStartElement("PullTask_actionsClassNames"); writer.writeAttribute("pullTask_id", tasks.get(getAttributeValue(reader, "syncTask_id"))); String syncActionClassName = getAttributeValue(reader, "element"); switch (syncActionClassName) { case "org.apache.syncope.core.sync.impl.LDAPMembershipSyncActions": syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.LDAPMembershipPullActions"; break; case "org.apache.syncope.core.sync.impl.LDAPPasswordSyncActions": syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.LDAPPasswordPullActions"; break; case "org.apache.syncope.core.sync.impl.DBPasswordSyncActions": syncActionClassName = "org.apache.syncope.core.provisioning.java.pushpull.DBPasswordPullActions"; break; default: } writer.writeAttribute("actionClassName", syncActionClassName); writer.writeEndElement(); break; case "notification": writer.writeStartElement("Notification"); lastUUID = UUID.randomUUID().toString(); notifications.put(getAttributeValue(reader, "id"), lastUUID); writer.writeAttribute("id", lastUUID); copyAttrs(reader, writer, "recipientAttrType", "template", "userAbout", "roleAbout", "recipients", "recipientAttrName"); String recipientAttrType = getAttributeValue(reader, "recipientAttrType"); writeIntAttrName(recipientAttrType, "recipientAttrName", mappings.get(getAttributeValue(reader, "recipientAttrName")), writer); String recipients = getAttributeValue(reader, "recipients"); if (StringUtils.isNotBlank(recipients)) { writer.writeAttribute("recipientsFIQL", getAttributeValue(reader, "recipients")); } writer.writeAttribute("template_id", getAttributeValue(reader, "template")); writer.writeEndElement(); String userAbout = getAttributeValue(reader, "userAbout"); if (StringUtils.isNotBlank(userAbout)) { writer.writeStartElement("AnyAbout"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("notification_id", lastUUID); writer.writeAttribute("anyType_id", "USER"); writer.writeAttribute("filter", userAbout); writer.writeEndElement(); } String roleAbout = getAttributeValue(reader, "roleAbout"); if (StringUtils.isNotBlank(roleAbout)) { writer.writeStartElement("AnyAbout"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("notification_id", lastUUID); writer.writeAttribute("anyType_id", "GROUP"); writer.writeAttribute("filter", roleAbout); writer.writeEndElement(); } break; case "notification_events": writer.writeStartElement("Notification_events"); copyAttrs(reader, writer, "notification_id", "events"); writer.writeAttribute("notification_id", notifications.get(getAttributeValue(reader, "notification_id"))); writer.writeAttribute("event", getAttributeValue(reader, "events").replaceAll("Controller", "Logic")); writer.writeEndElement(); break; case "notificationtask_recipients": writer.writeStartElement("NotificationTask_recipients"); copyAttrs(reader, writer, "notificationTask_id"); writer.writeAttribute("notificationTask_id", tasks.get(getAttributeValue(reader, "notificationTask_id"))); writer.writeEndElement(); break; case "report": writer.writeStartElement("Report"); copyAttrs(reader, writer); lastUUID = UUID.randomUUID().toString(); reports.put(getAttributeValue(reader, "id"), lastUUID); writer.writeAttribute("id", lastUUID); writer.writeAttribute("name", getAttributeValue(reader, "name")); writer.writeEndElement(); break; case "reportletconfinstance": writer.writeStartElement("ReportletConfInstance"); copyAttrs(reader, writer, "report_id"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("report_id", reports.get(getAttributeValue(reader, "report_id"))); writer.writeEndElement(); break; case "reportexec": writer.writeStartElement("ReportExec"); copyAttrs(reader, writer, "report_id"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("report_id", reports.get(getAttributeValue(reader, "report_id"))); writer.writeEndElement(); break; case "securityquestion": writer.writeStartElement("SecurityQuestion"); copyAttrs(reader, writer); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeEndElement(); break; default: } } reader.next(); } writer.writeStartElement("Realm"); writer.writeAttribute("id", UUID.randomUUID().toString()); writer.writeAttribute("name", "/"); if (globalAccountPolicy != null) { writer.writeAttribute("accountPolicy_id", globalAccountPolicy); } if (globalPasswordPolicy != null) { writer.writeAttribute("passwordPolicy_id", globalPasswordPolicy); } writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.close(); reporter.writeEndElement(); reporter.writeEndDocument(); reporter.close(); System.out.println("\nVirtual items, require manual intervention:\n" + reporterSW.toString()); }