From ebbacbdf42ef05d6fdee40a79e8511f43c6aac12 Mon Sep 17 00:00:00 2001 From: Alexander Dyuzhev Date: Fri, 2 Jul 2021 10:57:26 +0300 Subject: [PATCH] package name com.metanorma renamed to org.metanorma --- README.adoc | 2 +- pom.xml | 8 +- .../{com => org}/metanorma/Constants.java | 2 +- .../{com => org}/metanorma/LSInputImpl.java | 210 ++++----- .../metanorma/OutputFormatEnum.java | 12 +- .../{com => org}/metanorma/RegExHelper.java | 2 +- .../metanorma/ResourceResolver.java | 238 +++++------ .../metanorma/ResourcesUtils.java | 210 ++++----- .../{com => org}/metanorma/STSValidator.java | 14 +- .../java/{com => org}/metanorma/Util.java | 132 +++--- .../{com => org}/metanorma/XsltConverter.java | 8 +- .../java/{com => org}/metanorma/mn2sts.java | 400 +++++++++--------- .../metanorma/utils/LoggerHelper.java | 4 +- .../metanorma/validator/CheckAgainstEnum.java | 12 +- .../metanorma/validator/CheckAgainstMap.java | 42 +- .../metanorma/validator/DTDValidator.java | 212 +++++----- .../metanorma/validator/Validator.java | 84 ++-- .../metanorma/validator/XSDValidator.java | 100 ++--- src/main/resources/mn2sts.xsl | 4 +- .../{com => org}/metanorma/mn2stsTests.java | 8 +- 20 files changed, 853 insertions(+), 851 deletions(-) rename src/main/java/{com => org}/metanorma/Constants.java (96%) rename src/main/java/{com => org}/metanorma/LSInputImpl.java (93%) rename src/main/java/{com => org}/metanorma/OutputFormatEnum.java (62%) rename src/main/java/{com => org}/metanorma/RegExHelper.java (92%) rename src/main/java/{com => org}/metanorma/ResourceResolver.java (97%) rename src/main/java/{com => org}/metanorma/ResourcesUtils.java (97%) rename src/main/java/{com => org}/metanorma/STSValidator.java (91%) rename src/main/java/{com => org}/metanorma/Util.java (93%) rename src/main/java/{com => org}/metanorma/XsltConverter.java (97%) rename src/main/java/{com => org}/metanorma/mn2sts.java (95%) rename src/main/java/{com => org}/metanorma/utils/LoggerHelper.java (90%) rename src/main/java/{com => org}/metanorma/validator/CheckAgainstEnum.java (64%) rename src/main/java/{com => org}/metanorma/validator/CheckAgainstMap.java (92%) rename src/main/java/{com => org}/metanorma/validator/DTDValidator.java (94%) rename src/main/java/{com => org}/metanorma/validator/Validator.java (93%) rename src/main/java/{com => org}/metanorma/validator/XSDValidator.java (90%) rename src/test/java/{com => org}/metanorma/mn2stsTests.java (97%) diff --git a/README.adoc b/README.adoc index 228f8ce..f81970d 100644 --- a/README.adoc +++ b/README.adoc @@ -40,7 +40,7 @@ Update version in `pom.xml`, e.g.: [source,xml] ---- -com.metanorma +org.metanorma mn2sts 1.9 Metanorma MN XML to NISO STS XML converter diff --git a/pom.xml b/pom.xml index c37d9f3..80d388b 100644 --- a/pom.xml +++ b/pom.xml @@ -3,18 +3,18 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.metanorma + org.metanorma mn2sts 1.9 Metanorma XML to NISO STS XML converter jar - https://www.metanorma.com + https://www.metanorma.org UTF-8 1.8 1.8 ${project.artifactId}-${project.version}.jar - com.metanorma.mn2sts + org.metanorma.mn2sts 5.4.2 @@ -55,7 +55,7 @@ - com.metanorma.mn2sts + org.metanorma.mn2sts ${project.version} diff --git a/src/main/java/com/metanorma/Constants.java b/src/main/java/org/metanorma/Constants.java similarity index 96% rename from src/main/java/com/metanorma/Constants.java rename to src/main/java/org/metanorma/Constants.java index 8064518..46050f8 100644 --- a/src/main/java/com/metanorma/Constants.java +++ b/src/main/java/org/metanorma/Constants.java @@ -1,4 +1,4 @@ -package com.metanorma; +package org.metanorma; /** * diff --git a/src/main/java/com/metanorma/LSInputImpl.java b/src/main/java/org/metanorma/LSInputImpl.java similarity index 93% rename from src/main/java/com/metanorma/LSInputImpl.java rename to src/main/java/org/metanorma/LSInputImpl.java index 92403ca..3067acf 100644 --- a/src/main/java/com/metanorma/LSInputImpl.java +++ b/src/main/java/org/metanorma/LSInputImpl.java @@ -1,106 +1,106 @@ -package com.metanorma; - -import com.metanorma.utils.LoggerHelper; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.w3c.dom.ls.LSInput; - - -public class LSInputImpl implements LSInput { - - private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); - - private String publicId; - - private String systemId; - - public String getPublicId() { - return publicId; - } - - public void setPublicId(String publicId) { - this.publicId = publicId; - } - - public String getBaseURI() { - return null; - } - - public InputStream getByteStream() { - return null; - } - - public boolean getCertifiedText() { - return false; - } - - public Reader getCharacterStream() { - return null; - } - - public String getEncoding() { - return null; - } - - public String getStringData() { - synchronized (inputStream) { - try { - byte[] input = new byte[inputStream.available()]; - inputStream.read(input); - String contents = new String(input); - return contents; - } catch (IOException e) { - //e.printStackTrace(); - //System.out.println("Exception " + e); - logger.log(Level.INFO, "Exception {0}", e); - return null; - } - } - } - - public void setBaseURI(String baseURI) { - } - - public void setByteStream(InputStream byteStream) { - } - - public void setCertifiedText(boolean certifiedText) { - } - - public void setCharacterStream(Reader characterStream) { - } - - public void setEncoding(String encoding) { - } - - public void setStringData(String stringData) { - } - - public String getSystemId() { - return systemId; - } - - public void setSystemId(String systemId) { - this.systemId = systemId; - } - - public BufferedInputStream getInputStream() { - return inputStream; - } - - public void setInputStream(BufferedInputStream inputStream) { - this.inputStream = inputStream; - } - - private BufferedInputStream inputStream; - - public LSInputImpl(String publicId, String sysId, InputStream input) { - this.publicId = publicId; - this.systemId = sysId; - this.inputStream = new BufferedInputStream(input); - } +package org.metanorma; + +import org.metanorma.utils.LoggerHelper; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.w3c.dom.ls.LSInput; + + +public class LSInputImpl implements LSInput { + + private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); + + private String publicId; + + private String systemId; + + public String getPublicId() { + return publicId; + } + + public void setPublicId(String publicId) { + this.publicId = publicId; + } + + public String getBaseURI() { + return null; + } + + public InputStream getByteStream() { + return null; + } + + public boolean getCertifiedText() { + return false; + } + + public Reader getCharacterStream() { + return null; + } + + public String getEncoding() { + return null; + } + + public String getStringData() { + synchronized (inputStream) { + try { + byte[] input = new byte[inputStream.available()]; + inputStream.read(input); + String contents = new String(input); + return contents; + } catch (IOException e) { + //e.printStackTrace(); + //System.out.println("Exception " + e); + logger.log(Level.INFO, "Exception {0}", e); + return null; + } + } + } + + public void setBaseURI(String baseURI) { + } + + public void setByteStream(InputStream byteStream) { + } + + public void setCertifiedText(boolean certifiedText) { + } + + public void setCharacterStream(Reader characterStream) { + } + + public void setEncoding(String encoding) { + } + + public void setStringData(String stringData) { + } + + public String getSystemId() { + return systemId; + } + + public void setSystemId(String systemId) { + this.systemId = systemId; + } + + public BufferedInputStream getInputStream() { + return inputStream; + } + + public void setInputStream(BufferedInputStream inputStream) { + this.inputStream = inputStream; + } + + private BufferedInputStream inputStream; + + public LSInputImpl(String publicId, String sysId, InputStream input) { + this.publicId = publicId; + this.systemId = sysId; + this.inputStream = new BufferedInputStream(input); + } } \ No newline at end of file diff --git a/src/main/java/com/metanorma/OutputFormatEnum.java b/src/main/java/org/metanorma/OutputFormatEnum.java similarity index 62% rename from src/main/java/com/metanorma/OutputFormatEnum.java rename to src/main/java/org/metanorma/OutputFormatEnum.java index 967185d..2c3764c 100644 --- a/src/main/java/com/metanorma/OutputFormatEnum.java +++ b/src/main/java/org/metanorma/OutputFormatEnum.java @@ -1,6 +1,6 @@ -package com.metanorma; - - -public enum OutputFormatEnum { - NISO, ISO -} +package org.metanorma; + + +public enum OutputFormatEnum { + NISO, ISO +} diff --git a/src/main/java/com/metanorma/RegExHelper.java b/src/main/java/org/metanorma/RegExHelper.java similarity index 92% rename from src/main/java/com/metanorma/RegExHelper.java rename to src/main/java/org/metanorma/RegExHelper.java index a8db801..1ed8efa 100644 --- a/src/main/java/com/metanorma/RegExHelper.java +++ b/src/main/java/org/metanorma/RegExHelper.java @@ -1,4 +1,4 @@ -package com.metanorma; +package org.metanorma; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/src/main/java/com/metanorma/ResourceResolver.java b/src/main/java/org/metanorma/ResourceResolver.java similarity index 97% rename from src/main/java/com/metanorma/ResourceResolver.java rename to src/main/java/org/metanorma/ResourceResolver.java index a7d4a80..68be6bd 100644 --- a/src/main/java/com/metanorma/ResourceResolver.java +++ b/src/main/java/org/metanorma/ResourceResolver.java @@ -1,119 +1,119 @@ -package com.metanorma; - -// https://stackoverflow.com/questions/2342808/how-to-validate-an-xml-file-using-java-with-an-xsd-having-an-include - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; - -import org.w3c.dom.ls.LSInput; -import org.w3c.dom.ls.LSResourceResolver; - -/** - * The Class ResourceResolver. - */ -public class ResourceResolver implements LSResourceResolver { - - /** The schema base path. */ - private final String schemaBasePath; - - /** The path map. */ - private Map pathMap = new HashMap(); - - /** - * Instantiates a new resource resolver. - * - * @param schemaBasePath the schema base path - */ - public ResourceResolver(String schemaBasePath) { - this.schemaBasePath = schemaBasePath; - } - - /* (non-Javadoc) - * @see org.w3c.dom.ls.LSResourceResolver#resolveResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public LSInput resolveResource(String type, String namespaceURI, - String publicId, String systemId, String baseURI) { - // The base resource that includes this current resource - String baseResourceName = null; - String baseResourcePath = null; - // Extract the current resource name - if (systemId == null) { // skip empty - return null; // - } - String currentResourceName = systemId.substring(systemId.lastIndexOf("/") + 1); - - // If this resource hasn't been added yet - if (!pathMap.containsKey(currentResourceName)) { - if (baseURI != null) { - baseResourceName = baseURI - .substring(baseURI.lastIndexOf("/") + 1); - } - - // we dont need "./" since getResourceAsStream cannot understand it - if (systemId.startsWith("./")) { - systemId = systemId.substring(2, systemId.length()); - } - - // If the baseResourcePath has already been discovered, get that - // from pathMap - if (pathMap.containsKey(baseResourceName)) { - baseResourcePath = pathMap.get(baseResourceName); - } else { - // The baseResourcePath should be the schemaBasePath - baseResourcePath = schemaBasePath; - } - - // Read the resource as input stream - String normalizedPath = getNormalizedPath(baseResourcePath, systemId); - InputStream resourceAsStream = this.getClass().getClassLoader() - .getResourceAsStream(normalizedPath); - - // if the current resource is not in the same path with base - // resource, add current resource's path to pathMap - if (systemId.contains("/")) { - pathMap.put(currentResourceName, normalizedPath.substring(0,normalizedPath.lastIndexOf("/")+1)); - } else { - // The current resource should be at the same path as the base - // resource - pathMap.put(systemId, baseResourcePath); - } - Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A"); - String s1 = s.next().replaceAll("\\n", " ") // the parser cannot understand elements broken down multiple lines e.g. () - .replace("\\t", " ") // these two about whitespaces is only for decoration - .replaceAll("\\s+", " ").replaceAll("[^\\x20-\\x7e]", ""); // some files has a special character as a first character indicating utf-8 file - InputStream is = new ByteArrayInputStream(s1.getBytes()); - - return new LSInputImpl(publicId, systemId, is); // same as Input class - } - - // If this resource has already been added, do not add the same resource again. It throws - // "org.xml.sax.SAXParseException: sch-props-correct.2: A schema cannot contain two global components with the same name; this schema contains two occurrences of ..." - // return null instead. - return null; - } - - /** - * Gets the normalized path. - * - * @param basePath the base path - * @param relativePath the relative path - * @return the normalized path - */ - private String getNormalizedPath(String basePath, String relativePath){ - if(!relativePath.startsWith("../")){ - return basePath + relativePath; - } - else{ - while(relativePath.startsWith("../")){ - basePath = basePath.substring(0,basePath.substring(0, basePath.length()-1).lastIndexOf("/")+1); - relativePath = relativePath.substring(3); - } - return basePath+relativePath; - } - } -} - +package org.metanorma; + +// https://stackoverflow.com/questions/2342808/how-to-validate-an-xml-file-using-java-with-an-xsd-having-an-include + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +import org.w3c.dom.ls.LSInput; +import org.w3c.dom.ls.LSResourceResolver; + +/** + * The Class ResourceResolver. + */ +public class ResourceResolver implements LSResourceResolver { + + /** The schema base path. */ + private final String schemaBasePath; + + /** The path map. */ + private Map pathMap = new HashMap(); + + /** + * Instantiates a new resource resolver. + * + * @param schemaBasePath the schema base path + */ + public ResourceResolver(String schemaBasePath) { + this.schemaBasePath = schemaBasePath; + } + + /* (non-Javadoc) + * @see org.w3c.dom.ls.LSResourceResolver#resolveResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public LSInput resolveResource(String type, String namespaceURI, + String publicId, String systemId, String baseURI) { + // The base resource that includes this current resource + String baseResourceName = null; + String baseResourcePath = null; + // Extract the current resource name + if (systemId == null) { // skip empty + return null; // + } + String currentResourceName = systemId.substring(systemId.lastIndexOf("/") + 1); + + // If this resource hasn't been added yet + if (!pathMap.containsKey(currentResourceName)) { + if (baseURI != null) { + baseResourceName = baseURI + .substring(baseURI.lastIndexOf("/") + 1); + } + + // we dont need "./" since getResourceAsStream cannot understand it + if (systemId.startsWith("./")) { + systemId = systemId.substring(2, systemId.length()); + } + + // If the baseResourcePath has already been discovered, get that + // from pathMap + if (pathMap.containsKey(baseResourceName)) { + baseResourcePath = pathMap.get(baseResourceName); + } else { + // The baseResourcePath should be the schemaBasePath + baseResourcePath = schemaBasePath; + } + + // Read the resource as input stream + String normalizedPath = getNormalizedPath(baseResourcePath, systemId); + InputStream resourceAsStream = this.getClass().getClassLoader() + .getResourceAsStream(normalizedPath); + + // if the current resource is not in the same path with base + // resource, add current resource's path to pathMap + if (systemId.contains("/")) { + pathMap.put(currentResourceName, normalizedPath.substring(0,normalizedPath.lastIndexOf("/")+1)); + } else { + // The current resource should be at the same path as the base + // resource + pathMap.put(systemId, baseResourcePath); + } + Scanner s = new Scanner(resourceAsStream).useDelimiter("\\A"); + String s1 = s.next().replaceAll("\\n", " ") // the parser cannot understand elements broken down multiple lines e.g. () + .replace("\\t", " ") // these two about whitespaces is only for decoration + .replaceAll("\\s+", " ").replaceAll("[^\\x20-\\x7e]", ""); // some files has a special character as a first character indicating utf-8 file + InputStream is = new ByteArrayInputStream(s1.getBytes()); + + return new LSInputImpl(publicId, systemId, is); // same as Input class + } + + // If this resource has already been added, do not add the same resource again. It throws + // "org.xml.sax.SAXParseException: sch-props-correct.2: A schema cannot contain two global components with the same name; this schema contains two occurrences of ..." + // return null instead. + return null; + } + + /** + * Gets the normalized path. + * + * @param basePath the base path + * @param relativePath the relative path + * @return the normalized path + */ + private String getNormalizedPath(String basePath, String relativePath){ + if(!relativePath.startsWith("../")){ + return basePath + relativePath; + } + else{ + while(relativePath.startsWith("../")){ + basePath = basePath.substring(0,basePath.substring(0, basePath.length()-1).lastIndexOf("/")+1); + relativePath = relativePath.substring(3); + } + return basePath+relativePath; + } + } +} + diff --git a/src/main/java/com/metanorma/ResourcesUtils.java b/src/main/java/org/metanorma/ResourcesUtils.java similarity index 97% rename from src/main/java/com/metanorma/ResourcesUtils.java rename to src/main/java/org/metanorma/ResourcesUtils.java index 77f855b..3b6ec50 100644 --- a/src/main/java/com/metanorma/ResourcesUtils.java +++ b/src/main/java/org/metanorma/ResourcesUtils.java @@ -1,106 +1,106 @@ -package com.metanorma; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.JarURLConnection; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Enumeration; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - -public class ResourcesUtils { - - // https://github.com/nguyenq/tess4j/blob/master/src/main/java/net/sourceforge/tess4j/util/LoadLibs.java - /** - * Copies resources to target folder. - * - * @param resourceUrl - * @param targetPath - */ - public static void copyResources(URL resourceUrl, String basePath, File targetPath) throws IOException, URISyntaxException { - - if (resourceUrl == null) { - return; - } - - //System.out.println("resourceUrl=" + resourceUrl.toString()); - URLConnection urlConnection = resourceUrl.openConnection(); - - /** - * Copy resources either from inside jar or from project folder. - */ - if (urlConnection instanceof JarURLConnection) { - copyJarResourceToPath((JarURLConnection) urlConnection, targetPath); - } else { - File file = new File(resourceUrl.getPath()); - if (file.isDirectory()) { - for (File resourceFile : FileUtils.listFiles(file, null, true)) { - String resourceFilePath = resourceFile.getPath().replaceAll("\\\\", "/"); - //int index = resourceFile.getPath().lastIndexOf(targetPath.getName()) + targetPath.getName().length(); - int index = resourceFilePath.lastIndexOf(basePath); - File targetFile = new File(targetPath, resourceFile.getPath().substring(index)); - if (!targetFile.exists() || targetFile.length() != resourceFile.length() || targetFile.lastModified() != resourceFile.lastModified()) { - if (resourceFile.isFile()) { - FileUtils.copyFile(resourceFile, targetFile, true); - } - } - } - } else { - if (!targetPath.exists() || targetPath.length() != file.length() || targetPath.lastModified() != file.lastModified()) { - FileUtils.copyFile(file, targetPath, true); - } - } - } - } - - /** - * Copies resources from the jar file of the current thread and extract it - * to the destination path. - * - * @param jarConnection - * @param destPath destination file or directory - */ - static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) { - try (JarFile jarFile = jarConnection.getJarFile()) { - String jarConnectionEntryName = jarConnection.getEntryName(); - if (!jarConnectionEntryName.endsWith("/")) { - jarConnectionEntryName += "/"; - } - - /** - * Iterate all entries in the jar file. - */ - for (Enumeration e = jarFile.entries(); e.hasMoreElements();) { - JarEntry jarEntry = e.nextElement(); - String jarEntryName = jarEntry.getName(); - - /** - * Extract files only if they match the path. - */ - if (jarEntryName.startsWith(jarConnectionEntryName)) { - String filename = jarConnectionEntryName + jarEntryName.substring(jarConnectionEntryName.length()); - File targetFile = new File(destPath, filename); - - if (jarEntry.isDirectory()) { - targetFile.mkdirs(); - } else { - if (!targetFile.exists() || targetFile.length() != jarEntry.getSize()) { - try (InputStream is = jarFile.getInputStream(jarEntry); - OutputStream out = FileUtils.openOutputStream(targetFile)) { - IOUtils.copy(is, out); - } - } - } - } - } - } catch (IOException e) { - System.err.println(e.getMessage()); - } - } +package org.metanorma; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.JarURLConnection; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.util.Enumeration; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +public class ResourcesUtils { + + // https://github.com/nguyenq/tess4j/blob/master/src/main/java/net/sourceforge/tess4j/util/LoadLibs.java + /** + * Copies resources to target folder. + * + * @param resourceUrl + * @param targetPath + */ + public static void copyResources(URL resourceUrl, String basePath, File targetPath) throws IOException, URISyntaxException { + + if (resourceUrl == null) { + return; + } + + //System.out.println("resourceUrl=" + resourceUrl.toString()); + URLConnection urlConnection = resourceUrl.openConnection(); + + /** + * Copy resources either from inside jar or from project folder. + */ + if (urlConnection instanceof JarURLConnection) { + copyJarResourceToPath((JarURLConnection) urlConnection, targetPath); + } else { + File file = new File(resourceUrl.getPath()); + if (file.isDirectory()) { + for (File resourceFile : FileUtils.listFiles(file, null, true)) { + String resourceFilePath = resourceFile.getPath().replaceAll("\\\\", "/"); + //int index = resourceFile.getPath().lastIndexOf(targetPath.getName()) + targetPath.getName().length(); + int index = resourceFilePath.lastIndexOf(basePath); + File targetFile = new File(targetPath, resourceFile.getPath().substring(index)); + if (!targetFile.exists() || targetFile.length() != resourceFile.length() || targetFile.lastModified() != resourceFile.lastModified()) { + if (resourceFile.isFile()) { + FileUtils.copyFile(resourceFile, targetFile, true); + } + } + } + } else { + if (!targetPath.exists() || targetPath.length() != file.length() || targetPath.lastModified() != file.lastModified()) { + FileUtils.copyFile(file, targetPath, true); + } + } + } + } + + /** + * Copies resources from the jar file of the current thread and extract it + * to the destination path. + * + * @param jarConnection + * @param destPath destination file or directory + */ + static void copyJarResourceToPath(JarURLConnection jarConnection, File destPath) { + try (JarFile jarFile = jarConnection.getJarFile()) { + String jarConnectionEntryName = jarConnection.getEntryName(); + if (!jarConnectionEntryName.endsWith("/")) { + jarConnectionEntryName += "/"; + } + + /** + * Iterate all entries in the jar file. + */ + for (Enumeration e = jarFile.entries(); e.hasMoreElements();) { + JarEntry jarEntry = e.nextElement(); + String jarEntryName = jarEntry.getName(); + + /** + * Extract files only if they match the path. + */ + if (jarEntryName.startsWith(jarConnectionEntryName)) { + String filename = jarConnectionEntryName + jarEntryName.substring(jarConnectionEntryName.length()); + File targetFile = new File(destPath, filename); + + if (jarEntry.isDirectory()) { + targetFile.mkdirs(); + } else { + if (!targetFile.exists() || targetFile.length() != jarEntry.getSize()) { + try (InputStream is = jarFile.getInputStream(jarEntry); + OutputStream out = FileUtils.openOutputStream(targetFile)) { + IOUtils.copy(is, out); + } + } + } + } + } + } catch (IOException e) { + System.err.println(e.getMessage()); + } + } } \ No newline at end of file diff --git a/src/main/java/com/metanorma/STSValidator.java b/src/main/java/org/metanorma/STSValidator.java similarity index 91% rename from src/main/java/com/metanorma/STSValidator.java rename to src/main/java/org/metanorma/STSValidator.java index 154f555..eb84481 100644 --- a/src/main/java/com/metanorma/STSValidator.java +++ b/src/main/java/org/metanorma/STSValidator.java @@ -1,11 +1,11 @@ -package com.metanorma; +package org.metanorma; -import static com.metanorma.Constants.*; -import com.metanorma.utils.LoggerHelper; -import com.metanorma.validator.CheckAgainstEnum; -import com.metanorma.validator.CheckAgainstMap; -import com.metanorma.validator.DTDValidator; -import com.metanorma.validator.XSDValidator; +import static org.metanorma.Constants.*; +import org.metanorma.utils.LoggerHelper; +import org.metanorma.validator.CheckAgainstEnum; +import org.metanorma.validator.CheckAgainstMap; +import org.metanorma.validator.DTDValidator; +import org.metanorma.validator.XSDValidator; import java.io.File; import java.util.List; diff --git a/src/main/java/com/metanorma/Util.java b/src/main/java/org/metanorma/Util.java similarity index 93% rename from src/main/java/com/metanorma/Util.java rename to src/main/java/org/metanorma/Util.java index 619603d..f3be944 100644 --- a/src/main/java/com/metanorma/Util.java +++ b/src/main/java/org/metanorma/Util.java @@ -1,66 +1,66 @@ -package com.metanorma; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -/** - * - * @author Alexander Dyuzhev - */ -public class Util { - - public static String getAppVersion() { - String version = ""; - try { - Enumeration resources = mn2sts.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); - while (resources.hasMoreElements()) { - Manifest manifest = new Manifest(resources.nextElement().openStream()); - // check that this is your manifest and do what you need or get the next one - Attributes attr = manifest.getMainAttributes(); - String mainClass = attr.getValue("Main-Class"); - if(mainClass != null && mainClass.contains("com.metanorma.mn2sts")) { - version = manifest.getMainAttributes().getValue("Implementation-Version"); - } - } - } catch (IOException ex) { - version = ""; - } - - return version; - } - - // get file from classpath, resources folder - public static InputStream getStreamFromResources(ClassLoader classLoader, String fileName) throws Exception { - InputStream stream = classLoader.getResourceAsStream(fileName); - if (stream == null) { - throw new Exception("Cannot get resource \"" + fileName + "\" from Jar file."); - } - return stream; - } - - public static void FlushTempFolder(Path tmpfilepath) { - if (Files.exists(tmpfilepath)) { - //Files.deleteIfExists(tmpfilepath); - try { - Files.walk(tmpfilepath) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - } - - public static String getJavaTempDir() { - return System.getProperty("java.io.tmpdir"); - } -} +package org.metanorma; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +/** + * + * @author Alexander Dyuzhev + */ +public class Util { + + public static String getAppVersion() { + String version = ""; + try { + Enumeration resources = mn2sts.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); + while (resources.hasMoreElements()) { + Manifest manifest = new Manifest(resources.nextElement().openStream()); + // check that this is your manifest and do what you need or get the next one + Attributes attr = manifest.getMainAttributes(); + String mainClass = attr.getValue("Main-Class"); + if(mainClass != null && mainClass.contains("org.metanorma.mn2sts")) { + version = manifest.getMainAttributes().getValue("Implementation-Version"); + } + } + } catch (IOException ex) { + version = ""; + } + + return version; + } + + // get file from classpath, resources folder + public static InputStream getStreamFromResources(ClassLoader classLoader, String fileName) throws Exception { + InputStream stream = classLoader.getResourceAsStream(fileName); + if (stream == null) { + throw new Exception("Cannot get resource \"" + fileName + "\" from Jar file."); + } + return stream; + } + + public static void FlushTempFolder(Path tmpfilepath) { + if (Files.exists(tmpfilepath)) { + //Files.deleteIfExists(tmpfilepath); + try { + Files.walk(tmpfilepath) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + public static String getJavaTempDir() { + return System.getProperty("java.io.tmpdir"); + } +} diff --git a/src/main/java/com/metanorma/XsltConverter.java b/src/main/java/org/metanorma/XsltConverter.java similarity index 97% rename from src/main/java/com/metanorma/XsltConverter.java rename to src/main/java/org/metanorma/XsltConverter.java index 35cca51..c19d70d 100644 --- a/src/main/java/com/metanorma/XsltConverter.java +++ b/src/main/java/org/metanorma/XsltConverter.java @@ -1,8 +1,8 @@ -package com.metanorma; +package org.metanorma; -import static com.metanorma.Constants.*; -import com.metanorma.utils.LoggerHelper; -import com.metanorma.validator.CheckAgainstEnum; +import static org.metanorma.Constants.*; +import org.metanorma.utils.LoggerHelper; +import org.metanorma.validator.CheckAgainstEnum; import java.io.BufferedWriter; import java.io.File; diff --git a/src/main/java/com/metanorma/mn2sts.java b/src/main/java/org/metanorma/mn2sts.java similarity index 95% rename from src/main/java/com/metanorma/mn2sts.java rename to src/main/java/org/metanorma/mn2sts.java index 7540f1b..42bc000 100644 --- a/src/main/java/com/metanorma/mn2sts.java +++ b/src/main/java/org/metanorma/mn2sts.java @@ -1,201 +1,201 @@ -package com.metanorma; - -import static com.metanorma.Constants.*; -import com.metanorma.utils.LoggerHelper; -import java.io.PrintWriter; -import java.io.StringWriter; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -/** - * This application for the conversion of an XML file from Metanorma to NISO/ISO STS format - */ -public class mn2sts { - - static String VER = Util.getAppVersion(); - - static final Options optionsInfo = new Options() { - { - addOption(Option.builder("v") - .longOpt("version") - .desc("display application version") - .required(true) - .build()); - } - }; - - static final Options optionsCheckOnly = new Options() { - { - addOption(Option.builder("v") - .longOpt("version") - .desc("display application version") - .required(false) - .build()); - addOption(Option.builder("x") - .longOpt("xml-file-in") - .desc("path to source XML file") - .hasArg() - .argName("file") - .required(true) - .build()); - addOption(Option.builder("t") - .longOpt("check-type") - .desc("Check against XSD NISO (value xsd-niso), DTD ISO (dtd-iso), DTD NISO (dtd-niso) (Default: xsd-niso)") - .hasArg() - .argName("xsd-niso|dtd-iso|dtd-niso") - .required(false) - .build()); - } - }; - - static final Options options = new Options() { - { - addOption(Option.builder("x") - .longOpt("xml-file-in") - .desc("path to source XML file") - .hasArg() - .argName("file") - .required(true) - .build()); - addOption(Option.builder("s") - .longOpt("xsl-file") - .desc("path to XSL file (optional)") - .hasArg() - .argName("file") - .required(false) - .build()); - addOption(Option.builder("o") - .longOpt("xml-file-out") - .desc("path to output XML file") - .hasArg() - .argName("file") - .required(true) - .build()); - addOption(Option.builder("d") - .longOpt("debug") - .desc("print additional debug information into output XML file") - .required(false) - .build()); - addOption(Option.builder("v") - .longOpt("version") - .desc("display application version") - .required(false) - .build()); - addOption(Option.builder("t") - .longOpt("check-type") - .desc("Check against XSD NISO (value 'xsd-niso'), DTD ISO (value 'dtd-iso'), DTD NISO (value 'dtd-niso') (Default: xsd-niso)") - .hasArg() - .argName("xsd-niso|dtd-iso|dtd-niso") - .required(false) - .build()); - addOption(Option.builder("f") - .longOpt("output-format") - .desc("Output format: NISO STS (value 'niso') or ISO STS (value 'iso') (Default: niso)") - .hasArg() - .argName("niso|iso") - .required(false) - .build()); - } - }; - - static final String USAGE = getUsage(); - - - /** - * Main method. - * - * @param args command-line arguments - * @throws org.apache.commons.cli.ParseException - */ - public static void main(String[] args) throws ParseException { - - LoggerHelper.setupLogger(); - - CommandLineParser parser = new DefaultParser(); - - boolean cmdFail = false; - - try { - CommandLine cmdInfo = parser.parse(optionsInfo, args); - printVersion(cmdInfo.hasOption("version")); - } catch (ParseException exp) { - cmdFail = true; - } - - if(cmdFail) { - try { - CommandLine cmdCheckOnly = parser.parse(optionsCheckOnly, args); - System.out.print("mn2sts "); - printVersion(cmdCheckOnly.hasOption("version")); - System.out.println("\n"); - - STSValidator validator = new STSValidator(cmdCheckOnly.getOptionValue("xml-file-in"), cmdCheckOnly.getOptionValue("check-type")); - - if (!validator.check()) { - System.exit(ERROR_EXIT_CODE); - } - - cmdFail = false; - } catch (ParseException exp) { - cmdFail = true; - } - } - - if(cmdFail) { - try { - CommandLine cmd = parser.parse(options, args); - - System.out.print("mn2sts "); - printVersion(cmd.hasOption("version")); - System.out.println("\n"); - - XsltConverter converter = new XsltConverter(); - converter.setInputFilePath(cmd.getOptionValue("xml-file-in")); - converter.setInputXslPath(cmd.getOptionValue("xsl-file")); - converter.setOutputFilePath(cmd.getOptionValue("xml-file-out")); - converter.setDebugMode(cmd.hasOption("debug")); - converter.setCheckType(cmd.getOptionValue("check-type")); - converter.setOutputFormat(cmd.getOptionValue("output-format")); - - boolean result = converter.process(); - - if (!result) { - System.exit(ERROR_EXIT_CODE); - } - cmdFail = false; - - - } catch (ParseException exp) { - cmdFail = true; - } - } - - if (cmdFail) { - System.out.println(USAGE); - System.exit(ERROR_EXIT_CODE); - } - } - - private static String getUsage() { - StringWriter stringWriter = new StringWriter(); - PrintWriter pw = new PrintWriter(stringWriter); - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp(pw, 80, CMD, "", options, 0, 0, ""); - pw.flush(); - return stringWriter.toString(); - } - - - private static void printVersion(boolean print) { - if (print) { - System.out.println(VER); - } - } - +package org.metanorma; + +import static org.metanorma.Constants.*; +import org.metanorma.utils.LoggerHelper; +import java.io.PrintWriter; +import java.io.StringWriter; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +/** + * This application for the conversion of an XML file from Metanorma to NISO/ISO STS format + */ +public class mn2sts { + + static String VER = Util.getAppVersion(); + + static final Options optionsInfo = new Options() { + { + addOption(Option.builder("v") + .longOpt("version") + .desc("display application version") + .required(true) + .build()); + } + }; + + static final Options optionsCheckOnly = new Options() { + { + addOption(Option.builder("v") + .longOpt("version") + .desc("display application version") + .required(false) + .build()); + addOption(Option.builder("x") + .longOpt("xml-file-in") + .desc("path to source XML file") + .hasArg() + .argName("file") + .required(true) + .build()); + addOption(Option.builder("t") + .longOpt("check-type") + .desc("Check against XSD NISO (value xsd-niso), DTD ISO (dtd-iso), DTD NISO (dtd-niso) (Default: xsd-niso)") + .hasArg() + .argName("xsd-niso|dtd-iso|dtd-niso") + .required(false) + .build()); + } + }; + + static final Options options = new Options() { + { + addOption(Option.builder("x") + .longOpt("xml-file-in") + .desc("path to source XML file") + .hasArg() + .argName("file") + .required(true) + .build()); + addOption(Option.builder("s") + .longOpt("xsl-file") + .desc("path to XSL file (optional)") + .hasArg() + .argName("file") + .required(false) + .build()); + addOption(Option.builder("o") + .longOpt("xml-file-out") + .desc("path to output XML file") + .hasArg() + .argName("file") + .required(true) + .build()); + addOption(Option.builder("d") + .longOpt("debug") + .desc("print additional debug information into output XML file") + .required(false) + .build()); + addOption(Option.builder("v") + .longOpt("version") + .desc("display application version") + .required(false) + .build()); + addOption(Option.builder("t") + .longOpt("check-type") + .desc("Check against XSD NISO (value 'xsd-niso'), DTD ISO (value 'dtd-iso'), DTD NISO (value 'dtd-niso') (Default: xsd-niso)") + .hasArg() + .argName("xsd-niso|dtd-iso|dtd-niso") + .required(false) + .build()); + addOption(Option.builder("f") + .longOpt("output-format") + .desc("Output format: NISO STS (value 'niso') or ISO STS (value 'iso') (Default: niso)") + .hasArg() + .argName("niso|iso") + .required(false) + .build()); + } + }; + + static final String USAGE = getUsage(); + + + /** + * Main method. + * + * @param args command-line arguments + * @throws org.apache.commons.cli.ParseException + */ + public static void main(String[] args) throws ParseException { + + LoggerHelper.setupLogger(); + + CommandLineParser parser = new DefaultParser(); + + boolean cmdFail = false; + + try { + CommandLine cmdInfo = parser.parse(optionsInfo, args); + printVersion(cmdInfo.hasOption("version")); + } catch (ParseException exp) { + cmdFail = true; + } + + if(cmdFail) { + try { + CommandLine cmdCheckOnly = parser.parse(optionsCheckOnly, args); + System.out.print("mn2sts "); + printVersion(cmdCheckOnly.hasOption("version")); + System.out.println("\n"); + + STSValidator validator = new STSValidator(cmdCheckOnly.getOptionValue("xml-file-in"), cmdCheckOnly.getOptionValue("check-type")); + + if (!validator.check()) { + System.exit(ERROR_EXIT_CODE); + } + + cmdFail = false; + } catch (ParseException exp) { + cmdFail = true; + } + } + + if(cmdFail) { + try { + CommandLine cmd = parser.parse(options, args); + + System.out.print("mn2sts "); + printVersion(cmd.hasOption("version")); + System.out.println("\n"); + + XsltConverter converter = new XsltConverter(); + converter.setInputFilePath(cmd.getOptionValue("xml-file-in")); + converter.setInputXslPath(cmd.getOptionValue("xsl-file")); + converter.setOutputFilePath(cmd.getOptionValue("xml-file-out")); + converter.setDebugMode(cmd.hasOption("debug")); + converter.setCheckType(cmd.getOptionValue("check-type")); + converter.setOutputFormat(cmd.getOptionValue("output-format")); + + boolean result = converter.process(); + + if (!result) { + System.exit(ERROR_EXIT_CODE); + } + cmdFail = false; + + + } catch (ParseException exp) { + cmdFail = true; + } + } + + if (cmdFail) { + System.out.println(USAGE); + System.exit(ERROR_EXIT_CODE); + } + } + + private static String getUsage() { + StringWriter stringWriter = new StringWriter(); + PrintWriter pw = new PrintWriter(stringWriter); + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp(pw, 80, CMD, "", options, 0, 0, ""); + pw.flush(); + return stringWriter.toString(); + } + + + private static void printVersion(boolean print) { + if (print) { + System.out.println(VER); + } + } + } \ No newline at end of file diff --git a/src/main/java/com/metanorma/utils/LoggerHelper.java b/src/main/java/org/metanorma/utils/LoggerHelper.java similarity index 90% rename from src/main/java/com/metanorma/utils/LoggerHelper.java rename to src/main/java/org/metanorma/utils/LoggerHelper.java index 9b1c3dd..dd0642c 100644 --- a/src/main/java/com/metanorma/utils/LoggerHelper.java +++ b/src/main/java/org/metanorma/utils/LoggerHelper.java @@ -1,6 +1,6 @@ -package com.metanorma.utils; +package org.metanorma.utils; -import com.metanorma.mn2sts; +import org.metanorma.mn2sts; /** * diff --git a/src/main/java/com/metanorma/validator/CheckAgainstEnum.java b/src/main/java/org/metanorma/validator/CheckAgainstEnum.java similarity index 64% rename from src/main/java/com/metanorma/validator/CheckAgainstEnum.java rename to src/main/java/org/metanorma/validator/CheckAgainstEnum.java index 33febe2..18089b7 100644 --- a/src/main/java/com/metanorma/validator/CheckAgainstEnum.java +++ b/src/main/java/org/metanorma/validator/CheckAgainstEnum.java @@ -1,6 +1,6 @@ -package com.metanorma.validator; - - -public enum CheckAgainstEnum { - XSD_NISO, DTD_ISO, DTD_NISO -} +package org.metanorma.validator; + + +public enum CheckAgainstEnum { + XSD_NISO, DTD_ISO, DTD_NISO +} diff --git a/src/main/java/com/metanorma/validator/CheckAgainstMap.java b/src/main/java/org/metanorma/validator/CheckAgainstMap.java similarity index 92% rename from src/main/java/com/metanorma/validator/CheckAgainstMap.java rename to src/main/java/org/metanorma/validator/CheckAgainstMap.java index ae50624..edda248 100644 --- a/src/main/java/com/metanorma/validator/CheckAgainstMap.java +++ b/src/main/java/org/metanorma/validator/CheckAgainstMap.java @@ -1,21 +1,21 @@ -package com.metanorma.validator; - -import java.io.File; -import java.util.EnumMap; - - -public class CheckAgainstMap { - - static final EnumMap checkAgainstMap = new EnumMap(CheckAgainstEnum.class) { - { - put(CheckAgainstEnum.XSD_NISO, "NISO-STS-extended-1-MathML3-XSD" + File.separator + "NISO-STS-extended-1-mathml3.xsd"); - put(CheckAgainstEnum.DTD_ISO, "ISO-STS-DTD_v1.1" + File.separator + "ISOSTS.dtd"); - put(CheckAgainstEnum.DTD_NISO, "NISO-STS-extended-1-MathML3-DTD" + File.separator + "NISO-STS-extended-1-mathml3.dtd"); - } - }; - - public static EnumMap getMap() { - return checkAgainstMap; - } - -} +package org.metanorma.validator; + +import java.io.File; +import java.util.EnumMap; + + +public class CheckAgainstMap { + + static final EnumMap checkAgainstMap = new EnumMap(CheckAgainstEnum.class) { + { + put(CheckAgainstEnum.XSD_NISO, "NISO-STS-extended-1-MathML3-XSD" + File.separator + "NISO-STS-extended-1-mathml3.xsd"); + put(CheckAgainstEnum.DTD_ISO, "ISO-STS-DTD_v1.1" + File.separator + "ISOSTS.dtd"); + put(CheckAgainstEnum.DTD_NISO, "NISO-STS-extended-1-MathML3-DTD" + File.separator + "NISO-STS-extended-1-mathml3.dtd"); + } + }; + + public static EnumMap getMap() { + return checkAgainstMap; + } + +} diff --git a/src/main/java/com/metanorma/validator/DTDValidator.java b/src/main/java/org/metanorma/validator/DTDValidator.java similarity index 94% rename from src/main/java/com/metanorma/validator/DTDValidator.java rename to src/main/java/org/metanorma/validator/DTDValidator.java index 528ff83..d3e3718 100644 --- a/src/main/java/com/metanorma/validator/DTDValidator.java +++ b/src/main/java/org/metanorma/validator/DTDValidator.java @@ -1,106 +1,106 @@ -package com.metanorma.validator; - -import com.metanorma.ResourcesUtils; -import com.metanorma.Util; -import com.metanorma.utils.LoggerHelper; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.xml.sax.InputSource; - -public class DTDValidator extends Validator { - - private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); - boolean DEBUG = false; - - public DTDValidator (File xml) { - super(xml); - } - - @Override - public List validate(CheckAgainstEnum checkAgainst) { - this.checkAgainst = checkAgainst; - - String checkSrc = CheckAgainstMap.getMap().get(checkAgainst); - String checkSrcPath = "/" + new File(checkSrc).getParentFile(); - //System.out.println("Validate XML againts DTD " + checkSrc + "..."); - logger.log(Level.INFO, "Validate XML againts DTD {0}...", checkSrc); - - try { - DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = dbfactory.newDocumentBuilder(); - - // copy dtd folder and xml file into the temp folder - final Path tmpfilepath = Paths.get(Util.getJavaTempDir(), UUID.randomUUID().toString()); - - Files.createDirectories(tmpfilepath); - - ResourcesUtils.copyResources(getClass().getResource(checkSrcPath), checkSrcPath, tmpfilepath.toFile()); - // to debug jar - //jar:file:/C:/Metanorma/mn2sts/target/mn2sts-1.1.jar!/NISO-STS-extended-1-MathML3-DTD - //java.net.URL url = new java.net.URL("jar:file:/C:\\Metanorma\\mn2sts\\mn2sts-1.1.jar!/NISO-STS-extended-1-MathML3-DTD"); - //ResourcesUtils.copyResources(url , checkSrcPath, tmpfilepath.toFile()); - - //add - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = transformerFactory.newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - - Document document = builder.parse(xml); - DOMImplementation domImpl = document.getImplementation(); - DocumentType doctype = domImpl.createDocumentType("doctype", - "", - tmpfilepath + File.separator + checkSrc); - //transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); - transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); - DOMSource source = new DOMSource(document); - File xmlWithDTD = Paths.get(tmpfilepath.toString(), xml.getName()).toFile();//xmlout.getAbsolutePath() + ".tmp"; - StreamResult result = new StreamResult(xmlWithDTD); - - transformer.transform(source, result); - - InputStream inputStream = new FileInputStream(xmlWithDTD); - Reader reader = new InputStreamReader(inputStream,"UTF-8"); - dbfactory = DocumentBuilderFactory.newInstance(); - dbfactory.setValidating(true); - builder = dbfactory.newDocumentBuilder(); - builder.setErrorHandler(errorHandler); - builder.parse(new InputSource(reader)); - - // flush temporary folder - if (!DEBUG) { - Util.FlushTempFolder(tmpfilepath); - } - - } catch (Exception ex) { - exceptions.add("Validation error: " + ex.toString()); - } - return exceptions; - } - - public void setDebug (boolean debug) - { - this.DEBUG = debug; - } -} +package org.metanorma.validator; + +import org.metanorma.ResourcesUtils; +import org.metanorma.Util; +import org.metanorma.utils.LoggerHelper; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentType; +import org.xml.sax.InputSource; + +public class DTDValidator extends Validator { + + private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); + boolean DEBUG = false; + + public DTDValidator (File xml) { + super(xml); + } + + @Override + public List validate(CheckAgainstEnum checkAgainst) { + this.checkAgainst = checkAgainst; + + String checkSrc = CheckAgainstMap.getMap().get(checkAgainst); + String checkSrcPath = "/" + new File(checkSrc).getParentFile(); + //System.out.println("Validate XML againts DTD " + checkSrc + "..."); + logger.log(Level.INFO, "Validate XML againts DTD {0}...", checkSrc); + + try { + DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = dbfactory.newDocumentBuilder(); + + // copy dtd folder and xml file into the temp folder + final Path tmpfilepath = Paths.get(Util.getJavaTempDir(), UUID.randomUUID().toString()); + + Files.createDirectories(tmpfilepath); + + ResourcesUtils.copyResources(getClass().getResource(checkSrcPath), checkSrcPath, tmpfilepath.toFile()); + // to debug jar + //jar:file:/C:/Metanorma/mn2sts/target/mn2sts-1.1.jar!/NISO-STS-extended-1-MathML3-DTD + //java.net.URL url = new java.net.URL("jar:file:/C:\\Metanorma\\mn2sts\\mn2sts-1.1.jar!/NISO-STS-extended-1-MathML3-DTD"); + //ResourcesUtils.copyResources(url , checkSrcPath, tmpfilepath.toFile()); + + //add + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + + Document document = builder.parse(xml); + DOMImplementation domImpl = document.getImplementation(); + DocumentType doctype = domImpl.createDocumentType("doctype", + "", + tmpfilepath + File.separator + checkSrc); + //transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId()); + transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId()); + DOMSource source = new DOMSource(document); + File xmlWithDTD = Paths.get(tmpfilepath.toString(), xml.getName()).toFile();//xmlout.getAbsolutePath() + ".tmp"; + StreamResult result = new StreamResult(xmlWithDTD); + + transformer.transform(source, result); + + InputStream inputStream = new FileInputStream(xmlWithDTD); + Reader reader = new InputStreamReader(inputStream,"UTF-8"); + dbfactory = DocumentBuilderFactory.newInstance(); + dbfactory.setValidating(true); + builder = dbfactory.newDocumentBuilder(); + builder.setErrorHandler(errorHandler); + builder.parse(new InputSource(reader)); + + // flush temporary folder + if (!DEBUG) { + Util.FlushTempFolder(tmpfilepath); + } + + } catch (Exception ex) { + exceptions.add("Validation error: " + ex.toString()); + } + return exceptions; + } + + public void setDebug (boolean debug) + { + this.DEBUG = debug; + } +} diff --git a/src/main/java/com/metanorma/validator/Validator.java b/src/main/java/org/metanorma/validator/Validator.java similarity index 93% rename from src/main/java/com/metanorma/validator/Validator.java rename to src/main/java/org/metanorma/validator/Validator.java index 40c56a4..9dd8d13 100644 --- a/src/main/java/com/metanorma/validator/Validator.java +++ b/src/main/java/org/metanorma/validator/Validator.java @@ -1,42 +1,42 @@ -package com.metanorma.validator; - -import java.io.File; -import java.util.LinkedList; -import java.util.List; -import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; - -abstract class Validator { - - final List exceptions = new LinkedList<>(); - CheckAgainstEnum checkAgainst; - File xml; - - ErrorHandler errorHandler = new ErrorHandler() { - @Override - public void warning(SAXParseException exception) throws SAXException - { - exceptions.add(exception.toString()); - } - - @Override - public void fatalError(SAXParseException exception) throws SAXException - { - exceptions.add(exception.toString()); - } - - @Override - public void error(SAXParseException exception) throws SAXException - { - exceptions.add(exception.toString()); - } - }; - - public Validator (File xml) { - this.xml = xml; - } - - abstract public List validate(CheckAgainstEnum checkAgainst); - -} +package org.metanorma.validator; + +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +abstract class Validator { + + final List exceptions = new LinkedList<>(); + CheckAgainstEnum checkAgainst; + File xml; + + ErrorHandler errorHandler = new ErrorHandler() { + @Override + public void warning(SAXParseException exception) throws SAXException + { + exceptions.add(exception.toString()); + } + + @Override + public void fatalError(SAXParseException exception) throws SAXException + { + exceptions.add(exception.toString()); + } + + @Override + public void error(SAXParseException exception) throws SAXException + { + exceptions.add(exception.toString()); + } + }; + + public Validator (File xml) { + this.xml = xml; + } + + abstract public List validate(CheckAgainstEnum checkAgainst); + +} diff --git a/src/main/java/com/metanorma/validator/XSDValidator.java b/src/main/java/org/metanorma/validator/XSDValidator.java similarity index 90% rename from src/main/java/com/metanorma/validator/XSDValidator.java rename to src/main/java/org/metanorma/validator/XSDValidator.java index 8fc71bb..d13a439 100644 --- a/src/main/java/com/metanorma/validator/XSDValidator.java +++ b/src/main/java/org/metanorma/validator/XSDValidator.java @@ -1,50 +1,50 @@ -package com.metanorma.validator; - -import com.metanorma.ResourceResolver; -import com.metanorma.Util; -import com.metanorma.utils.LoggerHelper; -import java.io.File; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.XMLConstants; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -public class XSDValidator extends Validator { - - private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); - - public XSDValidator(File xml) { - super(xml); - } - - public List validate(CheckAgainstEnum checkAgainst) { - this.checkAgainst = checkAgainst; - - String checkSrc = CheckAgainstMap.getMap().get(checkAgainst); - - //System.out.println("Validate XML againts XSD " + checkSrc + "..."); - logger.log(Level.INFO, "Validate XML againts XSD {0}...", checkSrc); - - SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - // associate the schema factory with the resource resolver, which is responsible for resolving the imported XSD's - String rootResource = new File(checkSrc).getParentFile().toString() + "/"; - schemaFactory.setResourceResolver(new ResourceResolver(rootResource)); - //schemaFactory.setResourceResolver(new ResourceResolver("")); - - try { - Source schemaFile = new StreamSource(Util.getStreamFromResources(getClass().getClassLoader(), checkSrc.replaceAll("\\\\", "/"))); - Schema schema = schemaFactory.newSchema(schemaFile); - javax.xml.validation.Validator validator = schema.newValidator(); - validator.setErrorHandler(errorHandler); - validator.validate(new StreamSource(xml)); - } catch (Exception e) { - exceptions.add(e.toString()); - } - return exceptions; - } - -} +package org.metanorma.validator; + +import org.metanorma.ResourceResolver; +import org.metanorma.Util; +import org.metanorma.utils.LoggerHelper; +import java.io.File; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.XMLConstants; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +public class XSDValidator extends Validator { + + private static final Logger logger = Logger.getLogger(LoggerHelper.LOGGER_NAME); + + public XSDValidator(File xml) { + super(xml); + } + + public List validate(CheckAgainstEnum checkAgainst) { + this.checkAgainst = checkAgainst; + + String checkSrc = CheckAgainstMap.getMap().get(checkAgainst); + + //System.out.println("Validate XML againts XSD " + checkSrc + "..."); + logger.log(Level.INFO, "Validate XML againts XSD {0}...", checkSrc); + + SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + // associate the schema factory with the resource resolver, which is responsible for resolving the imported XSD's + String rootResource = new File(checkSrc).getParentFile().toString() + "/"; + schemaFactory.setResourceResolver(new ResourceResolver(rootResource)); + //schemaFactory.setResourceResolver(new ResourceResolver("")); + + try { + Source schemaFile = new StreamSource(Util.getStreamFromResources(getClass().getClassLoader(), checkSrc.replaceAll("\\\\", "/"))); + Schema schema = schemaFactory.newSchema(schemaFile); + javax.xml.validation.Validator validator = schema.newValidator(); + validator.setErrorHandler(errorHandler); + validator.validate(new StreamSource(xml)); + } catch (Exception e) { + exceptions.add(e.toString()); + } + return exceptions; + } + +} diff --git a/src/main/resources/mn2sts.xsl b/src/main/resources/mn2sts.xsl index 8a435ad..99bd448 100644 --- a/src/main/resources/mn2sts.xsl +++ b/src/main/resources/mn2sts.xsl @@ -5,7 +5,7 @@ xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xalan="http://xml.apache.org/xalan" xmlns:java="http://xml.apache.org/xalan/java" - xmlns:metanorma-class="xalan://com.metanorma.RegExHelper" + xmlns:metanorma-class="xalan://org.metanorma.RegExHelper" exclude-result-prefixes="xalan java metanorma-class" version="1.0"> @@ -2679,7 +2679,7 @@ dated - dated + dated undated diff --git a/src/test/java/com/metanorma/mn2stsTests.java b/src/test/java/org/metanorma/mn2stsTests.java similarity index 97% rename from src/test/java/com/metanorma/mn2stsTests.java rename to src/test/java/org/metanorma/mn2stsTests.java index 7e79939..4a1891c 100644 --- a/src/test/java/com/metanorma/mn2stsTests.java +++ b/src/test/java/org/metanorma/mn2stsTests.java @@ -1,7 +1,9 @@ -package com.metanorma; +package org.metanorma; -import static com.metanorma.Constants.*; -import com.metanorma.utils.LoggerHelper; +import org.metanorma.mn2sts; +import org.metanorma.RegExHelper; +import static org.metanorma.Constants.*; +import org.metanorma.utils.LoggerHelper; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream;