Skip to content

Commit

Permalink
Changed the file reference format to URI reference for the resolver s…
Browse files Browse the repository at this point in the history
…trategy input.

eclipse-esmf#474
  • Loading branch information
ysrbo committed Mar 19, 2024
1 parent 62e6a8a commit 430c55f
Show file tree
Hide file tree
Showing 26 changed files with 536 additions and 227 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,20 +50,6 @@
*/
public class SammAspectMetaModelResourceResolver implements AspectMetaModelResourceResolver {

/**
* Extends the given {@link Model} with elements contained in the given {@link InputStream}s.
*
* @param model the {@link Model} to be extended
* @param streams the {@link InputStream}s containing the additional model elements
* @return the extended {@link Model}
*/
private Try<Model> addToModel( final Model model, final Stream<InputStream> streams ) {
return streams.map( TurtleLoader::loadTurtle ).map( loadedModel -> loadedModel.flatMap( otherModel -> {
model.add( otherModel );
return Try.success( model );
} ) ).reduce( Try.success( model ), Try::orElse );
}

/**
* Loads an RDF model using a function that knows how to turn a target meta model version into a set of URLs
*
Expand All @@ -72,8 +58,17 @@ private Try<Model> addToModel( final Model model, final Stream<InputStream> stre
* @return The model
*/
private Try<Model> loadUrlSet( final KnownVersion version, final Function<KnownVersion, Set<URL>> resolver ) {
final Model model = ModelFactory.createDefaultModel();
return addToModel( model, resolver.apply( version ).stream().map( TurtleLoader::openUrl ) );
final Model result = ModelFactory.createDefaultModel();

var error = resolver.apply( version ).stream()
.map( url -> Try.withResources( url::openStream )
.of( TurtleLoader::loadTurtle )
.mapTry(Try::get)
.mapTry( result::add ))
.filter( Try::isFailure )
.findFirst();

return error.orElse( Try.success( result ) );
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,24 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
import javax.annotation.Nullable;

import org.eclipse.esmf.aspectmodel.resolver.exceptions.ParserException;
import org.eclipse.esmf.aspectmodel.resolver.parser.ReaderRiotTurtle;
import javax.annotation.Nullable;

import io.vavr.control.Try;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.Lang;
import org.apache.jena.riot.RDFLanguages;
import org.apache.jena.riot.RDFParserRegistry;
import org.apache.jena.riot.RiotException;
import org.eclipse.esmf.aspectmodel.resolver.exceptions.ParserException;
import org.eclipse.esmf.aspectmodel.resolver.parser.ReaderRiotTurtle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vavr.control.Try;

public final class TurtleLoader {
private static final Logger LOG = LoggerFactory.getLogger( TurtleLoader.class );

Expand Down Expand Up @@ -91,19 +91,4 @@ private static void registerTurtle() {
}
}
}

/**
* Opens an URL and returns its InputStream, but does not throw a checked exception.
*
* @param url The URL to open
* @return The InputStream on success
* @throws IllegalArgumentException if an {@link IOException} occurs
*/
public static InputStream openUrl( final URL url ) {
try {
return url.openStream();
} catch ( final IOException exception ) {
throw new IllegalArgumentException( exception );
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import org.eclipse.esmf.aspectmodel.generator.Artifact;
import org.eclipse.esmf.aspectmodel.generator.Generator;
import org.eclipse.esmf.metamodel.Aspect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -41,10 +40,9 @@ public JavaGenerator( final Aspect aspect, final JavaCodeGenerationConfig config
@Override
public void write( final Artifact<QualifiedName, String> artifact, final Function<QualifiedName, OutputStream> nameMapper ) {
final QualifiedName qualifiedName = artifact.getId();
final OutputStream outputStream = nameMapper.apply( qualifiedName );
final String content = artifact.getContent();
try ( final OutputStream outputStream = nameMapper.apply( qualifiedName ) ) {
final String content = artifact.getContent();

try {
try ( final Writer writer = new OutputStreamWriter( outputStream, StandardCharsets.UTF_8 ) ) {
for ( int i = 0; i < content.length(); i++ ) {
writer.write( content.charAt( i ) );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.tools.Diagnostic;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
Expand All @@ -48,58 +49,76 @@ public void report( final Diagnostic<? extends FileObject> diagnostic ) {
public static Map<QualifiedName, Class<?>> compile( final List<QualifiedName> loadOrder,
final Map<QualifiedName, String> sources, final List<String> predefinedClasses ) {
final javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final InMemoryClassFileManager manager = new InMemoryClassFileManager(
compiler.getStandardFileManager( null, null, null ) );
try(final InMemoryClassFileManager manager = new InMemoryClassFileManager(
compiler.getStandardFileManager( null, null, null ) )) {

final List<JavaFileObject> compilerInput = loadOrder.stream()
.map( key -> new CompilerInput( key.toString(), sources.get( key ) ) )
.collect( Collectors.toList() );
final List<JavaFileObject> compilerInput = loadOrder.stream()
.map( key -> new CompilerInput( key.toString(), sources.get( key ) ) )
.collect( Collectors.toList() );

if ( System.getProperty( WRITE_SOURCES_PROPERTY ) != null ) {
final String filepath = System.getProperty( "user.dir" ) + "/src/test/java/org/eclipse/esmf/test/";
final File outputdir = new File( filepath );
if ( !outputdir.exists() && !outputdir.mkdirs() ) {
throw new RuntimeException( "Could not create sources output directory " + outputdir );
}
for ( final Map.Entry<QualifiedName, String> entry : sources.entrySet() ) {
final String filename = entry.getKey().getClassName();
final File out = new File( filepath + filename + ".java" );
try {
final FileOutputStream outputStream = new FileOutputStream( out );
outputStream.write( entry.getValue().getBytes( StandardCharsets.UTF_8 ) );
outputStream.flush();
outputStream.close();
} catch ( final IOException e ) {
throw new RuntimeException( e );
if ( System.getProperty( WRITE_SOURCES_PROPERTY ) != null ) {
final String filepath = System.getProperty( "user.dir" ) + "/src/test/java/org/eclipse/esmf/test/";
final File outputdir = new File( filepath );
if ( !outputdir.exists() && !outputdir.mkdirs() ) {
throw new RuntimeException( "Could not create sources output directory " + outputdir );
}
for ( final Map.Entry<QualifiedName, String> entry : sources.entrySet() ) {
final String filename = entry.getKey().getClassName();
final File out = new File( filepath + filename + ".java" );
try ( final FileOutputStream outputStream = new FileOutputStream( out ) ) {
outputStream.write( entry.getValue().getBytes( StandardCharsets.UTF_8 ) );
outputStream.flush();
}
}
}
}

final DiagnosticListener diagnosticListener = new DiagnosticListener() {
@Override
public void report( final Diagnostic<? extends FileObject> diagnostic ) {
System.out.println( sources );
fail( "Compilation failed: " + diagnostic );
}
};
final DiagnosticListener diagnosticListener = new DiagnosticListener() {
@Override
public void report( final Diagnostic<? extends FileObject> diagnostic ) {
System.out.println( sources );
fail( "Compilation failed: " + diagnostic );
}
};

final List<String> compilerOptions = List.of( "-classpath", System.getProperty( "java.class.path" ) );
compiler.getTask( null, manager, diagnosticListener, compilerOptions, null, compilerInput ).call();
final ClassLoader classLoader = new ClassLoader() {
@Override
protected Class<?> findClass( final String name ) {
final byte[] classBytes = manager.getOutput( name ).getBytes();
return defineClass( name, classBytes, 0, classBytes.length );
}
};
return loadOrder.stream().collect( Collectors.toMap( Function.identity(), qualifiedName ->
defineAndLoad( qualifiedName, classLoader ) ) );
final List<String> compilerOptions = List.of( "-classpath", System.getProperty( "java.class.path" ) );
compiler.getTask( null, manager, diagnosticListener, compilerOptions, null, compilerInput ).call();
final ClassLoader classLoader = new ClassLoader() {
@Override
protected Class<?> findClass( final String name ) {
final byte[] classBytes = manager.getOutput( name ).getBytes();
return defineClass( name, classBytes, 0, classBytes.length );
}
};
return loadOrder.stream().collect( Collectors.toMap( Function.identity(), qualifiedName ->
defineAndLoad( qualifiedName, classLoader ) ) );
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}

@SuppressWarnings( "unchecked" )
private static <T> Class<T> defineAndLoad( final QualifiedName className, final ClassLoader classLoader ) {
try {
return (Class<T>) classLoader.loadClass( className.toString() );
// final List<String> compilerOptions = List.of( "-classpath", System.getProperty( "java.class.path" ) );
// compiler.getTask( null, manager, diagnosticListener, compilerOptions, null, compilerInput ).call();
// return loadOrder.stream().collect( Collectors.toMap( Function.identity(), qualifiedName ->
// defineAndLoad( qualifiedName, manager ) ) );
// } catch ( IOException e ) {
// throw new RuntimeException( e );
// }
// }
//
// @SuppressWarnings( "unchecked" )
// private static <T> Class<T> defineAndLoad( final QualifiedName className, final InMemoryClassFileManager manager ) {
// try {
// return (Class<T>) new ClassLoader() {
// @Override
// protected Class<?> findClass( final String name ) {
// final byte[] classBytes = manager.getOutput( name ).getBytes();
// return defineClass( name, classBytes, 0, classBytes.length );
// }
// }.loadClass( className.toString() );
} catch ( final ClassNotFoundException exception ) {
throw new RuntimeException( exception );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private static Map<QualifiedName, Class<?>> generateJavaCode( final File tempDir

final Map<QualifiedName, ByteArrayOutputStream> outputs = new LinkedHashMap<>();
generators.forEach( generator ->
generator.generate( name -> outputs.computeIfAbsent( name, name2 -> new ByteArrayOutputStream() ) ) );
generator.generate( name -> outputs.computeIfAbsent( name, __ -> new ByteArrayOutputStream() ) ) );

final Map<QualifiedName, String> sources = new LinkedHashMap<>();
final List<QualifiedName> loadOrder = new ArrayList<>();
Expand All @@ -84,8 +84,8 @@ private static Map<QualifiedName, Class<?>> generateJavaCode( final File tempDir

private static void writeFile( final String className, final byte[] content, final File targetDirectory ) {
final String fileName = className + ".java";
try {
IOUtils.write( content, Files.newOutputStream( new File( targetDirectory, fileName ).toPath() ) );
try (var stream = Files.newOutputStream( new File( targetDirectory, fileName ).toPath() )) {
IOUtils.write( content, stream );
} catch ( final IOException e ) {
fail( "Could not create file " + fileName );
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@

package org.eclipse.esmf.aspectmodel.resolver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.apache.jena.rdf.model.Model;
import org.eclipse.esmf.aspectmodel.resolver.services.TurtleLoader;

import io.vavr.control.Try;
import org.apache.jena.rdf.model.Model;

/**
* Abstract base class for the implementation of {@link ResolutionStrategy}s.
* Abstract base class for the implementation of {@link ResolutionStrategy}s
*/
public abstract class AbstractResolutionStrategy implements ResolutionStrategy {
/**
Expand All @@ -47,6 +50,11 @@ protected Try<Model> loadFromUri( final URI uri ) {
* @return The model
*/
protected Try<Model> loadFromUrl( final URL url ) {
return Try.ofSupplier( () -> TurtleLoader.openUrl( url ) ).flatMap( TurtleLoader::loadTurtle );
return Try.withResources( url::openStream ).of( TurtleLoader::loadTurtle ).map( Try::get );
}

@Override
public InputStream read( URI uri ) throws Exception {
return new FileInputStream( new File( uri ) );
}
}
Loading

0 comments on commit 430c55f

Please sign in to comment.