diff --git a/.gitignore b/.gitignore index f499553..bff2f1e 100644 --- a/.gitignore +++ b/.gitignore @@ -177,4 +177,6 @@ settings.xml # others -manip.md \ No newline at end of file +manip.md +.flattened-pom.xml +.mvn/ \ No newline at end of file diff --git a/src/main/java/com/geosiris/energyml/pkg/EPCFile.java b/src/main/java/com/geosiris/energyml/pkg/EPCFile.java index 7cf46ef..eec11c8 100644 --- a/src/main/java/com/geosiris/energyml/pkg/EPCFile.java +++ b/src/main/java/com/geosiris/energyml/pkg/EPCFile.java @@ -22,6 +22,7 @@ import energyml.core_properties.CoreProperties; import energyml.relationships.Relationship; import energyml.relationships.Relationships; +import energyml.relationships.TargetMode; import jakarta.xml.bind.JAXBException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -39,11 +40,12 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -public class EPCFile implements EnergymlWorkspace{ +public class EPCFile implements EnergymlWorkspace { public static Logger logger = LogManager.getLogger(EPCFile.class); /** - * Energyml files mapped by . The different versions of the object identified by the identifier (see. @getIdentifier) are stored in a list. + * Energyml files mapped by . The different versions of the object + * identified by the identifier (see. @getIdentifier) are stored in a list. */ Map energymlObjects; @@ -51,7 +53,7 @@ public class EPCFile implements EnergymlWorkspace{ Map> additionalRels; // Key is (Uuid;ObjectVersion) -// Map, List> readRels; + // Map, List> readRels; ExportVersion version; CoreProperties coreProperties; @@ -59,7 +61,9 @@ public class EPCFile implements EnergymlWorkspace{ String filePath; - public EPCFile(EPCPackageManager pkgManager, ExportVersion version, CoreProperties coreProperties, Map energymlObjects, Map otherFiles, Map> additionalRels ) { + public EPCFile(EPCPackageManager pkgManager, ExportVersion version, CoreProperties coreProperties, + Map energymlObjects, Map otherFiles, + Map> additionalRels) { this.energymlObjects = energymlObjects; this.otherFiles = otherFiles; this.additionalRels = additionalRels; @@ -69,20 +73,20 @@ public EPCFile(EPCPackageManager pkgManager, ExportVersion version, CoreProperti this.filePath = null; } - public EPCFile(EPCPackageManager pkgManager, ExportVersion version, CoreProperties coreProperties){ + public EPCFile(EPCPackageManager pkgManager, ExportVersion version, CoreProperties coreProperties) { this(pkgManager, version, coreProperties, new HashMap<>(), new HashMap<>(), new HashMap<>()); } - public EPCFile(EPCPackageManager pkgManager, ExportVersion version){ + public EPCFile(EPCPackageManager pkgManager, ExportVersion version) { this(pkgManager, version, new CoreProperties()); } - public EPCFile(EPCPackageManager pkgManager, String filePath){ + public EPCFile(EPCPackageManager pkgManager, String filePath) { this(pkgManager); this.filePath = filePath; } - public EPCFile(EPCPackageManager pkgManager){ + public EPCFile(EPCPackageManager pkgManager) { this(pkgManager, ExportVersion.EXPANDED); coreProperties.setVersion("1.0"); SimpleLiteral sl_creator = new SimpleLiteral(); @@ -91,9 +95,9 @@ public EPCFile(EPCPackageManager pkgManager){ } public void export(OutputStream os) throws IOException { - try(ZipOutputStream zos = new ZipOutputStream(os)){ + try (ZipOutputStream zos = new ZipOutputStream(os)) { // Non energyml entries : - for(Map.Entry e : otherFiles.entrySet()){ + for (Map.Entry e : otherFiles.entrySet()) { ZipEntry zipEntry = new ZipEntry(e.getKey()); zos.putNextEntry(zipEntry); e.getValue().transferTo(zos); @@ -122,26 +126,30 @@ public void export(OutputStream os) throws IOException { zos.closeEntry(); // Energyml Objects - for(String identifier : energymlObjects.keySet()){ + for (String identifier : energymlObjects.keySet()) { List toImport = new ArrayList<>(); - if(this.version == ExportVersion.CLASSIC){ + if (this.version == ExportVersion.CLASSIC) { // Only import the last version toImport.add(getLastModifiedObject(identifier)); - }else{ + } else { toImport.add(energymlObjects.get(identifier)); } - for(Object o : toImport){ - String pathInEPC = EPCGenericManager.genPathInEPC(o, this.version); - ZipEntry ze_obj = new ZipEntry(pathInEPC); - zos.putNextEntry(ze_obj); - this.pkgManager.marshal(o, zos); - zos.closeEntry(); - - Override overrideObjContentType = new Override(); - overrideObjContentType.setContentType(EPCGenericManager.getObjectContentType(o, true)); - overrideObjContentType.setPartName("/" + pathInEPC); // '/' at start is mandatory for ResqmlCAD - contentTypeFile.getDefaultOrOverride().add(overrideObjContentType); + for (Object o : toImport) { + if (o == null) { + logger.error("Null object found for identifier " + identifier); + } else { + String pathInEPC = EPCGenericManager.genPathInEPC(o, this.version); + ZipEntry ze_obj = new ZipEntry(pathInEPC); + zos.putNextEntry(ze_obj); + this.pkgManager.marshal(o, zos); + zos.closeEntry(); + + Override overrideObjContentType = new Override(); + overrideObjContentType.setContentType(EPCGenericManager.getObjectContentType(o, true)); + overrideObjContentType.setPartName("/" + pathInEPC); // '/' at start is mandatory for ResqmlCAD + contentTypeFile.getDefaultOrOverride().add(overrideObjContentType); + } } } @@ -152,7 +160,7 @@ public void export(OutputStream os) throws IOException { contentTypeFile.getDefaultOrOverride().add(relsDefaultCT); Map relsList = computeRelations(); - for(Map.Entry rels: relsList.entrySet()){ + for (Map.Entry rels : relsList.entrySet()) { String pathInEPC = OPCRelsPackage.genRelsPathInEPC(rels.getKey(), this.version); ZipEntry ze_objRels = new ZipEntry(pathInEPC); zos.putNextEntry(ze_objRels); @@ -167,7 +175,8 @@ public void export(OutputStream os) throws IOException { root_core_rel.setType(EPCRelsRelationshipType.ExtendedCoreProperties.getType()); rootRels.getRelationship().add(root_core_rel); - ZipEntry ze_rootRels = new ZipEntry(OPCRelsPackage.genRelsFolderPath(this.version) + "/." + OPCRelsPackage.getRelsExtension()); + ZipEntry ze_rootRels = new ZipEntry( + OPCRelsPackage.genRelsFolderPath(this.version) + "/." + OPCRelsPackage.getRelsExtension()); zos.putNextEntry(ze_rootRels); EPCGenericManager.marshal(OPCRelsPackage.JAXB_CONTEXT, null, rootRels, zos); zos.closeEntry(); @@ -179,7 +188,7 @@ public void export(OutputStream os) throws IOException { zos.closeEntry(); // Other files - for(Map.Entry otherFile: otherFiles.entrySet()){ + for (Map.Entry otherFile : otherFiles.entrySet()) { ZipEntry ze_otherFile = new ZipEntry(otherFile.getKey()); zos.putNextEntry(ze_otherFile); otherFile.getValue().transferTo(zos); @@ -188,12 +197,16 @@ public void export(OutputStream os) throws IOException { } } - public Object getLastModifiedObject(String uuid){ + public Object getLastModifiedObject(String identifier) { + final String uuid = getUuidFromIdentifier(identifier); + List objects = energymlObjects.entrySet().stream() .filter(e -> uuid.equals(getUuidFromIdentifier(e.getKey()))) .sorted((a, b) -> { - XMLGregorianCalendar a_lastModif = (XMLGregorianCalendar) ObjectController.getObjectAttributeValue(a, "Citation.LastUpdate"); - XMLGregorianCalendar b_lastModif = (XMLGregorianCalendar) ObjectController.getObjectAttributeValue(b, "Citation.LastUpdate"); + XMLGregorianCalendar a_lastModif = (XMLGregorianCalendar) ObjectController + .getObjectAttributeValue(a.getValue(), "Citation.LastUpdate"); + XMLGregorianCalendar b_lastModif = (XMLGregorianCalendar) ObjectController + .getObjectAttributeValue(b.getValue(), "Citation.LastUpdate"); if (a_lastModif == null) { return 1; } else if (b_lastModif == null) { @@ -201,21 +214,21 @@ public Object getLastModifiedObject(String uuid){ } else { return b_lastModif.compare(a_lastModif); } - }).collect(Collectors.toList()); - if(objects.size() > 0){ + }).map(Map.Entry::getValue).collect(Collectors.toList()); + if (!objects.isEmpty()) { return objects.get(0); } return null; } - public Object getObject(String uuid, String objectVersion){ + public Object getObject(String uuid, String objectVersion) { String identifier = getIdentifier(uuid, objectVersion); return getObjectByIdentifier(identifier); } @java.lang.Override public Object getObjectByIdentifier(String identifier) { - if(energymlObjects.containsKey(identifier)){ + if (energymlObjects.containsKey(identifier)) { return energymlObjects.get(identifier); } return null; @@ -231,87 +244,140 @@ public List readExternalArray(Object energyml_array, Object root_obj, String return List.of(); } - public List getAllVersions(String uuid){ + public List getAllVersions(String uuid) { return energymlObjects.keySet().stream() - .filter(o -> uuid.equals(getUuidFromIdentifier(o))) + .filter(o -> uuid.equals(getUuidFromIdentifier(o))) .map(EPCFile::getObjVersionFromIdentifier) .collect(Collectors.toList()); } - public Map computeRelations(){ + public Map computeRelations() { Map relations = new HashMap<>(); Map> sourceRels = new HashMap<>(); Map> destRels = new HashMap<>(); - for(Object o: this.energymlObjects.values()){ + for (Object o : this.energymlObjects.values()) { destRels.put(o, ObjectController.findSubObjects(o, "DataObjectReference", true).stream() .map(obj -> { - try{ + try { Object rel = getObjectByIdentifier(getIdentifier(obj)); - if(!sourceRels.containsKey(rel)){ + if (!sourceRels.containsKey(rel)) { sourceRels.put(rel, new ArrayList<>()); } sourceRels.get(rel).add(o); return rel; - }catch (Exception ignore){} + } catch (Exception ignore) { + } return null; }).filter(Objects::nonNull) .collect(Collectors.toList())); } - for(Object o: this.energymlObjects.values()){ + for (Object o : this.energymlObjects.values()) { Path o_parentFolder = Paths.get(EPCGenericManager.genPathInEPC(o, version)).getParent(); Relationships rels = new Relationships(); relations.put(o, rels); - if (sourceRels.containsKey(o)){ - for(Object source: new HashSet<>(sourceRels.get(o))){ + if (sourceRels.containsKey(o)) { + for (Object source : new HashSet<>(sourceRels.get(o))) { String s_uuid = getUuid(source); String s_objVersion = getObjectVersion(source); Relationship rel = new Relationship(); - rel.setType(EPCRelsRelationshipType.SourceObject.getType()); - rel.setId(URLEncoder.encode(s_uuid + (s_objVersion!= null ? "_" + s_objVersion : ""), Charset.defaultCharset())); - if(o_parentFolder != null) { - rel.setTarget(o_parentFolder.relativize(Paths.get(EPCGenericManager.genPathInEPC(source, version))).toString()); - }else{ + rel.setType(getRelType(o, false)); + // rel.setType(EPCRelsRelationshipType.SourceObject.getType()); + rel.setId(URLEncoder.encode(s_uuid + (s_objVersion != null ? "_" + s_objVersion : ""), + Charset.defaultCharset())); + if (o_parentFolder != null) { + rel.setTarget(o_parentFolder + .relativize(Paths.get(EPCGenericManager.genPathInEPC(source, version))).toString()); + } else { rel.setTarget(EPCGenericManager.genPathInEPC(source, version)); } rels.getRelationship().add(rel); } } - if (destRels.containsKey(o)){ - for(Object dest: new HashSet<>(destRels.get(o))){ + if (destRels.containsKey(o)) { + for (Object dest : new HashSet<>(destRels.get(o))) { String s_uuid = getUuid(dest); String s_objVersion = getObjectVersion(dest); Relationship rel = new Relationship(); - rel.setType(EPCRelsRelationshipType.DestinationObject.getType()); - rel.setId(URLEncoder.encode(s_uuid + (s_objVersion!= null ? "_" + s_objVersion : ""), Charset.defaultCharset())); - if(o_parentFolder != null) { - rel.setTarget(o_parentFolder.relativize(Paths.get(EPCGenericManager.genPathInEPC(dest, version))).toString()); - }else{ + rel.setType(getRelType(dest, true)); + // rel.setType(EPCRelsRelationshipType.DestinationObject.getType()); + rel.setId(URLEncoder.encode(s_uuid + (s_objVersion != null ? "_" + s_objVersion : ""), + Charset.defaultCharset())); + if (o_parentFolder != null) { + rel.setTarget(o_parentFolder + .relativize(Paths.get(EPCGenericManager.genPathInEPC(dest, version))).toString()); + } else { rel.setTarget(EPCGenericManager.genPathInEPC(dest, version)); } rels.getRelationship().add(rel); } } String oId = getIdentifier(o); - if (additionalRels.containsKey(oId)){ - for(Relationship r: additionalRels.get(oId)){ + if (additionalRels.containsKey(oId)) { + for (Relationship r : additionalRels.get(oId)) { rels.getRelationship().add(r); } } + + // remove duplicated that has the same target and type + List uniqueRels = rels.getRelationship().stream() + .collect(Collectors.toMap( + r -> r.getTarget() + "|" + r.getType(), + r -> r, + (r1, r2) -> r1)) + .values().stream() + .collect(Collectors.toList()); + + // force TargetMode to External for externalResource + for(Relationship r: uniqueRels){ + if(r.getType().equals(EPCRelsRelationshipType.ExternalResource.getType())){ + r.setTargetMode(TargetMode.EXTERNAL); + } + } + rels.getRelationship().clear(); + rels.getRelationship().addAll(uniqueRels); } return relations; } + public static boolean isProxyObjectType(Object o) { + if (o instanceof String) { + // try to match ExternalPar + String o_lw = ((String) o).toLowerCase(); + return o_lw.contains("external") && o_lw.contains("reference"); + } else { + return isProxyObjectType(o.getClass().getSimpleName()); + } + } + + public static String getRelType(Object referred_in_dor, Boolean rel_of_referer) { + if (rel_of_referer) { + // This rels is written in the referer object (the one which contains the dor) + if (isProxyObjectType(referred_in_dor)) { + return EPCRelsRelationshipType.MlToExternalPartProxy.getType(); + } else { + return EPCRelsRelationshipType.DestinationObject.getType(); + } + } else { + // This rels is written in the referred object (the DOR target) + if (isProxyObjectType(referred_in_dor)) { + return EPCRelsRelationshipType.ExternalPartProxyToMl.getType(); + } else { + return EPCRelsRelationshipType.SourceObject.getType(); + } + } + } + public static EPCFile read(String filePath, EPCPackageManager pkgManager) throws FileNotFoundException { EPCFile file = read(new FileInputStream(filePath), pkgManager); file.filePath = filePath; return file; } - public static EPCFile read(InputStream input, EPCPackageManager pkgManager){ + public static EPCFile read(InputStream input, EPCPackageManager pkgManager) { EPCFile epc = new EPCFile(pkgManager); byte[] buffer = new byte[2048]; @@ -319,10 +385,10 @@ public static EPCFile read(InputStream input, EPCPackageManager pkgManager){ Map mapPathToRelationships = new HashMap<>(); boolean foundNamespaceFolder = false; - try(ZipInputStream zip = new ZipInputStream(input)){ + try (ZipInputStream zip = new ZipInputStream(input)) { String corePath = OPCCorePackage.genCorePath(); ZipEntry entry = null; - while ((entry = zip.getNextEntry()) != null){ + while ((entry = zip.getNextEntry()) != null) { ByteArrayOutputStream entryBOS = new ByteArrayOutputStream(); int len; while ((len = zip.read(buffer)) > 0) { @@ -330,27 +396,34 @@ public static EPCFile read(InputStream input, EPCPackageManager pkgManager){ } // Other files - if(!entry.isDirectory() ) { + if (!entry.isDirectory()) { logger.debug("Reading " + entry.getName()); if (corePath.compareToIgnoreCase(entry.getName()) == 0) { - epc.coreProperties = (CoreProperties) OPCCorePackage.unmarshal(new ByteArrayInputStream(entryBOS.toByteArray())); - }else if (entry.getName().compareToIgnoreCase(OPCContentType.genContentTypePath()) == 0) { - // contentTypes = (Types) OPCContentType.unmarshal(new ByteArrayInputStream(entryBOS.toByteArray())); - }else if (entry.getName().endsWith(".xml")){ - try{ + epc.coreProperties = (CoreProperties) OPCCorePackage + .unmarshal(new ByteArrayInputStream(entryBOS.toByteArray())); + } else if (entry.getName().compareToIgnoreCase(OPCContentType.genContentTypePath()) == 0) { + // contentTypes = (Types) OPCContentType.unmarshal(new + // ByteArrayInputStream(entryBOS.toByteArray())); + } else if (entry.getName().endsWith(".xml")) { + try { Object o = pkgManager.unmarshal(entryBOS.toByteArray()).getValue(); String identifier = getIdentifier(o); - if(epc.energymlObjects.containsKey(identifier)){ + if (epc.energymlObjects.containsKey(identifier)) { logger.debug("Duplicate object found for identifier {}", identifier); } epc.energymlObjects.put(identifier, o); mapPathToObject.put(entry.getName(), o); - if(entry.getName().toLowerCase().startsWith("namespace_")){ + if (entry.getName().toLowerCase().startsWith("namespace_")) { foundNamespaceFolder = true; } - }catch (Exception e){logger.error("Error for {}: {}", entry.getName(), e);logger.error(e);}; - }else if (entry.getName().endsWith("." + OPCRelsPackage.getRelsExtension())){ - Relationships rels = (Relationships) OPCRelsPackage.unmarshal(new ByteArrayInputStream(entryBOS.toByteArray())); + } catch (Exception e) { + logger.error("Error for {}: {}", entry.getName(), e); + logger.error(e); + } + ; + } else if (entry.getName().endsWith("." + OPCRelsPackage.getRelsExtension())) { + Relationships rels = (Relationships) OPCRelsPackage + .unmarshal(new ByteArrayInputStream(entryBOS.toByteArray())); String objPath = entry.getName() .substring(0, entry.getName().lastIndexOf(".")) // removing rels extension .replace(OPCRelsPackage.genRelsFolderPath(epc.version) + "/", "") @@ -363,31 +436,41 @@ public static EPCFile read(InputStream input, EPCPackageManager pkgManager){ throw new RuntimeException(e); } - for(Map.Entry rels: mapPathToRelationships.entrySet()) { - if (mapPathToObject.containsKey(rels.getKey())){ + for (Map.Entry rels : mapPathToRelationships.entrySet()) { + if (mapPathToObject.containsKey(rels.getKey())) { Object target = mapPathToObject.get(rels.getKey()); String targId = getIdentifier(target); - Pair obj_pair = new Pair<>((String) ObjectController.getObjectAttributeValue(target, "uuid"), - getObjectVersion(target)); -// if(!epc.readRels.containsKey(obj_pair)){ -// epc.readRels.put(obj_pair, new ArrayList<>()); -// } -// epc.readRels.get(obj_pair).addAll(rels.getValue().getRelationship()); - - for(Relationship r: rels.getValue().getRelationship()){ - if(EPCRelsRelationshipType.DestinationObject.getType() .compareToIgnoreCase(r.getType()) != 0 - && EPCRelsRelationshipType.SourceObject.getType().compareToIgnoreCase(r.getType()) != 0){ - if(!epc.additionalRels.containsKey(targId)){ + // Pair obj_pair = new Pair<>( + // (String) ObjectController.getObjectAttributeValue(target, "uuid"), + // getObjectVersion(target)); + // if(!epc.readRels.containsKey(obj_pair)){ + // epc.readRels.put(obj_pair, new ArrayList<>()); + // } + // epc.readRels.get(obj_pair).addAll(rels.getValue().getRelationship()); + + for (Relationship r : rels.getValue().getRelationship()) { + if (EPCRelsRelationshipType.DestinationObject.getType().compareToIgnoreCase(r.getType()) != 0 + && EPCRelsRelationshipType.SourceObject.getType().compareToIgnoreCase(r.getType()) != 0) { + if (!epc.additionalRels.containsKey(targId)) { epc.additionalRels.put(targId, new ArrayList<>()); } epc.additionalRels.get(targId).add(r); } } - }else{ + } else { logger.error("Object " + rels.getKey() + " not found for rels"); - for(String k: mapPathToObject.keySet()){ - logger.debug("\t" + k + " ==> " + mapPathToObject.containsKey(rels.getKey()) + "--" + mapPathToObject.get(rels.getKey())); + StringBuilder sb = new StringBuilder(); + for (Relationship relationship : rels.getValue().getRelationship()) { + String[] parts = relationship.getType().split("/"); + sb.append(parts[parts.length - 1]); + sb.append(" => Target:"); + sb.append(relationship.getTarget()); + } + logger.debug(sb.toString()); + for (String k : mapPathToObject.keySet()) { + logger.debug("\t" + k + " ==> " + mapPathToObject.containsKey(rels.getKey()) + "--" + + mapPathToObject.get(rels.getKey())); } } } @@ -397,27 +480,31 @@ public static EPCFile read(InputStream input, EPCPackageManager pkgManager){ return epc; } -// public String findNumericalDataLocation(String uuid, String objectVersion){ -// Object related = getObject(uuid, objectVersion); -// if(related != null){ -// Relationships rels = computeRelations().get(related); -// for(Relationship rel : rels.getRelationship()){ -// if(rel.getType().compareToIgnoreCase(EPCRelsRelationshipType.ExternalResource.label) == 0){ -// if(rel.getTarget().toLowerCase().endsWith(".h5") || rel.getTarget().toLowerCase().endsWith(".hdf5")){ -// return rel.getTarget(); -// } -// } -// } -// List references = new ArrayList<>(); -// references.addAll(ObjectController.findAllAttributesFromName(related, "EpcExternalPartReference", true, false)); -// references.addAll(ObjectController.findAllAttributesFromName(related, "HdfProxy", true, false)); -// -// for(Object ref: references){ -// -// } -// } -// return null; -// } + // public String findNumericalDataLocation(String uuid, String objectVersion){ + // Object related = getObject(uuid, objectVersion); + // if(related != null){ + // Relationships rels = computeRelations().get(related); + // for(Relationship rel : rels.getRelationship()){ + // if(rel.getType().compareToIgnoreCase(EPCRelsRelationshipType.ExternalResource.label) + // == 0){ + // if(rel.getTarget().toLowerCase().endsWith(".h5") || + // rel.getTarget().toLowerCase().endsWith(".hdf5")){ + // return rel.getTarget(); + // } + // } + // } + // List references = new ArrayList<>(); + // references.addAll(ObjectController.findAllAttributesFromName(related, + // "EpcExternalPartReference", true, false)); + // references.addAll(ObjectController.findAllAttributesFromName(related, + // "HdfProxy", true, false)); + // + // for(Object ref: references){ + // + // } + // } + // return null; + // } /* --------------------------------------------------- */ @@ -433,9 +520,9 @@ public Map> getAdditionalRels() { return additionalRels; } -// public Map, List> getReadRels() { -// return readRels; -// } + // public Map, List> getReadRels() { + // return readRels; + // } public ExportVersion getVersion() { return version; @@ -456,31 +543,33 @@ public String getEpcFileFolder() { return null; } - public static String getUuid(Object obj){ + public static String getUuid(Object obj) { return (String) ObjectController.getObjectAttributeValueRgx(obj, "uuid").get(0); } - public static String getSchemaVersion(Object obj){ + public static String getSchemaVersion(Object obj) { return (String) ObjectController.getObjectAttributeValue(obj, "schemaVersion"); } - public static String getObjectVersion(Object obj){ + public static String getObjectVersion(Object obj) { try { return (String) ObjectController.getObjectAttributeValueRgx(obj, "objectVersion|versionString").get(0); - }catch (Exception e){ + } catch (Exception e) { logger.error("@getObjectVersion {}", e); } return null; -// return (String) ObjectController.getObjectAttributeValue(obj, "objectVersion"); + // return (String) ObjectController.getObjectAttributeValue(obj, + // "objectVersion"); } /** * Generates an objet identifier as : 'OBJ_UUID.OBJ_VERSION' * If the object version is None, the result is 'OBJ_UUID.' + * * @param obj * @return */ - public static String getIdentifier(Object obj){ + public static String getIdentifier(Object obj) { String objVersion = getObjectVersion(obj); if (objVersion == null) { objVersion = ""; @@ -489,17 +578,17 @@ public static String getIdentifier(Object obj){ return getIdentifier(objUuid, objVersion); } - public static String getIdentifier(String uuid, String objVersion){ - return uuid + "." + (objVersion != null ? objVersion: ""); + public static String getIdentifier(String uuid, String objVersion) { + return uuid + "." + (objVersion != null ? objVersion : ""); } - public static String getUuidFromIdentifier(String identifier){ + public static String getUuidFromIdentifier(String identifier) { return identifier.substring(0, identifier.indexOf(".")); } - public static String getObjVersionFromIdentifier(String identifier){ + public static String getObjVersionFromIdentifier(String identifier) { String version = identifier.substring(identifier.indexOf(".") + 1); - if(!version.isEmpty()) + if (!version.isEmpty()) return version; return null; } diff --git a/src/main/java/com/geosiris/energyml/pkg/EPCPackage.java b/src/main/java/com/geosiris/energyml/pkg/EPCPackage.java index e89442b..6509e68 100644 --- a/src/main/java/com/geosiris/energyml/pkg/EPCPackage.java +++ b/src/main/java/com/geosiris/energyml/pkg/EPCPackage.java @@ -50,7 +50,8 @@ public class EPCPackage { protected final String domain; /** - * Version of the package : for resqml2_2 is '2.2', for resqml_dev3x_2_2 is '2.2dev3' + * Version of the package : for resqml2_2 is '2.2', for resqml_dev3x_2_2 is + * '2.2dev3' */ protected final String domainVersion; protected final String versionNum; @@ -58,27 +59,28 @@ public class EPCPackage { protected final String packageName; protected final String packagePath; - public EPCPackage(String pkgPath, String xsdMappingFilePath) throws EPCPackageInitializationException { this(pkgPath, xsdMappingFilePath, Thread.currentThread().getContextClassLoader()); } - public EPCPackage(String pkgPath, String xsdMappingFilePath, final ClassLoader classLoader) throws EPCPackageInitializationException { + public EPCPackage(String pkgPath, String xsdMappingFilePath, final ClassLoader classLoader) + throws EPCPackageInitializationException { String devVersionNum1; this.packagePath = pkgPath; Matcher pkgMatch = EPCGenericManager.PATTERN_ENERGYML_CLASS_NAME.matcher(pkgPath); - if(pkgMatch.find()){ + if (pkgMatch.find()) { this.domain = pkgMatch.group("domain"); - this.domainVersion = (pkgMatch.group("versionNum") + (pkgMatch.group("dev") != null ? pkgMatch.group("dev"): "")).replace("_", "."); + this.domainVersion = (pkgMatch.group("versionNum") + + (pkgMatch.group("dev") != null ? pkgMatch.group("dev") : "")).replace("_", "."); this.packageName = pkgMatch.group("packageName"); this.versionNum = pkgMatch.group("versionNum").replace("_", "."); try { devVersionNum1 = pkgMatch.group("devNum").replace("_", "."); - }catch (Exception ignore){ + } catch (Exception ignore) { devVersionNum1 = null; } - }else{ + } else { throw new EPCPackageInitializationException(pkgPath); } @@ -87,27 +89,30 @@ public EPCPackage(String pkgPath, String xsdMappingFilePath, final ClassLoader c this.pkgClasses = new ArrayList<>(ContextBuilder.getClasses(this.packagePath, classLoader)); SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - try{ + try { xsdSchema = sf.newSchema(new File(Objects.requireNonNull(xsdMappingFilePath))); - }catch (Exception e){ + } catch (Exception e) { logger.error("ERR: no xsd schema for package '" + packagePath + "' at path " + xsdMappingFilePath); } } - public boolean isDevVersion(){ + public boolean isDevVersion() { return devVersionNum != null; } - public boolean isReleaseVersion(){ - return ! isDevVersion(); + public boolean isReleaseVersion() { + return !isDevVersion(); } public List> getRootsElementsClasses() { - // return pkgClasses.stream().filter(EPCGenericManager::isRootClass).collect(Collectors.toList()); OLD Way, but it includes types with no "createMY_TYPE_NAME(MY_TYPE value) -> JaxbElement" functions + // return + // pkgClasses.stream().filter(EPCGenericManager::isRootClass).collect(Collectors.toList()); + // OLD Way, but it includes types with no "createMY_TYPE_NAME(MY_TYPE value) -> + // JaxbElement" functions Object objFactory = getObjectFactory(); return Arrays.stream(objFactory.getClass().getMethods()) .filter(m -> m.getReturnType() == JAXBElement.class && m.getParameterCount() == 1) - .map(m->m.getParameters()[0].getType()) + .map(m -> m.getParameters()[0].getType()) .collect(Collectors.toList()); } @@ -161,13 +166,13 @@ public JAXBElement parseXmlContent(String xmlContent, boolean alternateDevVer long ticBegin = System.currentTimeMillis(); logger.debug(">Trying to parse from package '" + this.packagePath); - - JAXBElement result = parseXmlFromContext(xmlContent, true, alternateDevVersionExists, xsdSchema); + + JAXBElement result = parseXmlFromContext(xmlContent, true, alternateDevVersionExists, xsdSchema); if (result != null) { logger.debug("Success reading with '" + this.packagePath + "' object class : " + result.getValue().getClass().getName()); } else { - logger.debug("\terror reading with package " + this.packagePath); // + " --> " + xmlContent); + logger.debug("\terror reading with package " + this.packagePath); // + " --> " + xmlContent); } long ticEnd = System.currentTimeMillis(); @@ -176,20 +181,21 @@ public JAXBElement parseXmlContent(String xmlContent, boolean alternateDevVer } private JAXBElement parseXmlFromContext(String xmlContent, - boolean tryWithoutNamespaceIfFail, - boolean testRemarshalling, // test to marshall/unmarshall after first unmarshall - // to verify if everything has been read correctly - Schema schema) { + boolean tryWithoutNamespaceIfFail, + boolean testRemarshalling, // test to marshall/unmarshall after first unmarshall + // to verify if everything has been read correctly + Schema schema) { ValidationEventCollector vec = null; try { long ticCreateUnmarshaller_b = System.currentTimeMillis(); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - if(schema != null) + if (schema != null) unmarshaller.setSchema(schema); long ticCreateUnmarshaller_e = System.currentTimeMillis(); - logger.debug("\t@parseXmlFromContext (" + this.packagePath + ": Creating unmarshaller " + (ticCreateUnmarshaller_e - ticCreateUnmarshaller_b) / 1000.0 + "s"); + logger.debug("\t@parseXmlFromContext (" + this.packagePath + ": Creating unmarshaller " + + (ticCreateUnmarshaller_e - ticCreateUnmarshaller_b) / 1000.0 + "s"); vec = new ValidationEventCollector(); unmarshaller.setEventHandler(vec); @@ -198,7 +204,8 @@ private JAXBElement parseXmlFromContext(String xmlContent, long ticUnmarshall_b = System.currentTimeMillis(); JAXBElement result = (JAXBElement) unmarshaller.unmarshal(bais); long ticUnmarshall_e = System.currentTimeMillis(); - logger.debug("\t@parseXmlFromContext : Unmarshalling took " + (ticUnmarshall_e - ticUnmarshall_b) / 1000.0 + "s"); + logger.debug("\t@parseXmlFromContext : Unmarshalling took " + (ticUnmarshall_e - ticUnmarshall_b) / 1000.0 + + "s"); logger.debug("result " + result); if (vec.getEvents().length > 0) { @@ -208,19 +215,21 @@ private JAXBElement parseXmlFromContext(String xmlContent, logger.debug("events found"); return null; } else if (result != null) { - if(testRemarshalling) { + if (testRemarshalling) { logger.debug("no events found"); long ticMarshall_b = System.currentTimeMillis(); String xmlNewContent = marshal(result.getValue()); long ticMarshall_e = System.currentTimeMillis(); - logger.debug("\t@parseXmlFromContext : Marshalling took " + (ticMarshall_e - ticMarshall_b) / 1000.0 + "s"); + logger.debug("\t@parseXmlFromContext : Marshalling took " + (ticMarshall_e - ticMarshall_b) / 1000.0 + + "s"); long ticCountingChevron_b = System.currentTimeMillis(); int countOld = 0; int countNew = 0; for (int i = 0; i < xmlNewContent.length(); i++) if (xmlNewContent.charAt(i) == '<') - if (xmlNewContent.charAt(i + 1) != '?') // On ne compte pas le parseXmlFromContext(String xmlContent, long ticCountingChevron_e = System.currentTimeMillis(); - logger.debug("\t@parseXmlFromContext : Counting chevron cost " + (ticCountingChevron_e - ticCountingChevron_b) / 1000.0 + "s"); + logger.debug("\t@parseXmlFromContext : Counting chevron cost " + + (ticCountingChevron_e - ticCountingChevron_b) / 1000.0 + "s"); if (countOld > countNew) { logger.error("Error reading object class : " + result.getValue().getClass().getName() @@ -240,7 +250,8 @@ private JAXBElement parseXmlFromContext(String xmlContent, if (tryWithoutNamespaceIfFail) { logger.debug("Trying without namespace"); - String contentNoNamespace = xmlContent.replaceAll("<(/?)[a-zA-Z0-9_]+:([\\w\\d_]+)", "<$1$2"); + String contentNoNamespace = xmlContent.replaceAll("<(/?)[a-zA-Z0-9_]+:([\\w\\d_]+)", + "<$1$2"); return parseXmlFromContext(contentNoNamespace, false, testRemarshalling, schema); } else { return null; @@ -261,23 +272,25 @@ private JAXBElement parseXmlFromContext(String xmlContent, assert !processedXmlContent.contains(":obj_") && !processedXmlContent.contains(" result = parseXmlFromContext(processedXmlContent, tryWithoutNamespaceIfFail, testRemarshalling, schema); + JAXBElement result = parseXmlFromContext(processedXmlContent, tryWithoutNamespaceIfFail, + testRemarshalling, schema); if (result != null) { logger.debug("Successfully parsed after obj_ prefix removal"); return result; } - } catch (Exception ignore) {} + } catch (Exception ignore) { + } logger.debug("Failed to parse after obj_ prefix removal"); - }else{ - if(schema != null){ + } else { + if (schema != null) { logger.debug(e.getCause() + " " + e.getMessage()); // try to parse without schema return parseXmlFromContext(xmlContent, tryWithoutNamespaceIfFail, testRemarshalling, null); } logger.debug(e.getMessage(), e); logger.debug("File not read : "); - logger.debug(xmlContent.substring(0,500) + " [.....]"); - if(vec != null){ + logger.debug(xmlContent.substring(0, 500) + " [.....]"); + if (vec != null) { logger.debug("\tRead event [" + vec.getEvents().length + "]"); for (ValidationEvent ev : vec.getEvents()) { logger.debug("event : " + ev); @@ -301,7 +314,7 @@ public void marshal(Object obj, OutputStream os) { JAXBElement elt = wrap(obj, factory); marshaller.marshal(elt, os); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { + | InvocationTargetException e) { logger.error(e.getMessage(), e); } } catch (JAXBException e) { @@ -322,35 +335,35 @@ public static JAXBElement wrap(Object energymlObject, Object factory) throws methodPotentialName.add("create" + typename); methodPotentialName.add(typename.substring(0, 1).toLowerCase() + typename.substring(1)); for (String prefixToRemove : listOfPotentialRemovablePrefix) { - if(typename.startsWith(prefixToRemove)) { + if (typename.startsWith(prefixToRemove)) { String noPrefix = typename.substring(prefixToRemove.length()); methodPotentialName.add("create" + noPrefix); methodPotentialName.add(noPrefix.substring(0, 1).toLowerCase() + noPrefix.substring(1)); } } - for(String m_name : methodPotentialName){ + for (String m_name : methodPotentialName) { try { Method m = classFactory22.getMethod(m_name, class22); return (JAXBElement) m.invoke(factory, energymlObject); - }catch (NoSuchMethodException e){ + } catch (NoSuchMethodException e) { // pass } catch (Exception e2) { logger.error(e2.getMessage(), e2); } } logger.error("No method found to create a type " + typename); - logger.error("Tested names " + methodPotentialName.stream().reduce((s1,s2) -> s1 + ", " + s2)); + logger.error("Tested names " + methodPotentialName.stream().reduce((s1, s2) -> s1 + ", " + s2)); return null; } public boolean validate(Object obj) throws JAXBException { - if(obj != null) { + if (obj != null) { Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); jaxbUnmarshaller.setSchema(xsdSchema); String xmlObj = marshal(obj); - System.out.println(xmlObj); + logger.debug(xmlObj); ByteArrayInputStream bais = new ByteArrayInputStream(xmlObj.getBytes(StandardCharsets.UTF_8)); jaxbUnmarshaller.unmarshal(bais); @@ -360,7 +373,7 @@ public boolean validate(Object obj) throws JAXBException { } public String marshal(Object obj) { - if(obj != null) { + if (obj != null) { try { OutputStream os = new ByteArrayOutputStream(); marshal(obj, os); @@ -373,13 +386,13 @@ public String marshal(Object obj) { return null; } -/* - ______ __ __ _______ __ __ - / ____/__ / /_/ /____ __________ _/_/ ___/___ / /_/ /____ __________ - / / __/ _ \/ __/ __/ _ \/ ___/ ___/_/_/ \__ \/ _ \/ __/ __/ _ \/ ___/ ___/ - / /_/ / __/ /_/ /_/ __/ / (__ )/_/ ___/ / __/ /_/ /_/ __/ / (__ ) - \____/\___/\__/\__/\___/_/ /____/_/ /____/\___/\__/\__/\___/_/ /____/ -*/ + /* + * ______ __ __ _______ __ __ + * / ____/__ / /_/ /____ __________ _/_/ ___/___ / /_/ /____ __________ + * / / __/ _ \/ __/ __/ _ \/ ___/ ___/_/_/ \__ \/ _ \/ __/ __/ _ \/ ___/ ___/ + * / /_/ / __/ /_/ /_/ __/ / (__ )/_/ ___/ / __/ /_/ /_/ __/ / (__ ) + * \____/\___/\__/\__/\___/_/ /____/_/ /____/\___/\__/\__/\___/_/ /____/ + */ public String getDomain() { return domain; @@ -409,7 +422,7 @@ public String getDevVersionNum() { return devVersionNum; } - public boolean matchNamespace(String namespace){ + public boolean matchNamespace(String namespace) { return namespace.toLowerCase().contains(domain.toLowerCase()); } }