Skip to content

Commit

Permalink
Allow loading included schemas on the class-path
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeEdgar committed Dec 21, 2021
1 parent ef86d59 commit eedfb16
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 3 deletions.
@@ -0,0 +1,28 @@
package io.xlate.edi.internal.schema;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

class ClasspathURLStreamHandler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;

public ClasspathURLStreamHandler(ClassLoader classLoader) {
this.classLoader = classLoader;
}

@Override
protected URLConnection openConnection(URL u) throws IOException {
final String resourcePath = u.getPath();
final URL resourceUrl = classLoader.getResource(resourcePath);

if (resourceUrl == null) {
throw new FileNotFoundException("Class-path resource not found: " + resourcePath);
}

return resourceUrl.openConnection();
}
}
13 changes: 12 additions & 1 deletion src/main/java/io/xlate/edi/internal/schema/SchemaReaderV4.java
Expand Up @@ -48,7 +48,18 @@ protected void readInclude(XMLStreamReader reader, Map<String, EDIType> types) t
}
}

URL schemaLocation = context != null ? new URL(context, location) : new URL(location);
URL schemaLocation;

if (location.startsWith("classpath:")) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (location.startsWith("classpath:/")) {
location = location.substring(0, "classpath:".length()) + location.substring("classpath:/".length());
}
schemaLocation = new URL(null, location, new ClasspathURLStreamHandler(loader));
} else {
schemaLocation = new URL(context, location);
}

types.putAll(StaEDISchemaFactory.readSchemaTypes(schemaLocation, super.properties));
reader.nextTag(); // End of include
} catch (Exception e) {
Expand Down
2 changes: 1 addition & 1 deletion src/test/resources/x12/005010X222/837_REF_impls.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schema xmlns="http://xlate.io/EDISchema/v4">

<include schemaLocation="file:./target/test-classes/x12/005010/837.xml"/>
<include schemaLocation="classpath:/x12/005010/837.xml"/>

<implementation>
<sequence>
Expand Down
2 changes: 1 addition & 1 deletion src/test/resources/x12/005010X222/837_loop1000_only.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schema xmlns="http://xlate.io/EDISchema/v4">

<include schemaLocation="file:./target/test-classes/x12/005010/837.xml"/>
<include schemaLocation="classpath:x12/005010/837.xml"/>

<implementation>
<sequence>
Expand Down

0 comments on commit eedfb16

Please sign in to comment.