From cf576836a6e24746b42b2ac39943c1dd46e38ebb Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:10:11 +0200 Subject: [PATCH 01/16] [#324] Fix the typo in the class name --- .../java/cz/cvut/spipes/config/AuditConfig.java | 6 +++--- .../cvut/spipes/config/CompatibilityConfig.java | 4 ++-- .../cz/cvut/spipes/config/ContextsConfig.java | 6 +++--- .../cz/cvut/spipes/config/ExecutionConfig.java | 16 ++++++++-------- ...gProperies.java => CoreConfigProperties.java} | 8 ++++---- .../cvut/spipes/modules/Rdf4jDeployModule.java | 4 ++-- 6 files changed, 22 insertions(+), 22 deletions(-) rename s-pipes-core/src/main/java/cz/cvut/spipes/util/{CoreConfigProperies.java => CoreConfigProperties.java} (91%) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/config/AuditConfig.java b/s-pipes-core/src/main/java/cz/cvut/spipes/config/AuditConfig.java index 2f851231f..551e80da8 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/config/AuditConfig.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/config/AuditConfig.java @@ -1,16 +1,16 @@ package cz.cvut.spipes.config; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; import java.nio.file.Path; import java.nio.file.Paths; public class AuditConfig { public static Path getResourcesPath() { - return Paths.get(CoreConfigProperies.get("audit.resourcesPath")); + return Paths.get(CoreConfigProperties.get("audit.resourcesPath")); } public static boolean isEnabled() { - return Boolean.parseBoolean(CoreConfigProperies.get("audit.enable")); + return Boolean.parseBoolean(CoreConfigProperties.get("audit.enable")); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/config/CompatibilityConfig.java b/s-pipes-core/src/main/java/cz/cvut/spipes/config/CompatibilityConfig.java index ff851d725..99ad5952b 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/config/CompatibilityConfig.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/config/CompatibilityConfig.java @@ -1,10 +1,10 @@ package cz.cvut.spipes.config; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; public class CompatibilityConfig { public static boolean isLoadSparqlMotionFiles() { - return Boolean.parseBoolean(CoreConfigProperies.get("compatibility.loadSparqlMotionFiles", "false")); + return Boolean.parseBoolean(CoreConfigProperties.get("compatibility.loadSparqlMotionFiles", "false")); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/config/ContextsConfig.java b/s-pipes-core/src/main/java/cz/cvut/spipes/config/ContextsConfig.java index 7a07fab81..a51af2aab 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/config/ContextsConfig.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/config/ContextsConfig.java @@ -1,6 +1,6 @@ package cz.cvut.spipes.config; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -12,8 +12,8 @@ public class ContextsConfig { public static List getScriptPaths() { return Arrays - .stream(CoreConfigProperies.get("contexts.scriptPaths").split(";")) - .map(path -> Paths.get(path)) + .stream(CoreConfigProperties.get("contexts.scriptPaths").split(";")) + .map(Paths::get) .collect(Collectors.toList()); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/config/ExecutionConfig.java b/s-pipes-core/src/main/java/cz/cvut/spipes/config/ExecutionConfig.java index 349ba59a0..e0ca75347 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/config/ExecutionConfig.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/config/ExecutionConfig.java @@ -1,43 +1,43 @@ package cz.cvut.spipes.config; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; import java.nio.file.Path; import java.nio.file.Paths; public class ExecutionConfig { public static Path getTempDirectoryPath() { - return Paths.get(CoreConfigProperies.get("execution.tempDirectoryPath", System.getProperty("java.io.tmpdir"))); + return Paths.get(CoreConfigProperties.get("execution.tempDirectoryPath", System.getProperty("java.io.tmpdir"))); } public static boolean isExitOnError() { - return Boolean.parseBoolean(CoreConfigProperies.get( + return Boolean.parseBoolean(CoreConfigProperties.get( "execution.exitOnError", "false")); } public static boolean isCheckValidationConstrains() { - return Boolean.parseBoolean(CoreConfigProperies.get( + return Boolean.parseBoolean(CoreConfigProperties.get( "execution.validation.checkConstraints", "true")); } public static int getEvidenceNumber() { - return Integer.parseInt(CoreConfigProperies.get("execution.validation.maxNumberOfConstraintFailureEvidences", "3")); + return Integer.parseInt(CoreConfigProperties.get("execution.validation.maxNumberOfConstraintFailureEvidences", "3")); } public static String getConfigUrl() { - return CoreConfigProperies.get("execution.configUrl", "config.ttl"); + return CoreConfigProperties.get("execution.configUrl", "config.ttl"); } public static Environment getEnvironment() { - return Environment.valueOf(CoreConfigProperies.get( + return Environment.valueOf(CoreConfigProperties.get( "execution.environment", Environment.production.toString()) ); } public static String getDevelopmentServiceUrl() { - return CoreConfigProperies.get("execution.developmentServiceUrl", "http://localhost:8080/s-pipes/"); + return CoreConfigProperties.get("execution.developmentServiceUrl", "http://localhost:8080/s-pipes/"); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperies.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperties.java similarity index 91% rename from s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperies.java rename to s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperties.java index 86215298a..34015ca6b 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperies.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/CoreConfigProperties.java @@ -7,15 +7,15 @@ import java.io.IOException; import java.io.InputStream; -public class CoreConfigProperies { +public class CoreConfigProperties { private static final String CONFIG_FILE = "config-core.properties"; private static final java.util.Properties prop = new java.util.Properties(); - private static final Logger log = LoggerFactory.getLogger(CoreConfigProperies.class); + private static final Logger log = LoggerFactory.getLogger(CoreConfigProperties.class); private static final String variableAssignmentPrefix = "variable.assignment"; static { try { - InputStream is = CoreConfigProperies.class.getClassLoader().getResourceAsStream("config-core.properties"); + InputStream is = CoreConfigProperties.class.getClassLoader().getResourceAsStream("config-core.properties"); if (is != null) { prop.load(is); prop.keySet().forEach(k -> { @@ -35,7 +35,7 @@ public class CoreConfigProperies { throw new FileNotFoundException("Property file '" + CONFIG_FILE + "' not found in the classpath"); } } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage()); } } diff --git a/s-pipes-modules/module-rdf4j/src/main/java/cz/cvut/spipes/modules/Rdf4jDeployModule.java b/s-pipes-modules/module-rdf4j/src/main/java/cz/cvut/spipes/modules/Rdf4jDeployModule.java index 7ce454b8f..f09bc0f58 100644 --- a/s-pipes-modules/module-rdf4j/src/main/java/cz/cvut/spipes/modules/Rdf4jDeployModule.java +++ b/s-pipes-modules/module-rdf4j/src/main/java/cz/cvut/spipes/modules/Rdf4jDeployModule.java @@ -5,7 +5,7 @@ import cz.cvut.spipes.engine.ExecutionContextFactory; import cz.cvut.spipes.exception.ModuleConfigurationInconsistentException; import cz.cvut.spipes.modules.annotations.SPipesModule; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; import cz.cvut.spipes.util.JenaUtils; import lombok.extern.slf4j.Slf4j; import org.apache.jena.query.Dataset; @@ -244,7 +244,7 @@ public void loadManualConfiguration() { if (variableName == null) { return null; } - return CoreConfigProperies.getConfigurationVariable(variableName); + return CoreConfigProperties.getConfigurationVariable(variableName); } private boolean isRdf4jContextIRIDefined() { From bdcc2ab1bf082eb35af68dc438d269c6da596fb8 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:11:02 +0200 Subject: [PATCH 02/16] [#324] Refactor s-pipes-core/constants to reduce the number of warnings --- .../src/main/java/cz/cvut/spipes/constants/KBSS_TIMEF.java | 2 +- s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIF.java | 2 +- .../src/main/java/cz/cvut/spipes/constants/SPIPES.java | 4 ++-- s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPL.java | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/KBSS_TIMEF.java b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/KBSS_TIMEF.java index e778d12ce..54de3303c 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/KBSS_TIMEF.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/KBSS_TIMEF.java @@ -10,6 +10,6 @@ public class KBSS_TIMEF { */ public static final String uri = "http://onto.fel.cvut.cz/ontologies/lib/function/time/"; - protected static final Property property(String local ) + protected static Property property(String local) { return ResourceFactory.createProperty( uri, local ); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIF.java b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIF.java index ec70b7292..21969928a 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIF.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIF.java @@ -10,6 +10,6 @@ public class SPIF { */ public static final String uri = "http://spinrdf.org/spif#"; - protected static final Property property(String local ) + protected static Property property(String local) { return ResourceFactory.createProperty( uri, local ); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIPES.java b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIPES.java index ec13bc223..22b1a6c25 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIPES.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPIPES.java @@ -11,10 +11,10 @@ public class SPIPES { */ public static final String uri = "http://onto.fel.cvut.cz/ontologies/s-pipes/"; - protected static final org.apache.jena.rdf.model.Resource resource(String local ) + protected static org.apache.jena.rdf.model.Resource resource(String local) { return ResourceFactory.createResource( uri + local ); } - protected static final Property property(String local ) + protected static Property property(String local) { return ResourceFactory.createProperty( uri, local ); } public static final Resource ProgressListener = resource("progress-listener"); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPL.java b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPL.java index 873eb496c..43ac0ecb8 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPL.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/constants/SPL.java @@ -12,10 +12,10 @@ public class SPL { */ private static final String uri = "http://spinrdf.org/spl#"; - protected static final Resource resource(String local ) + protected static Resource resource(String local) { return ResourceFactory.createResource( uri + local ); } - protected static final Property property(String local ) + protected static Property property(String local) { return ResourceFactory.createProperty( uri, local ); } public static final Resource tarql = resource("Argument"); From 631f20fd811b748901d64401526d8d9cb1b4b320 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:11:30 +0200 Subject: [PATCH 03/16] [#324] Refactor s-pipes-core/engine to reduce the number of warnings --- .../cvut/spipes/engine/ExecutionContext.java | 2 +- .../engine/ExecutionContextFactory.java | 4 +- .../spipes/engine/ExecutionEngineImpl.java | 17 ++--- .../cvut/spipes/engine/PipelineFactory.java | 74 +++++++++---------- .../cvut/spipes/engine/ProgressListener.java | 4 +- .../cvut/spipes/engine/VariablesBinding.java | 11 +-- .../spipes/engine/PipelineFactoryTest.java | 2 +- .../spipes/engine/VariablesBindingTest.java | 48 ++++++------ 8 files changed, 71 insertions(+), 91 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContext.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContext.java index 5ea321398..01343618a 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContext.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContext.java @@ -74,5 +74,5 @@ public interface ExecutionContext { // TODO named graphs ? -- in merge rather having multiple graphs (for debugging) // TODO variable binding supporting stream etc .. ? - // TODO prefixe map ?? + // TODO prefix map ?? } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContextFactory.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContextFactory.java index f64fca314..ae39f47c0 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContextFactory.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionContextFactory.java @@ -8,9 +8,7 @@ public class ExecutionContextFactory { - /** - * @return - */ + public static ExecutionContext createEmptyContext() { ExecutionContextImpl context = new ExecutionContextImpl(); context.setDefaultModel(ModelFactory.createDefaultModel()); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionEngineImpl.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionEngineImpl.java index 8f658ce76..8dc20cb36 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionEngineImpl.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ExecutionEngineImpl.java @@ -53,7 +53,7 @@ private ExecutionContext _executePipeline(long pipelineExecutionId, Module modul return module.getOutputContext(); } - // module has no predeccesor + // module has no predecessor if (module.getInputModules().isEmpty()) { fire((l) -> {l.moduleExecutionStarted(pipelineExecutionId, moduleExecutionId, module, context, predecessorId); return null;}); @@ -62,7 +62,7 @@ private ExecutionContext _executePipeline(long pipelineExecutionId, Module modul } else { module.setInputContext(context); - log.info(" ##### " + module.getLabel()); + log.info(" ##### {}", module.getLabel()); if (log.isTraceEnabled()) { log.trace("Using input context {}", context.toTruncatedSimpleString()); //TODO redundant code -> merge } @@ -80,7 +80,7 @@ private ExecutionContext _executePipeline(long pipelineExecutionId, Module modul .collect(Collectors.toMap(Module::getResource, mod -> this._executePipeline(pipelineExecutionId, mod, context, moduleExecutionId))); - log.info(" ##### " + module.getLabel()); + log.info(" ##### {}", module.getLabel()); ExecutionContext mergedContext = mergeContexts(resource2ContextMap); if (log.isTraceEnabled()) { log.trace("Using input merged context {}", mergedContext.toTruncatedSimpleString()); @@ -114,21 +114,18 @@ private ExecutionContext mergeContexts(Map resource2 VariablesBinding variablesBinding = new VariablesBinding(); - resource2ContextMap.entrySet().stream().forEach(e -> { - - Resource modRes = e.getKey(); - ExecutionContext context = e.getValue(); + resource2ContextMap.forEach((modRes, context) -> { // merge models newModel.add(context.getDefaultModel()); // merge variable bindings - VariablesBinding b = e.getValue().getVariablesBinding(); + VariablesBinding b = context.getVariablesBinding(); VariablesBinding conflictingBinding = variablesBinding.extendConsistently(b); - if (! conflictingBinding.isEmpty()) { - log.warn("Module {} has conflicting variables binding {} with sibling modules ocurring in pipeline. ", modRes, context); + if (!conflictingBinding.isEmpty()) { + log.warn("Module {} has conflicting variables binding {} with sibling modules occurring in pipeline. ", modRes, context); } }); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/PipelineFactory.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/PipelineFactory.java index 16996bc33..634edff56 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/PipelineFactory.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/PipelineFactory.java @@ -21,20 +21,18 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.nio.file.Path; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; public class PipelineFactory { private static final Logger log = LoggerFactory.getLogger(PipelineFactory.class); - // TODO inheritence not involved, not static context - static Map> moduleTypes = new HashMap<>(); + // TODO inheritance not involved, not static context + static final Map> moduleTypes = new HashMap<>(); //TODO move to ModuleRegistry static { @@ -75,7 +73,7 @@ public static void registerModuleTypesOnClassPath() { List> moduleClasses = reflections.getSubTypesOf(Module.class).stream().filter( c -> !Modifier.isAbstract(c.getModifiers()) - ).collect(Collectors.toList()); + ).toList(); moduleClasses.forEach( mClass -> { @@ -96,7 +94,7 @@ public static void registerFunctionsOnClassPath() { List> functionClasses = reflections.getSubTypesOf(ARQFunction.class).stream().filter( c -> !Modifier.isAbstract(c.getModifiers()) - ).collect(Collectors.toList()); + ).toList(); functionClasses.forEach( fClass -> { @@ -124,13 +122,13 @@ public static Module loadModule(@NotNull Resource moduleRes) { // TODO not very effective public static Module loadPipeline(@NotNull Resource resource) { return loadPipelines(resource.getModel()).stream().filter(m -> { - //TODO does not work on annonymous node + //TODO does not work on anonymous node return resource.getURI().equals(m.getResource().getURI()); }).findAny().orElse(null); } /** - * @param configModel + * @param configModel configuration model containing pipeline definition * @return List of output modules. */ public static List loadPipelines(@NotNull Model configModel) { @@ -139,7 +137,7 @@ public static List loadPipelines(@NotNull Model configModel) { Set inputModulesSet = res2ModuleMap.values().stream().flatMap(m -> m.getInputModules().stream()).collect(Collectors.toSet()); - List outputModulesList = res2ModuleMap.values().stream().collect(Collectors.toList()); + List outputModulesList = new ArrayList<>(res2ModuleMap.values()); outputModulesList.removeAll(inputModulesSet); return outputModulesList; @@ -151,37 +149,31 @@ private static Map loadAllModules(@NotNull Model configModel) Map res2ModuleMap = new HashMap<>(); JenaPipelineUtils.getAllModulesWithTypes(configModel) - .entrySet() - .forEach(e -> { - Module m = loadModule(e.getKey(), e.getValue()); + .forEach((key, value) -> { + Module m = loadModule(key, value); if (m != null) { - res2ModuleMap.put(e.getKey(), m); + res2ModuleMap.put(key, m); } }); // .collect(Collectors.toMap(Map.Entry::getKey, e -> loadModule(e.getKey(), e.getValue()))); // set appropriate links //TODO problem 2 files reusing module inconsistently ? do i need to solve it ? - res2ModuleMap.entrySet() - .forEach(e -> { - Resource res = e.getKey(); - - // set up input modules - res.listProperties(SM.JENA.next).toList().stream() - .map(st -> { - Module m = res2ModuleMap.get(st.getObject().asResource()); - if (m == null) { - log.error("Ignoring statement {}. The object of the triple must have rdf:type {}.", st, SM.Module); - } - return m; - }).filter(m -> (m != null)).forEach( - m -> { - - m.getInputModules().add(e.getValue()); - } + res2ModuleMap.forEach((res, value) -> { + + // set up input modules + res.listProperties(SM.JENA.next).toList().stream() + .map(st -> { + Module m = res2ModuleMap.get(st.getObject().asResource()); + if (m == null) { + log.error("Ignoring statement {}. The object of the triple must have rdf:type {}.", st, SM.Module); + } + return m; + }).filter(Objects::nonNull).forEach( + m -> m.getInputModules().add(value) ); - }); + }); return res2ModuleMap; } @@ -195,12 +187,12 @@ private static Module loadModule(@NotNull Resource moduleRes, @NotNull Resource return null; } - Module module = null; + Module module; try { - module = moduleClass.newInstance(); + module = moduleClass.getDeclaredConstructor().newInstance(); module.setConfigurationResource(moduleRes); - } catch (InstantiationException | IllegalAccessException e) { + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException("Could not instantiate module of type " + moduleTypeRes, e); } @@ -209,16 +201,16 @@ private static Module loadModule(@NotNull Resource moduleRes, @NotNull Resource public static Module instantiateModule(Class moduleClass) { try { - return moduleClass.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { + return moduleClass.getDeclaredConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException("Could not instantiate module of type " + moduleClass); } } public static ARQFunction instantiateFunction(Class functionClass) { try { - return functionClass.newInstance(); - } catch (InstantiationException | IllegalAccessException e) { + return functionClass.getDeclaredConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException("Could not instantiate function of type " + functionClass); } } @@ -232,7 +224,7 @@ public static Module loadModule(@NotNull Path configFilePath, @NotNull String mo configModel.read(new FileInputStream(configFilePath.toFile()), null, FileUtils.langTurtle); return PipelineFactory.loadModule(configModel.createResource(moduleResourceUri)); } catch (FileNotFoundException e) { - e.printStackTrace(); + log.error("Loading of module failed.", e); throw new RuntimeException("Loading of module failed."); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ProgressListener.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ProgressListener.java index 41b9521a1..c36ddc379 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ProgressListener.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/ProgressListener.java @@ -4,7 +4,7 @@ /** * Progress listener applicable to pipeline executions. - * + *

* Following variables are defined within interface: * pipelineExecutionId -- is unique id whose identity is defined by event of execution of a pipeline. * moduleExecutionId -- is unique id whose identity is defined by pipeline execution, module's instance and input context of the module. @@ -35,7 +35,7 @@ public interface ProgressListener { * @param predecessorModuleExecutionId execution id of a module that triggered execution * of this module. This module will be executed before * its predecessor module as the predecessor module might - * use output of this module. + * use the output of this module. */ void moduleExecutionStarted(long pipelineExecutionId, String moduleExecutionId, Module outputModule, ExecutionContext inputContext, String predecessorModuleExecutionId); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/VariablesBinding.java b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/VariablesBinding.java index c90c9add8..b23973453 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/engine/VariablesBinding.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/engine/VariablesBinding.java @@ -9,7 +9,6 @@ import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.engine.binding.BindingBuilder; -import org.apache.jena.sparql.engine.binding.BindingFactory; import org.apache.jena.vocabulary.RDF; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; @@ -27,7 +26,7 @@ public class VariablesBinding { private static final Logger log = LoggerFactory.getLogger(VariablesBinding.class); private static final int MAX_TRUNCATED_VALUE_SIZE = 300; - QuerySolutionMap binding = new QuerySolutionMap(); + final QuerySolutionMap binding = new QuerySolutionMap(); public VariablesBinding() { } @@ -63,8 +62,6 @@ public QuerySolution asQuerySolution() { } public Binding asBinding() { - if(binding == null) - return BindingFactory.empty(); BindingBuilder bb = BindingBuilder.create(); binding.varNames().forEachRemaining(v -> bb.add(Var.alloc(v), binding.get(v).asNode())); return bb.build(); @@ -106,8 +103,8 @@ public VariablesBinding extendConsistently(VariablesBinding newVarsBinding) { } /** - * Returns new variables binding from this variables binding restricted to listed variables. - * @param varNames Names of variables that should be copied from this variables binding. + * Returns new variables binding from these variables binding restricted to listed variables. + * @param varNames Names of variables that should be copied from these variables binding. * @return new variables binding */ public VariablesBinding restrictTo(@NotNull List varNames) { @@ -125,7 +122,7 @@ public VariablesBinding restrictTo(@NotNull List varNames) { } /** - * Returns new variables binding from this variables binding restricted to listed variables. + * Returns new variables binding from these variables binding restricted to listed variables. * @param varNames Names of variables that should be copied to the new binding. * @return new variables binding */ diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/engine/PipelineFactoryTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/engine/PipelineFactoryTest.java index 8beacc4b0..4a7fbf7e0 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/engine/PipelineFactoryTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/engine/PipelineFactoryTest.java @@ -12,7 +12,7 @@ public class PipelineFactoryTest { @Test - public void loadPipelines() throws Exception { + public void loadPipelines() { JenaTestUtils.mapLocalSPipesDefinitionFiles(); OntModel ontModel = JenaTestUtils.loadOntologyClosureFromResources("/pipeline/config.ttl"); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/engine/VariablesBindingTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/engine/VariablesBindingTest.java index 9d91b6c52..eaf7c06c5 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/engine/VariablesBindingTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/engine/VariablesBindingTest.java @@ -11,7 +11,6 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; -import cz.cvut.spipes.util.JenaUtils; import org.apache.jena.rdf.model.ResourceFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -31,35 +30,34 @@ public void restrictToReturnsOnlyListedVariables() { vb.add("var3", ResourceFactory.createStringLiteral("value3")); vb.add("var4", ResourceFactory.createStringLiteral("value4")); VariablesBinding newVB = vb.restrictTo("var2", "var4"); - assertEquals(getSize(newVB), 2); + assertEquals(2, getSize(newVB)); assertNotNull(newVB.asQuerySolution().get("var2")); assertNotNull(newVB.asQuerySolution().get("var4")); - assertEquals(newVB.asQuerySolution().get("var2").toString(), "value2"); - assertEquals(newVB.asQuerySolution().get("var4").toString(), "value4"); + assertEquals("value2", newVB.asQuerySolution().get("var2").toString()); + assertEquals("value4", newVB.asQuerySolution().get("var4").toString()); } @Test - public void loadMultipleBindings() throws Exception { + public void loadMultipleBindings() throws IOException { final VariablesBinding vb = new VariablesBinding(); - final InputStream is = this.getClass().getResourceAsStream("/engine/variables-binding-test-1.ttl"); - IOException thrown = assertThrows(IOException.class, - () -> { - vb.load(is, "TURTLE"); - }); - assertTrue(thrown.getMessage().contains("1 was expected")); + try (InputStream is = this.getClass().getResourceAsStream("/engine/variables-binding-test-1.ttl")) { + IOException thrown = assertThrows(IOException.class, + () -> vb.load(is, "TURTLE")); + assertTrue(thrown.getMessage().contains("1 was expected")); + } } @Test - public void loadNoBinding() throws Exception { + public void loadNoBinding() throws IOException { final VariablesBinding vb = new VariablesBinding(); - final InputStream is = this.getClass().getResourceAsStream("/engine/variables-binding-test-2.ttl"); - IOException thrown = assertThrows(IOException.class, - () -> { - vb.load(is, "TURTLE"); - }); - assertTrue(thrown.getMessage().contains("1 was expected")); + try (InputStream is = this.getClass().getResourceAsStream("/engine/variables-binding-test-2.ttl")) { + IOException thrown = assertThrows(IOException.class, + () -> vb.load(is, "TURTLE")); + assertTrue(thrown.getMessage().contains("1 was expected")); + } } + @Test public void loadCorrectBindingWithTwoVariables() throws Exception { final VariablesBinding vb = new VariablesBinding(); @@ -67,7 +65,7 @@ public void loadCorrectBindingWithTwoVariables() throws Exception { vb.load(is, "TURTLE"); - assertEquals(iteratorToStream(vb.asQuerySolution().varNames()).count(), 2); + assertEquals(2, iteratorToStream(vb.asQuerySolution().varNames()).count()); } @Test @@ -84,11 +82,11 @@ public void saveAndLoadBinding() throws Exception { final VariablesBinding vb2 = new VariablesBinding(); vb2.load(new FileInputStream(f), "TURTLE"); - assertEquals(iteratorToStream(vb.asQuerySolution().varNames()).count(), 3); + assertEquals(3, iteratorToStream(vb.asQuerySolution().varNames()).count()); - assertEquals(vb.asQuerySolution().get("x").asResource().getURI(), "http://example.org/test-resource"); - assertEquals(vb.asQuerySolution().get("y").asLiteral().getString(), "plain literal"); - assertEquals(vb.asQuerySolution().get("z").asLiteral().getString(), "plain literal 2"); + assertEquals("http://example.org/test-resource", vb.asQuerySolution().get("x").asResource().getURI()); + assertEquals("plain literal", vb.asQuerySolution().get("y").asLiteral().getString()); + assertEquals("plain literal 2", vb.asQuerySolution().get("z").asLiteral().getString()); } private Stream iteratorToStream(final Iterator iterator) { @@ -100,9 +98,7 @@ private Stream iteratorToStream(final Iterator iterator) { private int getSize(VariablesBinding newVB) { final Integer[] countRef = {0}; newVB.getVarNames().forEachRemaining( - n -> { - countRef[0]++; - } + n -> countRef[0]++ ); return countRef[0]; } From 3acc32ba898c5e0a6b4450dbd7e1d7a09f698479 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:12:28 +0200 Subject: [PATCH 04/16] [#324] Refactor s-pipes-core/exception to reduce the number of warnings --- .../ModuleConfigurationInconsistentException.java | 2 +- .../cvut/spipes/exception/ResourceNotFoundException.java | 7 +------ .../exception/ValidationConstraintFailedException.java | 5 +---- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ModuleConfigurationInconsistentException.java b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ModuleConfigurationInconsistentException.java index 895a7f8b2..a2a107065 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ModuleConfigurationInconsistentException.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ModuleConfigurationInconsistentException.java @@ -1,7 +1,7 @@ package cz.cvut.spipes.exception; /** - * Indicate that SPipes Module was incorrectly configured. + * Indicate that the SPipes Module was incorrectly configured. */ public class ModuleConfigurationInconsistentException extends SPipesException { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ResourceNotFoundException.java b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ResourceNotFoundException.java index e7d253b02..7e44d9c99 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ResourceNotFoundException.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ResourceNotFoundException.java @@ -1,14 +1,9 @@ package cz.cvut.spipes.exception; -/** - * Exception thrown when a resource is not found. - * - */ - import java.util.Set; /** - * + * Exception thrown when a resource is not found. */ public class ResourceNotFoundException extends SPipesException { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ValidationConstraintFailedException.java b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ValidationConstraintFailedException.java index f5f02947b..ffe04eb5d 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ValidationConstraintFailedException.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/exception/ValidationConstraintFailedException.java @@ -4,7 +4,6 @@ import cz.cvut.spipes.util.RDFNodeUtils; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; -import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.*; @@ -117,9 +116,7 @@ private void buildRows(StringBuilder tableBuilder, String format) { private void buildSeparator(StringBuilder tableBuilder, Map columnWidths) { StringBuilder separator = new StringBuilder("+"); for (int width : columnWidths.values()) { - for (int i = 0; i < width + 2; i++) { - separator.append("-"); - } + separator.append("-".repeat(Math.max(0, width + 2))); separator.append("+"); } tableBuilder.append(separator).append(System.lineSeparator()); From d56c3a8e76ecc5c15638006a5236255182270ba6 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:12:51 +0200 Subject: [PATCH 05/16] [#324] Refactor s-pipes-core/function to reduce the number of warnings --- .../main/java/cz/cvut/spipes/function/time/AddDays.java | 9 +++++++-- .../java/cz/cvut/spipes/function/date/ParseDateTest.java | 5 ++--- .../java/cz/cvut/spipes/function/time/DurationTest.java | 1 - 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/function/time/AddDays.java b/s-pipes-core/src/main/java/cz/cvut/spipes/function/time/AddDays.java index 6d2b8b0b6..369788bf7 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/function/time/AddDays.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/function/time/AddDays.java @@ -8,20 +8,24 @@ import org.apache.jena.datatypes.xsd.impl.XSDDateType; import org.apache.jena.sparql.expr.NodeValue; import org.apache.jena.sparql.function.FunctionBase2; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.LocalDate; import java.time.format.DateTimeParseException; import java.util.Optional; /** - * Extend specified `date` by number of `days`. Return typed literal with same datatype. - * Currently, supports only xsd:date datatype. + * Extend the specified `date` by number of `days`. Return typed literal with the same datatype. + * Currently, it supports only xsd:date datatype. */ public class AddDays extends FunctionBase2 implements ValueFunction { private static final String TYPE_IRI = KBSS_TIMEF.uri + "add-days"; + private static final Logger log = LoggerFactory.getLogger(AddDays.class); + @Override public String getTypeURI() { return TYPE_IRI; @@ -40,6 +44,7 @@ public NodeValue exec(NodeValue date, NodeValue days) { return NodeValue.makeNode(newDate, datatype); } } catch (DateTimeParseException e){ + log.warn("Cannot parse date: {}", date.asNode().getLiteral().getValue().toString()); } return null; diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/function/date/ParseDateTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/function/date/ParseDateTest.java index 4627cdc8d..3b0d96f5e 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/function/date/ParseDateTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/function/date/ParseDateTest.java @@ -2,7 +2,6 @@ import cz.cvut.spipes.exception.ParseException; import cz.cvut.spipes.function.spif.ParseDate; -import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.datatypes.xsd.XSDDatatype; import org.apache.jena.graph.NodeFactory; import org.apache.jena.query.QueryExecution; @@ -191,7 +190,7 @@ public void execThrowsExceptionWhenPatternNotCompliantWithPatternLanguage() { public void execThrowsExceptionWhenPatternIsUriNode() { ParseDate parseDate = new ParseDate(); NodeValue text = createLiteral("19/12/2016"); - NodeValue pattern = createURI("htttp://example.org/person"); + NodeValue pattern = createURI("http://example.org/person"); assertThrows(LiteralRequiredException.class, () -> parseDate.exec(text, pattern, null) @@ -256,7 +255,7 @@ private NodeValue getNode(String text, XSDDatatype type) { return NodeValue.makeNode( text, null, - ((RDFDatatype) type).getURI() + type.getURI() ); } diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/function/time/DurationTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/function/time/DurationTest.java index c7bbea43d..2f3923589 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/function/time/DurationTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/function/time/DurationTest.java @@ -2,7 +2,6 @@ import org.apache.jena.datatypes.RDFDatatype; import org.apache.jena.datatypes.xsd.XSDDatatype; -import org.apache.jena.graph.Node; import org.apache.jena.sparql.expr.NodeValue; import org.junit.jupiter.api.Test; From dac6462bde8b03dc42109dea6c2758663306d803 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:13:18 +0200 Subject: [PATCH 06/16] [#324] Refactor s-pipes-core/logging to reduce the number of warnings --- .../logging/AdvancedLoggingProgressListener.java | 15 +++++---------- .../cz/cvut/spipes/logging/FileSystemLogger.java | 7 ++++++- .../spipes/logging/RDF4JPersistenceFactory.java | 3 +-- .../logging/SemanticLoggingProgressListener.java | 4 ++-- .../java/cz/cvut/spipes/logging/LoggingTest.java | 4 ++-- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/AdvancedLoggingProgressListener.java b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/AdvancedLoggingProgressListener.java index 48f6b7881..9f04d06ae 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/AdvancedLoggingProgressListener.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/AdvancedLoggingProgressListener.java @@ -59,7 +59,7 @@ public class AdvancedLoggingProgressListener implements ProgressListener { Vocabulary.ONTOLOGY_IRI_DATASET_DESCRIPTOR + "/has-part"; private static final String P_HAS_NEXT = Vocabulary.ONTOLOGY_IRI_DATASET_DESCRIPTOR + "/has-next"; - private static final String P_HAS_INPUT_BINDDING = + private static final String P_HAS_INPUT_BINDING = Vocabulary.ONTOLOGY_IRI_DATASET_DESCRIPTOR + "/has-input-binding"; private static final String LOCAL_NAME = "advanced-logging-progress-listener"; private static final String PREFIX_IRI = SPIPES.uri + LOCAL_NAME + "/"; @@ -163,7 +163,7 @@ private void persistPipelineExecutionFinished2(final EntityManager em, final lon } writer.endRDF(); } catch (IOException e) { - e.printStackTrace(); + log.error("Error while trying to persist pipeline execution finished", e); } entityManagerMap.remove(em); em.close(); @@ -326,7 +326,7 @@ public void moduleExecutionFinished(long pipelineExecutionId, final String modul ); addProperty( moduleExecution, - ResourceFactory.createProperty(P_HAS_INPUT_BINDDING), + ResourceFactory.createProperty(P_HAS_INPUT_BINDING), URI.create(inputBindings.getId()) ); @@ -349,9 +349,7 @@ public void moduleExecutionFinished(long pipelineExecutionId, final String modul } private void mergeAll(EntityManager em, EntityDescriptor pd, Thing... thing) { - Arrays.stream(thing).forEach(t -> { - em.merge(t, pd); - }); + Arrays.stream(thing).forEach(t -> em.merge(t, pd)); } private void writeRawData(EntityManager em, URI contextUri, Model model) { @@ -533,10 +531,7 @@ private boolean hasProperty(@NotNull Thing thing, @NotNull Property property) { if (!thing.getProperties().containsKey(property.toString())) { return false; } - if (thing.getProperties().get(property.toString()).isEmpty()) { - return false; - } - return true; + return !thing.getProperties().get(property.toString()).isEmpty(); } private Object getSingletonPropertyValue(@NotNull Thing thing, @NotNull Property property) { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/FileSystemLogger.java b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/FileSystemLogger.java index a20cecadd..1e22c7efe 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/FileSystemLogger.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/FileSystemLogger.java @@ -1,6 +1,8 @@ package cz.cvut.spipes.logging; import cz.cvut.spipes.util.TempFileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; @@ -10,11 +12,14 @@ class FileSystemLogger { private static Path root; + private static final Logger log = + LoggerFactory.getLogger(FileSystemLogger.class); + static { try { root = Files.createTempDirectory(TempFileUtils.createTimestampFileName("-s-pipes-log-")); } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage()); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/RDF4JPersistenceFactory.java b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/RDF4JPersistenceFactory.java index 0ada51cd0..5fd2462d5 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/RDF4JPersistenceFactory.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/RDF4JPersistenceFactory.java @@ -19,10 +19,9 @@ private RDF4JPersistenceFactory() { public static @NotNull EntityManagerFactory getEntityManagerFactory(String persistenceUnitName, String rdf4jServerUrl, String repositoryName) { - final Map props = new HashMap<>(); String rdf4jRepositoryUrl = rdf4jServerUrl + "/repositories/" + repositoryName; - props.putAll(getInitialParams()); + final Map props = new HashMap<>(getInitialParams()); props.put(JOPAPersistenceProperties.ONTOLOGY_PHYSICAL_URI_KEY, rdf4jRepositoryUrl ); return Persistence.createEntityManagerFactory(persistenceUnitName, props); } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/SemanticLoggingProgressListener.java b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/SemanticLoggingProgressListener.java index 6572d233d..0a17504a5 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/logging/SemanticLoggingProgressListener.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/logging/SemanticLoggingProgressListener.java @@ -106,7 +106,7 @@ public SemanticLoggingProgressListener(Resource configResource) { } writer.endRDF(); } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage()); } entityManagerMap.remove(em); em.close(); @@ -181,7 +181,7 @@ private Path getDir(final long pipelineExecutionId) { } private String saveModelToFile(Path dir, String fileName, Model model) { - File file = null; + File file; try { file = Files.createFile(dir.resolve(TempFileUtils.createTimestampFileName(fileName))).toFile(); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/logging/LoggingTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/logging/LoggingTest.java index 45b11cc94..b0c4867eb 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/logging/LoggingTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/logging/LoggingTest.java @@ -43,8 +43,8 @@ private void logNoOp3() { @Test public void testThreadConcurrence() { final ExecutorService s = Executors.newFixedThreadPool(2); - s.submit(() -> logNoOp3()); - s.submit(() -> logNoOp3()); + s.submit(this::logNoOp3); + s.submit(this::logNoOp3); s.shutdown(); try { s.awaitTermination(1, TimeUnit.MINUTES); From b0cfac96ee582d86b965a9de52e21095aab2d730 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:15:13 +0200 Subject: [PATCH 07/16] [#324] Refactor s-pipes-core/manager to reduce the number of warnings --- .../cz/cvut/spipes/manager/SPipesScriptManager.java | 8 ++++---- .../spipes/manager/factory/ContextLoaderHelper.java | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/manager/SPipesScriptManager.java b/s-pipes-core/src/main/java/cz/cvut/spipes/manager/SPipesScriptManager.java index 1bcb1f3e7..e36e93e5b 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/manager/SPipesScriptManager.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/manager/SPipesScriptManager.java @@ -22,10 +22,10 @@ /** * Registers resources to contexts. - * + *

* resource -> location * alternative id -> location - * + *

* TODO resource registry * */ @@ -50,7 +50,7 @@ private void registerAll(OntologyDocumentManager ontoDocManager, Collection globalScript) { - this.globalScripts = new HashSet(globalScript); + this.globalScripts = new HashSet<>(globalScript); registerAll(ontoDocManager, this.globalScripts); } @@ -96,7 +96,7 @@ public OntModel getScriptByContextId(String contextId){ } - //TODO !!!! shold not be implemented here + //TODO !!!! should not be implemented here private Resource getReturnModule(Resource functionResource) { return JenaPipelineUtils.getAllFunctionsWithReturnModules(functionResource.getModel()).get(functionResource); } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/manager/factory/ContextLoaderHelper.java b/s-pipes-core/src/main/java/cz/cvut/spipes/manager/factory/ContextLoaderHelper.java index 1f7e4223d..2f5d90ace 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/manager/factory/ContextLoaderHelper.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/manager/factory/ContextLoaderHelper.java @@ -4,7 +4,7 @@ import cz.cvut.spipes.manager.OntoDocManager; import cz.cvut.spipes.manager.OntologyDocumentManager; import cz.cvut.spipes.manager.SPipesScriptManager; -import cz.cvut.spipes.util.CoreConfigProperies; +import cz.cvut.spipes.util.CoreConfigProperties; import org.apache.jena.util.LocationMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,8 +20,8 @@ public class ContextLoaderHelper { // TODO should not point to scriptManager /** - * Reloads those contexts (i.e. files) whose time stamp is newer than the time stamp of the last reload. - * @param scriptManager + * Reloads those contexts (i.e., files) whose time stamp is newer than the time stamp of the last reload. + * @param scriptManager Script manager to reload the scripts. */ public static void updateContextsIfNecessary(SPipesScriptManager scriptManager) { if (isKeepUpdated()) { @@ -35,7 +35,7 @@ public static void updateContextsIfNecessary(SPipesScriptManager scriptManager) /** * Registers all scripts from contexts.scriptPaths variable and return those files that - * represents global scripts (i.e. ending with sms.ttl). + * represents global scripts (i.e., ending with sms.ttl). * * @param ontDocManager Ontology document manager to register the scripts. * @return List of baseIRIs of global scripts. @@ -52,7 +52,7 @@ public static List registerGlobalScripts(OntologyDocumentManager ontDocM ontoUri -> { String loc = locMapper.getAltEntry(ontoUri); if (loc.endsWith(".sms.ttl")) { - log.info("Registering script from file " + loc + "."); + log.info("Registering script from file {}.", loc); _globalScripts.add(ontoUri); } } @@ -61,7 +61,7 @@ public static List registerGlobalScripts(OntologyDocumentManager ontDocM } public static boolean isKeepUpdated() { - return Boolean.parseBoolean(CoreConfigProperies.get("contextsLoader.data.keepUpdated")); + return Boolean.parseBoolean(CoreConfigProperties.get("contextsLoader.data.keepUpdated")); } } From 9ffd8427780a4a01b3a8011f785b0f6b03065f3a Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:15:57 +0200 Subject: [PATCH 08/16] [#324] Refactor s-pipes-core/modules/handlers to reduce the number of warnings --- .../modules/handlers/BaseRDFNodeHandler.java | 5 ++-- .../modules/handlers/CharacterHandler.java | 2 +- .../modules/handlers/DefaultHandler.java | 6 ++-- .../spipes/modules/handlers/FieldSetter.java | 2 +- .../cvut/spipes/modules/handlers/Handler.java | 2 +- .../modules/handlers/HandlerRegistry.java | 29 ++++++++++++------- .../spipes/modules/handlers/ListSetter.java | 2 +- .../spipes/modules/handlers/PathHandler.java | 1 - .../modules/handlers/RDFNodeHandler.java | 1 - .../modules/handlers/ResourceHandler.java | 1 - .../handlers/StreamResourceHandler.java | 2 +- .../modules/handlers/StringHandler.java | 1 - .../handlers/BaseRDFNodeHandlerTest.java | 4 +-- .../modules/handlers/BooleanHandlerTest.java | 3 -- .../modules/handlers/FieldSetterTest.java | 16 +++++----- .../modules/handlers/ListHandlerTest.java | 10 +++++-- .../modules/handlers/ListSetterTest.java | 4 +-- .../modules/handlers/PathHandlerTest.java | 2 -- .../modules/handlers/URLHandlerTest.java | 8 ++--- 19 files changed, 50 insertions(+), 51 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandler.java index 2235ea5c2..f0afe62ea 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandler.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandler.java @@ -6,7 +6,6 @@ import org.apache.jena.rdf.model.Property; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.Resource; -import org.apache.jena.rdf.model.Statement; import java.util.Optional; @@ -26,7 +25,7 @@ public BaseRDFNodeHandler(Resource resource, ExecutionContext executionContext, /** * Retrieves the effective RDF node value for a given property from the current resource. - * + *

* This method first attempts to retrieve the RDF node associated with the specified property from * the current resource. If the retrieved node is an RDF expression, it evaluates the expression * using the current execution context and variable bindings. If the node is not an expression, it @@ -51,7 +50,7 @@ public RDFNode getEffectiveValue(Property property) { /** * Checks if the given property is assigned a value in the current resource. - * + *

* This method verifies whether the current resource has an RDF property assignment for the specified * property. It returns {@code true} if the resource has a value for the property, and {@code false} * otherwise. This is useful for determining if there is an existing value before attempting to diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/CharacterHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/CharacterHandler.java index 46439e1b1..255f64402 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/CharacterHandler.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/CharacterHandler.java @@ -11,7 +11,7 @@ public CharacterHandler(Resource resource, ExecutionContext executionContext, Se } @Override - Character getRDFNodeValue(RDFNode node) throws Exception { + Character getRDFNodeValue(RDFNode node) { return node.asLiteral().getChar(); } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/DefaultHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/DefaultHandler.java index 60fabfc38..141079047 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/DefaultHandler.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/DefaultHandler.java @@ -9,11 +9,11 @@ * It delegates the handling responsibility to the {@link Handler} class registered for the field type * within the {@link HandlerRegistry}. **/ -public class DefaultHandler extends Handler { +public class DefaultHandler extends Handler { - private Handler typeHandler; + private final Handler typeHandler; - public DefaultHandler(Resource resource, ExecutionContext executionContext, Setter setter) { + public DefaultHandler(Resource resource, ExecutionContext executionContext, Setter setter) { super(resource, executionContext, setter); HandlerRegistry handlerRegistry = HandlerRegistry.getInstance(); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/FieldSetter.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/FieldSetter.java index f921b245d..de1e4c4d9 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/FieldSetter.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/FieldSetter.java @@ -2,7 +2,7 @@ import java.lang.reflect.Field; -public class FieldSetter extends Setter { +public class FieldSetter extends Setter { public FieldSetter(Field f, Object bean) { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/Handler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/Handler.java index edde56560..c94392afd 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/Handler.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/Handler.java @@ -8,7 +8,7 @@ /** * Abstract class for handler that is responsible to load native Java value * from its RDF representation and set this value using provided {@link Setter}. - * + *

* The class is initialized with: * - {@link Resource} and {@link ExecutionContext} which provides partial context from which RDF value can be extracted * - {@link Setter} which is used to set native Java value into exactly one Java field diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/HandlerRegistry.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/HandlerRegistry.java index bdffc06ef..c3e820b89 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/HandlerRegistry.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/HandlerRegistry.java @@ -22,7 +22,7 @@ * The `HandlerRegistry` initializes and registers handlers for common data types, * and it provides a mechanism to register custom handlers as needed. * - *

The registry is thread-safe, ensuring consistent behavior in multi-threaded environments. + *

The registry is thread-safe, ensuring consistent behavior in multithreaded environments. * *

Usage example: *

@@ -35,7 +35,7 @@
 public class HandlerRegistry {
 
     private static HandlerRegistry instance;
-    private final Map handlers =  Collections.synchronizedMap(new HashMap<>());
+    private final Map, HandlerFactory> handlers =  Collections.synchronizedMap(new HashMap<>());
 
     public synchronized static HandlerRegistry getInstance() {
         if (instance == null) {
@@ -65,7 +65,7 @@ private void initHandlers() {
         registerHandler(StreamResource.class, StreamResourceHandler.class);
     }
 
-    public synchronized Handler getHandler(Class clazz, Resource resource, ExecutionContext context, Setter setter) {
+    public synchronized Handler getHandler(Class clazz, Resource resource, ExecutionContext context, Setter setter) {
         HandlerFactory handlerFactory = handlers.get(clazz);
         if (handlerFactory == null) {
             throw new RuntimeException("No handler for " + clazz);
@@ -74,7 +74,7 @@ public synchronized Handler getHandler(Class clazz, Resource resource, Execution
     }
 
 
-    private static Constructor getConstructor(Class handler){
+    private static Constructor> getConstructor(Class> handler){
         try {
             return handler.getConstructor(Resource.class, ExecutionContext.class, Setter.class);
         } catch (NoSuchMethodException e) {
@@ -82,7 +82,7 @@ private static Constructor getConstructor(Class handlerClass) {
+    public synchronized void registerHandler(Class valueType, Class> handlerClass) {
         handlers.put(valueType, new DefaultConstructorHandlerFactory(handlerClass));
     }
 
@@ -91,23 +91,31 @@ public synchronized void registerHandler(Class valueType, Class getHandler(Resource resource, ExecutionContext executionContext, Setter setter);
+        Handler getHandler(Resource resource, ExecutionContext executionContext, Setter setter);
     }
 
     /**
      * The `DefaultConstructorHandlerFactory` is a factory class that uses a constructor
      * to create handler instances. It implements the `HandlerFactory` interface.
      */
-    private class DefaultConstructorHandlerFactory implements HandlerFactory {
+    private static class DefaultConstructorHandlerFactory implements HandlerFactory {
 
-        private final Constructor constructor;
+        private final Constructor> constructor;
 
-        public DefaultConstructorHandlerFactory(Class type) {
+        public DefaultConstructorHandlerFactory(Class> type) {
             this.constructor = getConstructor(type);
         }
 
+        private static Constructor> getConstructor(Class> type) {
+            try {
+                return type.getConstructor(Resource.class, ExecutionContext.class, Setter.class);
+            } catch (NoSuchMethodException e) {
+                throw new RuntimeException("Expected constructor (Resource, ExecutionContext, Setter) in " + type, e);
+            }
+        }
+
         @Override
-        public Handler getHandler(Resource resource, ExecutionContext executionContext, Setter setter) {
+        public Handler getHandler(Resource resource, ExecutionContext executionContext, Setter setter) {
             try {
                 return constructor.newInstance(resource, executionContext, setter);
             } catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
@@ -116,4 +124,5 @@ public Handler getHandler(Resource resource, ExecutionContext executionContex
         }
     }
 
+
 }
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ListSetter.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ListSetter.java
index db0ff8c6f..0b4b4e491 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ListSetter.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ListSetter.java
@@ -3,7 +3,7 @@
 import java.lang.reflect.Field;
 import java.util.List;
 
-public class ListSetter extends Setter{
+public class ListSetter extends Setter{
 
     public ListSetter(Field f, Object bean) {
         super(f, bean);
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/PathHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/PathHandler.java
index 425d0ff4f..5e03f241b 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/PathHandler.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/PathHandler.java
@@ -1,7 +1,6 @@
 package cz.cvut.spipes.modules.handlers;
 
 import cz.cvut.spipes.engine.ExecutionContext;
-import org.apache.jena.rdf.model.Property;
 import org.apache.jena.rdf.model.RDFNode;
 import org.apache.jena.rdf.model.Resource;
 import java.nio.file.Path;
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/RDFNodeHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/RDFNodeHandler.java
index c22964560..bbe67cad1 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/RDFNodeHandler.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/RDFNodeHandler.java
@@ -1,7 +1,6 @@
 package cz.cvut.spipes.modules.handlers;
 
 import cz.cvut.spipes.engine.ExecutionContext;
-import org.apache.jena.rdf.model.Property;
 import org.apache.jena.rdf.model.RDFNode;
 import org.apache.jena.rdf.model.Resource;
 
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ResourceHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ResourceHandler.java
index 2dd1aeaf2..39ad5d0ba 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ResourceHandler.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/ResourceHandler.java
@@ -2,7 +2,6 @@
 
 
 import cz.cvut.spipes.engine.ExecutionContext;
-import org.apache.jena.rdf.model.Property;
 import org.apache.jena.rdf.model.RDFNode;
 import org.apache.jena.rdf.model.Resource;
 
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StreamResourceHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StreamResourceHandler.java
index 6dc6155b6..81aeefc33 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StreamResourceHandler.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StreamResourceHandler.java
@@ -14,7 +14,7 @@ public StreamResourceHandler(Resource resource, ExecutionContext executionContex
     }
 
     @Override
-    StreamResource getRDFNodeValue(RDFNode node) throws Exception {
+    StreamResource getRDFNodeValue(RDFNode node) {
         StreamResource res = StreamResourceRegistry.getInstance().getResourceByUrl(node.asLiteral().toString());
 
         if (res == null) {
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StringHandler.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StringHandler.java
index 6bbe6a233..66c01329a 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StringHandler.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/handlers/StringHandler.java
@@ -1,7 +1,6 @@
 package cz.cvut.spipes.modules.handlers;
 
 import cz.cvut.spipes.engine.ExecutionContext;
-import org.apache.jena.rdf.model.Property;
 import org.apache.jena.rdf.model.RDFNode;
 import org.apache.jena.rdf.model.Resource;
 
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandlerTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandlerTest.java
index 8918585a1..52eeaa64d 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandlerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BaseRDFNodeHandlerTest.java
@@ -24,9 +24,9 @@ void setUp() {
         mockExecutionContext = mock(ExecutionContext.class);
         mockSetter = mock(Setter.class);
         mockProperty = mock(Property.class);
-        handler = new BaseRDFNodeHandler(mockResource, mockExecutionContext, mockSetter){
+        handler = new BaseRDFNodeHandler<>(mockResource, mockExecutionContext, mockSetter) {
             @Override
-            String getRDFNodeValue(RDFNode node) throws Exception {
+            String getRDFNodeValue(RDFNode node) {
                 return node.asLiteral().getString();
             }
         };
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BooleanHandlerTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BooleanHandlerTest.java
index 062967c96..23b3e5d95 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BooleanHandlerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/BooleanHandlerTest.java
@@ -1,12 +1,9 @@
 package cz.cvut.spipes.modules.handlers;
 
 import cz.cvut.spipes.engine.ExecutionContext;
-import cz.cvut.spipes.exception.ScriptRuntimeErrorException;
 import org.apache.jena.rdf.model.*;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mockito;
 
 import static org.junit.jupiter.api.Assertions.*;
 import static org.mockito.Mockito.*;
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/FieldSetterTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/FieldSetterTest.java
index d145dd63f..20229e97e 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/FieldSetterTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/FieldSetterTest.java
@@ -11,11 +11,11 @@ class FieldSetterTest {
 
     private TestBean testBean;
     private Field testField;
-    private FieldSetter fieldSetter;
+    private FieldSetter fieldSetter;
 
     public static class TestBean {
         public String publicField;
-        private String privateField;
+        private final String privateField;
 
         public TestBean(String privateField) {
             this.privateField = privateField;
@@ -26,7 +26,7 @@ public TestBean(String privateField) {
     void setUp() throws NoSuchFieldException {
         testBean = new TestBean("initialValue");
         testField = TestBean.class.getField("publicField");
-        fieldSetter = new FieldSetter(testField, testBean);
+        fieldSetter = new FieldSetter<>(testField, testBean);
     }
 
     @Test
@@ -40,7 +40,7 @@ void testSetValueOnPublicField() {
     void testSetValueOnPrivateField() throws NoSuchFieldException {
         Field privateField = TestBean.class.getDeclaredField("privateField");
         privateField.setAccessible(true);
-        FieldSetter privateFieldSetter = new FieldSetter(privateField, testBean);
+        FieldSetter privateFieldSetter = new FieldSetter<>(privateField, testBean);
 
         privateFieldSetter.addValue("newPrivateValue");
 
@@ -50,7 +50,7 @@ void testSetValueOnPrivateField() throws NoSuchFieldException {
     @Test
     void testSetValueOnPrivateFieldWhenInitiallyNotAccessible() throws NoSuchFieldException {
         Field privateField = TestBean.class.getDeclaredField("privateField");
-        FieldSetter privateFieldSetter = new FieldSetter(privateField, testBean);
+        FieldSetter privateFieldSetter = new FieldSetter<>(privateField, testBean);
 
         privateFieldSetter.addValue("newPrivateValue");
 
@@ -62,11 +62,9 @@ void testSetValueOnPrivateFieldWhenInitiallyNotAccessible() throws NoSuchFieldEx
     void testSetValueToFieldWithDifferentType() throws NoSuchFieldException {
         Field intField = TestBean.class.getDeclaredField("privateField");
         intField.setAccessible(true);
-        FieldSetter intFieldSetter = new FieldSetter(intField, testBean);
+        FieldSetter intFieldSetter = new FieldSetter<>(intField, testBean);
 
-        assertThrows(IllegalArgumentException.class, () -> {
-            intFieldSetter.addValue(123);
-        });
+        assertThrows(IllegalArgumentException.class, () -> intFieldSetter.addValue(123));
     }
 }
 
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListHandlerTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListHandlerTest.java
index 6f4084a44..6323b9b11 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListHandlerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListHandlerTest.java
@@ -2,6 +2,7 @@
 
 import cz.cvut.spipes.engine.ExecutionContext;
 import org.apache.jena.rdf.model.*;
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.mockito.InjectMocks;
@@ -30,6 +31,7 @@ public class ListHandlerTest {
     @InjectMocks
     private ListHandler listHandler;
 
+    private AutoCloseable mocks;
 
     static class SampleClass {
         List listField;
@@ -38,7 +40,12 @@ static class SampleClass {
     @BeforeEach
     void setUp() {
         // Initializes the mocks and injects them into the @InjectMocks field
-        MockitoAnnotations.openMocks(this);
+        mocks = MockitoAnnotations.openMocks(this);
+    }
+
+    @AfterEach
+    void tearDown() throws Exception {
+        mocks.close();
     }
 
     @Test
@@ -69,7 +76,6 @@ public void testGetStringListByProperty_withValidData() throws Exception {
             HandlerRegistry mockRegistry = mock(HandlerRegistry.class);
 
             // Use raw type for mocking Handler
-            @SuppressWarnings("unchecked")
             BaseRDFNodeHandler mockHandler = mock(StringHandler.class);
 
 
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListSetterTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListSetterTest.java
index d4c20d60b..afe9597be 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListSetterTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/ListSetterTest.java
@@ -14,7 +14,7 @@ class ListSetterTest {
 
     private TestBean testBean;
     private Field testField;
-    private ListSetter listSetter;
+    private ListSetter listSetter;
 
     public static class TestBean {
         public List values;
@@ -24,7 +24,7 @@ public static class TestBean {
     void setUp() throws NoSuchFieldException {
         testBean = new TestBean();
         testField = TestBean.class.getField("values");
-        listSetter = new ListSetter(testField, testBean);
+        listSetter = new ListSetter<>(testField, testBean);
     }
 
     @Test
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/PathHandlerTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/PathHandlerTest.java
index 9ff0d00f1..92a92c81e 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/PathHandlerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/PathHandlerTest.java
@@ -2,12 +2,10 @@
 
 import cz.cvut.spipes.engine.ExecutionContext;
 import org.apache.jena.rdf.model.ModelFactory;
-import org.apache.jena.rdf.model.Property;
 import org.apache.jena.rdf.model.RDFNode;
 import org.apache.jena.rdf.model.Resource;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.mockito.ArgumentCaptor;
 
 import java.nio.file.Path;
 import java.nio.file.Paths;
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/URLHandlerTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/URLHandlerTest.java
index ed25826be..017750b21 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/URLHandlerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/handlers/URLHandlerTest.java
@@ -40,9 +40,7 @@ void testGetRDFNodeValue_InvalidURL() {
 
         RDFNode node = ResourceFactory.createPlainLiteral("invalid-url");
 
-        assertThrows(MalformedURLException.class, () -> {
-            urlHandler.getRDFNodeValue(node);
-        });
+        assertThrows(MalformedURLException.class, () -> urlHandler.getRDFNodeValue(node));
     }
 
     @Test
@@ -50,8 +48,6 @@ void testGetRDFNodeValue_NullNode() {
 
         RDFNode node = null;
 
-        assertThrows(NullPointerException.class, () -> {
-            urlHandler.getRDFNodeValue(node);
-        });
+        assertThrows(NullPointerException.class, () -> urlHandler.getRDFNodeValue(node));
     }
 }

From c5476810da6934a53f83791cd9f29d8a7e960e69 Mon Sep 17 00:00:00 2001
From: Evgenii Grigorev 
Date: Wed, 3 Sep 2025 10:16:30 +0200
Subject: [PATCH 09/16] [#324] Refactor s-pipes-core/modules to reduce the
 number of warnings

---
 .../cvut/spipes/modules/AbstractModule.java   | 110 +++++++++---------
 .../modules/AnnotatedAbstractModule.java      |   2 +-
 .../spipes/modules/ApplyConstructModule.java  |   6 +-
 .../spipes/modules/BindBySelectModule.java    |  39 ++++---
 .../modules/BindWithConstantModule.java       |   2 +-
 .../modules/ImportFileFromURLModule.java      |   4 +-
 .../modules/ImportRDFFromWorkspaceModule.java |   5 +-
 .../modules/RetrievePrefixesModule.java       |  16 +--
 .../modules/AbstractCoreModuleTestHelper.java |   4 +-
 .../spipes/modules/AbstractModuleTest.java    |  19 +--
 .../modules/ApplyConstructModuleTest.java     |  16 +--
 .../modules/BindWithConstantModuleTest.java   |   4 +-
 .../modules/ImportFileFromURLModuleTest.java  |  10 +-
 .../ImportRDFFromWorkspaceModuleTest.java     |   4 +-
 .../modules/RetrievePrefixesModuleTest.java   |   9 +-
 .../cvut/spipes/modules/TarqlModuleTest.java  |   4 +-
 16 files changed, 116 insertions(+), 138 deletions(-)

diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AbstractModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AbstractModule.java
index c55491758..e7fbc06dd 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AbstractModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AbstractModule.java
@@ -64,11 +64,11 @@ public abstract class AbstractModule implements Module {
 
 
     // load each properties
-    // valiadation of required parameter
+    // validation of required parameter
     // ?? validation of shape of input graph
     // TODO move elsewhere?
     static {
-        SPipesUtil.init(); // initialize system functoins
+        SPipesUtil.init(); // initialize system functions
     }
 
 
@@ -193,11 +193,11 @@ interface RDFModelWriter {
     }
 
     private String saveModelToTemporaryFile(RDFModelWriter rdfModelWriter, Model model, String filePrefix) {
-        File tempFile = null;
+        File tempFile;
         try {
             tempFile = Files.createTempFile(filePrefix, ".ttl").toFile();
         } catch (IOException e) {
-            e.printStackTrace();
+            log.error(e.getMessage());
             return null;
         }
         try (OutputStream tempFileIs = new FileOutputStream(tempFile)) {
@@ -205,7 +205,7 @@ private String saveModelToTemporaryFile(RDFModelWriter rdfModelWriter, Model mod
 
             return tempFile.getAbsolutePath();
         } catch (IOException e) {
-            e.printStackTrace();
+            log.error(e.getMessage());
             return null;
         }
     }
@@ -228,12 +228,7 @@ protected String saveScriptToTemporaryFile(Model model) {
 
     protected String saveFullModelToTemporaryFile(OntModel model) {
         return saveModelToTemporaryFile(
-            new RDFModelWriter() {
-                @Override
-                public void write(OutputStream outputStream, Model model) {
-                    ((OntModel) model).writeAll(outputStream, FileUtils.langTurtle);
-                }
-            },
+                (outputStream, model1) -> ((OntModel) model1).writeAll(outputStream, FileUtils.langTurtle),
             model,
             "full-model-output-"
         );
@@ -277,7 +272,7 @@ void checkInputConstraints() {
 
     private void checkConstraints(Model model, QuerySolution bindings, List constraintQueries) {
 
-        // sort queries based on order specified by comments within query
+        // sort queries based on order specified by comments within a query
         constraintQueries = sortConstraintQueries(constraintQueries);
 
         //      set up variable bindings
@@ -289,44 +284,49 @@ private void checkConstraints(Model model, QuerySolution bindings, List> evidences = new ArrayList<>();
-            if (spinQuery instanceof Ask) {
-                constraintViolated = execution.execAsk();
-            } else if (spinQuery instanceof Select) { //TODO implement
-                ResultSet rs = execution.execSelect();
-                constraintViolated = rs.hasNext();
-                if(constraintViolated){
-
-                    for(int i = 0; i < ExecutionConfig.getEvidenceNumber() && rs.hasNext(); i++){
-                        QuerySolution solution = rs.next() ;
-                        Map evidenceMap = new LinkedHashMap<>();
-                        for (String varName : rs.getResultVars()) {
-                            RDFNode value = solution.get(varName);
-                            evidenceMap.put(varName, value);
+            Query query = QueryUtils.createQuery(Objects.requireNonNull(spinQuery));
+
+            try (QueryExecution execution = QueryExecution
+                    .model(model)
+                    .query(query)
+                    .substitution(bindings)
+                    .build()) {
+
+                boolean constraintViolated;
+                List> evidences = new ArrayList<>();
+                if (spinQuery instanceof Ask) {
+                    constraintViolated = execution.execAsk();
+                } else if (spinQuery instanceof Select) {
+                    ResultSet rs = execution.execSelect();
+                    constraintViolated = rs.hasNext();
+                    if (constraintViolated) {
+                        for (int i = 0; i < ExecutionConfig.getEvidenceNumber() && rs.hasNext(); i++) {
+                            QuerySolution solution = rs.next();
+                            Map evidenceMap = new LinkedHashMap<>();
+                            for (String varName : rs.getResultVars()) {
+                                RDFNode value = solution.get(varName);
+                                evidenceMap.put(varName, value);
+                            }
+                            evidences.add(evidenceMap);
                         }
-                        evidences.add(evidenceMap);
                     }
+                } else if (spinQuery instanceof Construct) {
+                    throw new NotImplemented("Constraints for objects " + query + " not implemented.");
+                } else {
+                    throw new NotImplemented("Constraints for objects " + query + " not implemented.");
                 }
-            } else if (spinQuery instanceof Construct) {
-                throw new NotImplemented("Constraints for objects " + query + " not implemented.");
-            } else {
-                throw new NotImplemented("Constraints for objects " + query + " not implemented.");
-            }
-            if (constraintViolated) {
-                String mainErrorMsg =  getQueryComment(spinQuery);
-                String failedQueryMsg = spinQuery.toString();
-                var exception = new ValidationConstraintFailedException(this, mainErrorMsg, failedQueryMsg, evidences);
-                log.error(exception.toString());
-                if (ExecutionConfig.isExitOnError()) {
-                    throw exception;
+
+                if (constraintViolated) {
+                    String mainErrorMsg = getQueryComment(spinQuery);
+                    String failedQueryMsg = spinQuery.toString();
+                    var exception = new ValidationConstraintFailedException(this, mainErrorMsg, failedQueryMsg, evidences);
+                    log.error(exception.toString());
+                    if (ExecutionConfig.isExitOnError()) {
+                        throw exception;
+                    }
+                } else {
+                    log.debug("Constraint validated for exception \"{}\".", getQueryComment(spinQuery));
                 }
-            } else {
-                log.debug("Constraint validated for exception \"{}\".", getQueryComment(spinQuery));
             }
         }
 
@@ -336,8 +336,8 @@ private void checkConstraints(Model model, QuerySolution bindings, Listquery resource argument. This is either the string
      * associated with query rdfs:comment or if not present the first comment line found in the query string.
      * If neither is present, the method returns the uri of the query resource.
-     * @param query
-     * @return
+     * @param query the query resource
+     * @return the query comment or the uri of the query resource
      */
     protected String getQueryComment(cz.cvut.spipes.spin.model.Query query) {
         if (query.getComment() != null) {
@@ -435,10 +435,10 @@ protected RDFNode getEffectiveValue(@NotNull Property valueProperty) {
 
     /**
      * Helper method to creates output execution context considering isReplace flag
-     * indicating if newly computed model should replace input model of the module
+     * indicating if a newly computed model should replace an input model of the module
      * or be appended to it.
-     * @param isReplace if true replace input model otherwise append to it.
-     * @param computedModel model to be reflected in final output of this module.
+     * @param isReplace if true, replace an input model, otherwise append to it.
+     * @param computedModel model to be reflected in the final output of this module.
      * @return Output execution context to be returned by this module.
      */
     protected ExecutionContext createOutputContext(boolean isReplace, Model computedModel) {
@@ -449,10 +449,10 @@ protected ExecutionContext createOutputContext(boolean isReplace, Model computed
 
     /**
      * Helper method to creates output model considering isReplace flag
-     * indicating if newly computed model should replace input model of the module
+     * indicating if a newly computed model should replace an input model of the module
      * or be appended to it.
-     * @param isReplace if true replace input model otherwise append to it.
-     * @param computedModel model to be reflected in final output of this module.
+     * @param isReplace if true, replace an input model otherwise append to it.
+     * @param computedModel model to be reflected in the final output of this module.
      * @return Output model to be returned by this module.
      */
     protected Model createOutputModel(boolean isReplace, Model computedModel) {
@@ -472,7 +472,7 @@ private List sortConstraintQueries(List constraintQueries) {
             cz.cvut.spipes.spin.model.Query spinQuery1 = SPINFactory.asQuery(resource1);
             cz.cvut.spipes.spin.model.Query spinQuery2 = SPINFactory.asQuery(resource2);
 
-            return spinQuery1.toString().compareTo(spinQuery2.toString());
+            return Objects.requireNonNull(spinQuery1).toString().compareTo(Objects.requireNonNull(spinQuery2).toString());
         }).collect(Collectors.toList());
     }
 
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AnnotatedAbstractModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AnnotatedAbstractModule.java
index 785048e68..e4ccd3ac5 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AnnotatedAbstractModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/AnnotatedAbstractModule.java
@@ -124,5 +124,5 @@ public void loadConfiguration() {
      */
     public void loadManualConfiguration(){
         // Default implementation: no manual configuration
-    };
+    }
 }
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ApplyConstructModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ApplyConstructModule.java
index 0919b87b7..b755447c4 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ApplyConstructModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ApplyConstructModule.java
@@ -42,14 +42,14 @@ public class ApplyConstructModule extends AnnotatedAbstractModule {
     private boolean parseText = false;
 
     /**
-     * Maximal number of iterations of the whole rule set. 0 means 0 iterations. The actual number of iterations can be smaller,
-     * if no new inferences are generated any more.
+     * Maximal number of iterations of the whole rule set. 0 means 0 iterations. The actual number of iterations can be smaller
+     * if no new inferences are generated anymore.
      * 

* iterationCount = 1: * - the whole rule set is executed only once. * iterationCount > 1: * - the whole rule set is executed at most "iterationCount" times. - * - in each iteration, queries are evaluated on the model merged from the default model and the result of previous iteration + * - in each iteration, queries are evaluated on the model merged from the default model and the result of the previous iteration *

* Within each iteration, all queries are evaluated on the same model. */ diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java index 55f992e78..c6102d27e 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java @@ -19,7 +19,7 @@ public class BindBySelectModule extends AnnotatedAbstractModule { private Select selectQuery; @Parameter(iri = SML.replace) - private boolean isReplace = false; + private final boolean isReplace = false; @Override public ExecutionContext executeSelf() { @@ -28,28 +28,31 @@ public ExecutionContext executeSelf() { QuerySolution inputBindings = executionContext.getVariablesBinding().asQuerySolution(); - QueryExecution execution = QueryExecutionFactory.create(query, executionContext.getDefaultModel(), inputBindings); + try (QueryExecution execution = QueryExecution + .model(executionContext.getDefaultModel()) + .query(query) + .substitution(inputBindings) + .build()) { + ResultSet resultSet = execution.execSelect(); - ResultSet resultSet = execution.execSelect(); + VariablesBinding variablesBinding = new VariablesBinding(); - VariablesBinding variablesBinding = new VariablesBinding(); + if (!resultSet.hasNext()) { + log.debug("\"{}\" query did not return any values.", getLabel()); + } else { + QuerySolution qs = resultSet.next(); + variablesBinding = new VariablesBinding(qs); - if (!resultSet.hasNext()) { - log.debug("\"{}\" query did not return any values.", getLabel()); - } else { - QuerySolution qs = resultSet.next(); - - variablesBinding = new VariablesBinding(qs); - - if (resultSet.hasNext()) { - log.warn("\"{}\" query did not return unique value. If it is correct, the query should be restricted by additional statement (e.g. \"LIMIT 1\"). Returning binding {}, ignoring binding {}", getLabel(), variablesBinding.asQuerySolution(), resultSet.next()); + if (resultSet.hasNext()) { + log.warn("\"{}\" query did not return unique value. If it is correct, the query should be restricted by additional statement (e.g. \"LIMIT 1\"). Returning binding {}, ignoring binding {}", getLabel(), variablesBinding.asQuerySolution(), resultSet.next()); + } } - } - return ExecutionContextFactory.createContext( - this.createOutputModel(isReplace, ModelFactory.createDefaultModel()), - variablesBinding - ); + return ExecutionContextFactory.createContext( + this.createOutputModel(isReplace, ModelFactory.createDefaultModel()), + variablesBinding + ); + } } @Override diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java index f84781a41..87438ee98 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java @@ -20,7 +20,7 @@ public class BindWithConstantModule extends AnnotatedAbstractModule { RDFNode value; @Parameter(iri = SML.replace) - private boolean isReplace = false; + private final boolean isReplace = false; @Override public ExecutionContext executeSelf() { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportFileFromURLModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportFileFromURLModule.java index 38b9ab832..9a2a6e2cb 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportFileFromURLModule.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportFileFromURLModule.java @@ -35,7 +35,7 @@ public class ImportFileFromURLModule extends AnnotatedAbstractModule { @Override public ExecutionContext executeSelf() { - Path computedTargetFilePath = null; + Path computedTargetFilePath; log.debug("Importing file from url {}.", url); try (InputStream inputStream = url.openStream()) { @@ -51,7 +51,7 @@ public ExecutionContext executeSelf() { throw new RuntimeException(e); } - if ((targetResourceVariable == null) || (targetResourceVariable.equals(""))) { + if ((targetResourceVariable == null) || (targetResourceVariable.isEmpty())) { return ExecutionContextFactory.createEmptyContext(); } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModule.java index 17f739cce..6d3645614 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModule.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModule.java @@ -7,13 +7,10 @@ import cz.cvut.spipes.manager.OntoDocManager; import cz.cvut.spipes.manager.OntologyDocumentManager; import org.apache.jena.rdf.model.Model; -import org.apache.jena.rdf.model.RDFNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Optional; public class ImportRDFFromWorkspaceModule extends AnnotatedAbstractModule { @@ -62,7 +59,7 @@ public void setSourceFilePath(Path sourceFilePath) { @Override public String getTypeURI() { - return SML.ImportRDFFromWorkspace.toString(); + return SML.ImportRDFFromWorkspace; } @Override diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java index 48b103702..d462ee041 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java @@ -15,29 +15,29 @@ /** * Module returns prefix mappings of all loaded scripts. - * Individual mappings are represented by following graph pattern: + * Individual mappings are represented by the following graph pattern: * * @prefix ja: . - * + *

* ?ontology ja:prefixMapping * [ a ja:SinglePrefixMapping ; * ja:namespace ?namespaceIRI ; * ja:prefix ?prefix ] * . - * - * As an example let's assume we loaded only one script: + *

+ * As an example, let's assume we loaded only one script: * * @prefix : . * @prefix owl: . - * + *

* :my-ontology a owl:Ontology . - * + *

* * The output of this module for the example script would be: * * @prefix : . * @prefix ja: . - * + *

* :my-ontology ja:prefixMapping * [ a ja:SinglePrefixMapping ; * ja:namespace "http://example.org/" ; @@ -53,7 +53,7 @@ public class RetrievePrefixesModule extends AnnotatedAbstractModule { private static final String TYPE_URI = KBSS_MODULE.uri + "retrieve-prefixes"; @Parameter(iri = SML.replace) - private boolean isReplace = false; + private final boolean isReplace = false; //TODO refactor -> should be part of execution context OntologyDocumentManager ontologyDocumentManager = OntoDocManager.getInstance(); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractCoreModuleTestHelper.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractCoreModuleTestHelper.java index 7712ae2ae..2823841ae 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractCoreModuleTestHelper.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractCoreModuleTestHelper.java @@ -4,9 +4,9 @@ import org.apache.jena.ontology.OntModel; /** - * This is helper class to write tests that load configuration of modules from ttl file + * This is a helper class to write tests that load configuration of modules from ttl file * that is organized in directory `test/resources/module/${moduleName}/`. - * + *

* See more information in {@link AbstractModuleTestHelper}. */ public abstract class AbstractCoreModuleTestHelper extends AbstractModuleTestHelper { diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractModuleTest.java index 7d2e47d01..902df8b45 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/AbstractModuleTest.java @@ -7,7 +7,6 @@ import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.RDFNode; import org.apache.jena.rdf.model.ResourceFactory; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -20,7 +19,7 @@ String getModuleName() { } @Test - public void getEffectiveValueReturnsComputedValue() throws Exception { + public void getEffectiveValueReturnsComputedValue() { Module module = PipelineFactory.loadPipelines(getConfigOntModel()).get(0); assertEquals(BindWithConstantModule.class, module.getClass(), "Incorrect module loaded."); @@ -37,20 +36,4 @@ public void getEffectiveValueReturnsComputedValue() throws Exception { } - @Disabled - @Test - public void throwValidationExceptionIfValidationConstrainFailsAndExitOnErrorIsTrue() { -// AbstractModule m = createModuleWithFailingValidationConstraint(); -// -// m.setInputContext(ExecutionContextFactory.createEmptyContext()); -// m.checkInputConstraints(); - } - - @Disabled - @Test - public void throwNoValidationExceptionIfValidationConstrainFailsAndExitOnErrorIsFalse() { - - } - - } \ No newline at end of file diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ApplyConstructModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ApplyConstructModuleTest.java index a9dddbd0e..b1b807a00 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ApplyConstructModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ApplyConstructModuleTest.java @@ -33,17 +33,17 @@ public void executeSimple() { module.setInputContext(ExecutionContextFactory.createContext(createSimpleModel())); module.loadConfiguration(); - ExecutionContext newContext = null; + ExecutionContext newContext; // isReplace = true module.setReplace(true); newContext = module.executeSelf(); - assertEquals(newContext.getDefaultModel().listStatements().toList().size(), 2); + assertEquals(2, newContext.getDefaultModel().listStatements().toList().size()); // isReplace = true module.setReplace(false); newContext = module.executeSelf(); - assertEquals(newContext.getDefaultModel().listStatements().toList().size(), 3); + assertEquals(3, newContext.getDefaultModel().listStatements().toList().size()); //newContext.getDefaultModel().write(System.out, FileUtils.langTurtle); } @@ -56,17 +56,17 @@ public void executeIteration() { module.setInputContext(ExecutionContextFactory.createContext(createSimpleModel())); module.loadConfiguration(); - ExecutionContext newContext = null; + ExecutionContext newContext; // isReplace = true module.setReplace(true); newContext = module.executeSelf(); - assertEquals(newContext.getDefaultModel().listStatements().toList().size(), 2); + assertEquals(2, newContext.getDefaultModel().listStatements().toList().size()); // isReplace = true module.setReplace(false); newContext = module.executeSelf(); - assertEquals(newContext.getDefaultModel().listStatements().toList().size(), 3); + assertEquals(3, newContext.getDefaultModel().listStatements().toList().size()); //newContext.getDefaultModel().write(System.out, FileUtils.langTurtle); } @@ -77,7 +77,7 @@ public void executeConstructQueryWithVariable() { ApplyConstructModule module = (ApplyConstructModule) getRootModule("remote-query.ttl"); - ExecutionContext newContext = null; + ExecutionContext newContext; VariablesBinding variablesBinding = new VariablesBinding( "sampleServiceUri", @@ -90,7 +90,7 @@ public void executeConstructQueryWithVariable() { // isReplace = true module.setReplace(true); newContext = module.executeSelf(); - assertEquals(newContext.getDefaultModel().listStatements().toList().size(), 54); + assertEquals(54, newContext.getDefaultModel().listStatements().toList().size()); } @Test diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/BindWithConstantModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/BindWithConstantModuleTest.java index 6ca745660..b7c0949e6 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/BindWithConstantModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/BindWithConstantModuleTest.java @@ -41,12 +41,12 @@ public void executeWithSimpleValue() { } @Test - public void executeWithBindedValue() throws Exception { + public void executeWithBindedValue() { OntModel ontModel = getConfigOntModel(); List moduleList = PipelineFactory.loadPipelines(ontModel); - assertEquals(moduleList.size(), 1, "Bad number of output modules"); + assertEquals(1, moduleList.size(), "Bad number of output modules"); Module module = moduleList.get(0); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportFileFromURLModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportFileFromURLModuleTest.java index 4e889f375..9faf9083b 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportFileFromURLModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportFileFromURLModuleTest.java @@ -6,8 +6,6 @@ import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -46,7 +44,7 @@ public class ImportFileFromURLModuleTest { // .andExpect(method(HttpMethod.GET)) // .andRespond(withSuccess("{}", MediaType.APPLICATION_JSON)); // mockServer.verify(); - //@Disabled //TODO mockServer works mostlikely only through Spring API not with URL.connection + //@Disabled //TODO mockServer works most likely only through Spring API not with URL.connection @Test public void executeWithTargetFilePath() throws Exception { @@ -85,9 +83,7 @@ public void executeWithUnreachableUrl() throws MalformedURLException { m.setInputContext(ExecutionContextFactory.createEmptyContext()); //TODO specific exception - assertThrows(RuntimeException.class, () -> { - m.executeSelf(); - }); + assertThrows(RuntimeException.class, m::executeSelf); } private ImportFileFromURLModule createModuleWithSampleUrl() { @@ -106,7 +102,7 @@ private URL getSampleFileUrl() { } private String getFileContent(Path file) throws IOException { - return new String (Files.readAllBytes(file), StandardCharsets.UTF_8); + return Files.readString(file); } } \ No newline at end of file diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModuleTest.java index c7cc0acd8..1729cf806 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/ImportRDFFromWorkspaceModuleTest.java @@ -25,7 +25,7 @@ public class ImportRDFFromWorkspaceModuleTest { @Test @Disabled - public void executeSelfWithBaseUriAndIgnoredImports() throws Exception { + public void executeSelfWithBaseUriAndIgnoredImports() { Model sampleModel = OntologyGenerator.getSampleModel(); @@ -50,7 +50,7 @@ public void executeSelfWithBaseUriAndIgnoredImports() throws Exception { @Test @Disabled - public void executeSelfWithInvalidBaseUriThrowsException() throws Exception { + public void executeSelfWithInvalidBaseUriThrowsException() { Model sampleModel = OntologyGenerator.getSampleModel(); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/RetrievePrefixesModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/RetrievePrefixesModuleTest.java index 2e71464cb..6b5ff6628 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/RetrievePrefixesModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/RetrievePrefixesModuleTest.java @@ -26,6 +26,7 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Objects; import static cz.cvut.spipes.test.JenaTestUtils.assertIsomorphic; import static org.mockito.BDDMockito.given; @@ -62,9 +63,7 @@ void setUp() { @Test void executeSelfReturnPrefixes() throws URISyntaxException { given(ontoDocManager.getRegisteredOntologyUris()).willReturn(uri2ontModel.keySet()); - uri2ontModel.forEach((key, value) -> { - doReturn(value).when(ontoDocManager).getOntology(key); - }); + uri2ontModel.forEach((key, value) -> doReturn(value).when(ontoDocManager).getOntology(key)); ExecutionContext inputExecutionContext = ExecutionContextFactory.createEmptyContext(); @@ -98,7 +97,7 @@ private static OntModel loadOntModel(InputStream inputStream) { OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); OntDocumentManager dm = OntDocumentManager.getInstance(); - dm.setFileManager(FileManager.get()); + dm.setFileManager(FileManager.getInternal()); ontModel.read(inputStream, null, FileUtils.langTurtle); dm.loadImports(ontModel); @@ -107,6 +106,6 @@ private static OntModel loadOntModel(InputStream inputStream) { public Path getFilePath(String fileName) throws URISyntaxException { - return Paths.get(getClass().getResource("/" + fileName).toURI()); + return Paths.get(Objects.requireNonNull(getClass().getResource("/" + fileName)).toURI()); } } \ No newline at end of file diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/TarqlModuleTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/TarqlModuleTest.java index 4a5f349d6..d1216970b 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/modules/TarqlModuleTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/modules/TarqlModuleTest.java @@ -11,11 +11,11 @@ public class TarqlModuleTest { - String TARQL_MODULE_DIR = "module/tarql"; + final String TARQL_MODULE_DIR = "module/tarql"; @Disabled @Test - public void execute() throws Exception { + public void execute() { ExecutionEngine e = ExecutionEngineFactory.createEngine(); From 770700357ba250d72bf1d621dacaa591ba260804 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:16:53 +0200 Subject: [PATCH 10/16] [#324] Refactor s-pipes-core/registry to reduce the number of warnings --- .../cz/cvut/spipes/registry/JenaResourceRegistry.java | 9 +++++---- .../cz/cvut/spipes/registry/StreamResourceRegistry.java | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/registry/JenaResourceRegistry.java b/s-pipes-core/src/main/java/cz/cvut/spipes/registry/JenaResourceRegistry.java index 929858a86..805e35bf4 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/registry/JenaResourceRegistry.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/registry/JenaResourceRegistry.java @@ -20,13 +20,13 @@ */ public class JenaResourceRegistry implements ResourceRegistry { - Map> local2fullNamesMap = new HashMap<>(); - Map> fullName2ContextsMap = new HashMap<>(); - Map> context2PrefixMappingMap = new HashMap<>(); + final Map> local2fullNamesMap = new HashMap<>(); + final Map> fullName2ContextsMap = new HashMap<>(); + final Map> context2PrefixMappingMap = new HashMap<>(); public JenaResourceRegistry(List resourceList) { - resourceList.stream() + resourceList .forEach(res -> { String resUri = res.getURI(); String localName = res.getLocalName(); @@ -53,6 +53,7 @@ public JenaResourceRegistry(List resourceList) { return Collections.unmodifiableSet(context2PrefixMappingMap.keySet()); } + @NotNull @Override public Set getContexts(String entityId) { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/registry/StreamResourceRegistry.java b/s-pipes-core/src/main/java/cz/cvut/spipes/registry/StreamResourceRegistry.java index 3129cea6a..ad564ea94 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/registry/StreamResourceRegistry.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/registry/StreamResourceRegistry.java @@ -76,7 +76,7 @@ private void cleanUpUnusedResources() { log.trace("Clearing {} resources from resource map: {}", keys.size(), keys); } keys.forEach( - k -> id2resourcesMap.remove(k) + id2resourcesMap::remove ); } } From e1b89b192f100999abc93d68691fd7729cf3a85d Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:17:12 +0200 Subject: [PATCH 11/16] [#324] Refactor s-pipes-core/repository to reduce the number of warnings --- .../SMScriptCollectionRepository.java | 11 ++++----- .../ScriptCollectionRepository.java | 4 ++-- .../SMScriptCollectionRepositoryTest.java | 23 ++++--------------- 3 files changed, 11 insertions(+), 27 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/repository/SMScriptCollectionRepository.java b/s-pipes-core/src/main/java/cz/cvut/spipes/repository/SMScriptCollectionRepository.java index c17d51bcc..d288dc4a5 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/repository/SMScriptCollectionRepository.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/repository/SMScriptCollectionRepository.java @@ -10,14 +10,11 @@ import org.slf4j.LoggerFactory; import java.net.URL; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; /** - * Know nothing about alternative entity ids -- e.g. prefixed-names, local-names. + * Know nothing about alternative entity ids -- e.g., prefixed-names, local-names. *

*/ public class SMScriptCollectionRepository implements ScriptCollectionRepository { @@ -51,7 +48,7 @@ public SMScriptCollectionRepository(OntologyDocumentManager ontoDocManager) { if (contexts == null) { throw new UnsupportedOperationException(); } - return null; + return Collections.emptyList(); } @Override @@ -106,7 +103,7 @@ private boolean isValidURL(String url) 1) get modules -- > IDs + context - 2) get funcitons + 2) get functions diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/repository/ScriptCollectionRepository.java b/s-pipes-core/src/main/java/cz/cvut/spipes/repository/ScriptCollectionRepository.java index 58ae62c8b..4e69f3ea7 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/repository/ScriptCollectionRepository.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/repository/ScriptCollectionRepository.java @@ -23,10 +23,10 @@ public interface ScriptCollectionRepository extends Repository { @NotNull List getModuleTypes(@Nullable Collection contexts); /** - * Returns all functions which are attached to a return module. + * Returns all functions that are attached to a return module. * @param contexts List of contexts to search in. * @return List of resources representing functions. - * @throws UnsupportedOperationException if contexts is null. + * @throws UnsupportedOperationException if contexts are null. */ @NotNull List getPipelineFunctions(@Nullable Collection contexts); diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/repository/SMScriptCollectionRepositoryTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/repository/SMScriptCollectionRepositoryTest.java index 46383202a..9a9415c5d 100644 --- a/s-pipes-core/src/test/java/cz/cvut/spipes/repository/SMScriptCollectionRepositoryTest.java +++ b/s-pipes-core/src/test/java/cz/cvut/spipes/repository/SMScriptCollectionRepositoryTest.java @@ -27,11 +27,10 @@ public class SMScriptCollectionRepositoryTest { @InjectMocks SMScriptCollectionRepository scriptCollectionRepository; - final OntModel sampleOntology = getSampleOntology(); final String sampleOntologyUri = JenaUtils.getBaseUri(getSampleOntology()); @Test - public void getModules() throws Exception { + public void getModules() { //given given(ontoDocManager.getOntology(sampleOntologyUri)).willReturn(getSampleOntology()); @@ -40,18 +39,12 @@ public void getModules() throws Exception { List modules = scriptCollectionRepository.getModules(Collections.singleton(sampleOntologyUri)); //then - assertEquals(modules.size(), 3); + assertEquals(3, modules.size()); // TODO better matching by junit5 or assertThat(modules, CoreMatcher.*); } - @Disabled - @Test - public void getModuleTypes() throws Exception { - - } - @Test - public void getPipelineFunctions() throws Exception { + public void getPipelineFunctions() { //given given(ontoDocManager.getOntology(sampleOntologyUri)).willReturn(getSampleOntology()); @@ -60,13 +53,13 @@ public void getPipelineFunctions() throws Exception { List functions = scriptCollectionRepository.getPipelineFunctions(Collections.singleton(sampleOntologyUri)); //then - assertEquals(functions.size(), 2); + assertEquals(2, functions.size()); } @Disabled @Test - public void getResource() throws Exception { + public void getResource() { //given given(ontoDocManager.getOntology(sampleOntologyUri)).willReturn(getSampleOntology()); @@ -80,12 +73,6 @@ public void getResource() throws Exception { assertEquals(sampleResource, resource); } - @Disabled - @Test - public void getAlternativeEntityIds() throws Exception { // get all baseIRIs - - } - private OntModel getSampleOntology() { return JenaTestUtils.loadOntologyClosureFromResources("/sample/sample.ttl"); } From 3faab558c0fbc0568a7c2a8419a1049e9e69aed9 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:17:39 +0200 Subject: [PATCH 12/16] [#324] Refactor s-pipes-core/spin to reduce the number of warnings --- .../java/cz/cvut/spipes/spin/model/impl/AskImpl.java | 3 --- .../java/cz/cvut/spipes/spin/util/ExtraPrefixes.java | 2 +- .../spipes/spin/util/SPINEnhancedNodeFactory.java | 12 ++++++++---- .../main/java/cz/cvut/spipes/spin/vocabulary/SP.java | 3 --- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/model/impl/AskImpl.java b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/model/impl/AskImpl.java index c7e88c145..7b0ba7a54 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/model/impl/AskImpl.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/model/impl/AskImpl.java @@ -1,10 +1,7 @@ package cz.cvut.spipes.spin.model.impl; import cz.cvut.spipes.spin.model.Ask; -import cz.cvut.spipes.spin.util.SPINEnhancedNodeFactory; -import cz.cvut.spipes.spin.vocabulary.SP; import org.apache.jena.enhanced.EnhGraph; -import org.apache.jena.enhanced.Implementation; import org.apache.jena.graph.Node; public class AskImpl extends QueryImpl implements Ask { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/ExtraPrefixes.java b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/ExtraPrefixes.java index fba793d7e..ff1d95f95 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/ExtraPrefixes.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/ExtraPrefixes.java @@ -4,7 +4,7 @@ import java.util.Map; public class ExtraPrefixes { - private static Map map = new HashMap(); + private static final Map map = new HashMap<>(); static { map.put("afn", "http://jena.hpl.hp.com/ARQ/function#"); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java index 46ec6d1f9..d739109b4 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java @@ -5,20 +5,24 @@ import org.apache.jena.enhanced.Implementation; import org.apache.jena.graph.Node; import org.apache.jena.vocabulary.RDF; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; public class SPINEnhancedNodeFactory extends Implementation { private final Node type; - private Constructor enhNodeConstructor; + private Constructor enhNodeConstructor; - public SPINEnhancedNodeFactory(Node type, Class implClass) { + private static final Logger log = LoggerFactory.getLogger(SPINEnhancedNodeFactory.class); + + public SPINEnhancedNodeFactory(Node type, Class implClass) { this.type = type; try { enhNodeConstructor = implClass.getConstructor(Node.class, EnhGraph.class); } catch (Throwable t) { - t.printStackTrace(); + log.error(t.getMessage(), t); } } @@ -28,7 +32,7 @@ public EnhNode wrap(Node node, EnhGraph eg) { return (EnhNode) enhNodeConstructor.newInstance(node, eg); } catch (Throwable t) { - t.printStackTrace(); + log.error(t.getMessage(), t); return null; } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/vocabulary/SP.java b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/vocabulary/SP.java index a08b340c8..88dfb2114 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/vocabulary/SP.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/vocabulary/SP.java @@ -15,11 +15,8 @@ import org.apache.jena.enhanced.BuiltinPersonalities; import org.apache.jena.enhanced.Personality; import org.apache.jena.rdf.model.*; -import org.apache.jena.util.FileUtils; import org.topbraid.shacl.model.SHFactory; -import java.io.InputStream; - /** * Derived from org.topbraid.shacl 1.0.1 * From f9563477d4003b289960ad4809420363d5ae3788 Mon Sep 17 00:00:00 2001 From: Evgenii Grigorev Date: Wed, 3 Sep 2025 10:18:12 +0200 Subject: [PATCH 13/16] [#324] Refactor s-pipes-core/util to reduce the number of warnings --- .../cz/cvut/spipes/util/EncodingUtils.java | 1 - .../java/cz/cvut/spipes/util/ExecUtils.java | 24 +++---- .../cvut/spipes/util/JenaPipelineUtils.java | 61 ++++++++--------- .../java/cz/cvut/spipes/util/JenaUtils.java | 18 +++-- .../java/cz/cvut/spipes/util/QueryUtils.java | 67 ++++++++++++------- .../java/cz/cvut/spipes/util/SPINUtils.java | 2 +- .../spipes/util/VariableBindingUtils.java | 4 +- .../query/OneStepBackExtendedResultSet.java | 4 +- .../cz/cvut/spipes/util/JenaUtilsTest.java | 8 +-- .../spipes/util/VariableBindingUtilsTest.java | 21 +++--- .../spipes/modules/ExternalSchemExModule.java | 3 +- 11 files changed, 110 insertions(+), 103 deletions(-) diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/EncodingUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/EncodingUtils.java index 203692035..7e074ea1a 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/EncodingUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/EncodingUtils.java @@ -1,6 +1,5 @@ package cz.cvut.spipes.util; -import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/ExecUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/ExecUtils.java index 6de41bd19..f749cb6bb 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/ExecUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/ExecUtils.java @@ -7,8 +7,7 @@ import java.io.*; import java.nio.file.Files; -import java.util.Arrays; -import java.util.stream.Collectors; +import java.util.Objects; public class ExecUtils { @@ -18,7 +17,7 @@ public static File stream2file(InputStream in) throws IOException { File tempFile = Files.createTempFile("execution-", ".txt").toFile(); //tempFile.deleteOnExit(); - log.trace("Using temporary file for input stream " + tempFile.getAbsolutePath()); + log.trace("Using temporary file for input stream {}", tempFile.getAbsolutePath()); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } @@ -30,10 +29,10 @@ public static File createTempFile() { try { tempFile = Files.createTempFile("execution-", ".txt").toFile(); } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage()); } - log.trace("Using temporary file for output stream " + tempFile.getAbsolutePath()); + log.trace("Using temporary file for output stream {}", Objects.requireNonNull(tempFile).getAbsolutePath()); return tempFile; } @@ -66,16 +65,13 @@ public static InputStream execProgram(String[] programCall, InputStream inputStr } //TODO remove - public static InputStream execProgramWithoutExeption(String[] programCall, InputStream inputStream) { - String programCallStr = "\"" + Arrays.asList(programCall).stream().collect(Collectors.joining(" ")) + "\"" ; - log.debug("Executing -- " + programCallStr); + public static void execProgramWithoutException(String[] programCall, InputStream inputStream) { + String programCallStr = "\"" + String.join(" ", programCall) + "\"" ; + log.debug("Executing -- {}", programCallStr); try { - return execProgram(programCall, inputStream); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); + execProgram(programCall, inputStream); + } catch (IOException | InterruptedException e) { + log.error(e.getMessage(), e); } - return null; } } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaPipelineUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaPipelineUtils.java index 0c89c9462..a80247ac6 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaPipelineUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaPipelineUtils.java @@ -15,6 +15,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -26,7 +27,7 @@ public class JenaPipelineUtils { public static boolean isModule(Resource res) { - return res.listProperties(RDF.type).filterKeep( + return !res.listProperties(RDF.type).filterKeep( st -> { if (!st.getObject().isResource()) { return false; @@ -34,51 +35,51 @@ public static boolean isModule(Resource res) { Resource objRes = st.getObject().asResource(); return objRes.hasProperty(RDF.type, SM.JENA.Module); } - ).toList().size() > 0; + ).toList().isEmpty(); } public static Map getAllModulesWithTypes(Model config) { - Query query = QueryFactory.create(loadResource("/query/get-all-sm-modules.sparql")); - QueryExecution queryExecution = QueryExecutionFactory.create(query, config); - Map module2moduleTypeMap = new HashMap<>(); - queryExecution.execSelect().forEachRemaining( - qs -> { - Resource module = qs.get("module").asResource(); - Resource moduleType = qs.get("moduleType").asResource(); - Resource previous = module2moduleTypeMap.put(module, moduleType); - if (previous != null) { - log.error("Module {} has colliding module types -- {}, {}. Ignoring type {}.", module, previous, moduleType, previous); - } + try (QueryExecution queryExecution = QueryExecutionFactory.create(query, config)) { + queryExecution.execSelect().forEachRemaining(qs -> { + Resource module = qs.get("module").asResource(); + Resource moduleType = qs.get("moduleType").asResource(); + Resource previous = module2moduleTypeMap.put(module, moduleType); + if (previous != null) { + log.error("Module {} has colliding module types -- {}, {}. Ignoring type {}.", + module, previous, moduleType, previous); } - ); + }); + } + return module2moduleTypeMap; } public static Map getAllFunctionsWithReturnModules(Model config) { Query query = QueryFactory.create(loadResource("/query/get-all-sm-functions.sparql")); - QueryExecution queryExecution = QueryExecutionFactory.create(query, config); Map function2retModuleMap = new HashMap<>(); - queryExecution.execSelect().forEachRemaining( - qs -> { - Resource module = qs.get("function").asResource(); - if (qs.get("returnModule") == null) { - //TODO cleaner workaround for -- ?function = ) - return; - } - Resource moduleType = qs.get("returnModule").asResource(); - log.debug("Registering function {} to return module {}.", module, moduleType); - Resource previous = function2retModuleMap.put(module, moduleType); - if (previous != null) { - log.error("Function {} has colliding return modules -- {}, {}. Ignoring type {}.", module, previous, moduleType, previous); - } + try (QueryExecution queryExecution = QueryExecutionFactory.create(query, config)) { + queryExecution.execSelect().forEachRemaining(qs -> { + Resource module = qs.get("function").asResource(); + if (qs.get("returnModule") == null) { + // TODO cleaner workaround for -- ?function = ) + return; + } + Resource moduleType = qs.get("returnModule").asResource(); + log.debug("Registering function {} to return module {}.", module, moduleType); + Resource previous = function2retModuleMap.put(module, moduleType); + if (previous != null) { + log.error("Function {} has colliding return modules -- {}, {}. Ignoring type {}.", + module, previous, moduleType, previous); } - ); + }); + } + return function2retModuleMap; } @@ -110,7 +111,7 @@ private static String loadResource(String path) { if (is == null) { throw new IllegalArgumentException("Resource with path " + path + " not found."); } - return IOUtils.toString(is); + return IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalArgumentException("Resource with path " + path + " could not be open.", e); } diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaUtils.java index 9c1b2ca52..9c4cc4f6d 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/JenaUtils.java @@ -60,8 +60,8 @@ public static String getBaseUri(Model model) { /** - * Compute hash of an dataset considering semantics of RDF, - * i.e. hashes of two RDF models are same iff RDF models are isomorphic. + * Compute hash of a dataset considering the semantics of RDF, + * i.e., hashes of two RDF models are same iff RDF models are isomorphic. *

* TODO this does not implement correct algorithm (different graphs might return same hash), * although should suffice in many real cases. See http://aidanhogan.com/skolem/ to find more reliable algorithm. @@ -73,9 +73,7 @@ public static String computeHash(Model model) { StringBuilder modelMetadataBuff = new StringBuilder(); Comparator uriComparator = - (r1, r2) -> { - return r1.getURI().compareTo(r2.getURI()); - }; + Comparator.comparing(Resource::getURI); long statementsSize = model.size(); List subjectResources = new ArrayList<>( @@ -105,7 +103,7 @@ public static String computeHash(Model model) { public static Model createUnion(Model... model) { Model outputModel = ModelFactory.createDefaultModel(); Stream.of(model).forEach( - m -> outputModel.add(m) + outputModel::add ); return outputModel; } @@ -113,10 +111,10 @@ public static Model createUnion(Model... model) { public static void saveModelToTemporaryFile(@NotNull Model model) { try { Path file = Files.createTempFile("model-output-", ".ttl"); - log.debug("Saving model to temporary file " + file.toString() + " ..."); + log.debug("Saving model to temporary file {} ...", file.toString()); JenaUtils.write(Files.newOutputStream(file.toFile().toPath()), model); } catch (IOException e) { - e.printStackTrace(); + log.error(e.getMessage()); } } @@ -195,7 +193,7 @@ public static Model getModel(String resource, String ontologyIRI) { : model.read(is, null, FileUtils.langTurtle); } - // TODO - Deside if reified statements should be supported or replaced with something else, e.g. RDF-star. Based on + // TODO - Decide if reified statements should be supported or replaced with something else, e.g. RDF-star. Based on // the decision retain or rewrite HOTFIX methods and their usage. Delete "HOTFIX" from comments. /** * HOTFIX - for model.listReifiedStatements() @@ -208,7 +206,7 @@ public static ExtendedIterator listStatementSubjectOfReifiedStatements } /** - * HOTFIX - adding reified statement represented by rs resource to model as statement + * HOTFIX - adding a reified statement represented by rs resource to model as statement * * @param m * @return iterator of resources which have the RDF.object property diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/QueryUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/QueryUtils.java index 8397f44ff..aa7861112 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/QueryUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/QueryUtils.java @@ -23,9 +23,9 @@ public class QueryUtils { private static final Logger log = LoggerFactory.getLogger(QueryUtils.class); /** - * Returns new query by substituting marker within given query with given value. + * Returns new query by substituting marker within a given query with given value. * Marker must be in syntax #${MARKER_NAME}. - * For example for marker with name "VALUES" query can look like following one : + * For example, for marker with name "VALUES" query can look like the following one: * SELECT * { * #${VALUES} * } @@ -68,7 +68,7 @@ private static String getValuesClauseHeader(ResultSet resultSet) { private static String getValuesClauseValues(ResultSet resultSet, int rowsCount) { - StringBuffer valuesBuffer = new StringBuffer(); + StringBuilder valuesBuffer = new StringBuilder(); while (resultSet.hasNext() && rowsCount > 0) { rowsCount--; @@ -87,7 +87,7 @@ private static String getValuesClauseValues(ResultSet resultSet, int rowsCount) } /** - * Executes construct query and if it fails executes it with additional debugging information. + * Executes construct query and if it fails, executes it with additional debugging information. * @param query * @param model * @param bindings @@ -104,10 +104,10 @@ public static Model execConstruct(Query query, Model model, QuerySolution bindin /** - * Executes construct query and if it fails executes it with additional debugging information. + * Executes construct query and if it fails, executes it with additional debugging information. * @param query Query to be executed. * @param inputModel Model that is queried. - * @param bindings Input binding used wihin the query. + * @param bindings Input binding used within the query. * @param outputModel Model where the output of the query will be stored. * @return */ @@ -121,7 +121,7 @@ public static Model execConstruct(Query query, Model inputModel, QuerySolution b } /** - * Executes select query and if it fails executes it with additional debugging information. + * Executes select query and if it fails, executes it with additional debugging information. * @param query * @param model * @param bindings @@ -136,25 +136,44 @@ public static ResultSet execSelect(Query query, Model model, QuerySolution bindi ); } - private static T execQuery(QueryExecutor queryExecutor, Query query, Model model, QuerySolution bindings) { - try { - return execQuery( - queryExecutor, - QueryExecutionFactory.create(query, model, bindings), - false); + private static T execQuery(QueryExecutor queryExecutor, + Query query, + Model model, + QuerySolution bindings) { + Dataset dataset = DatasetFactory.create(model); + + try (QueryExecution qexec = QueryExecution.dataset(dataset) + .query(query) + .initialBinding(bindings) + .build()) { + return execQuery(queryExecutor, qexec, false); } catch (RuntimeException ex) { - log.error("Failed execution of query [1] for binding [2], due to exception [3]. " + - "The query [1] will be executed again with detailed logging turned on. " + - "\n\t - query [1]: \"\n{}\n\"" + - "\n\t - binding [2]: \"\n{}\n\"" + - "\n\t - exception [3]: \"\n{}\n\"" - , query, bindings, getStackTrace(ex)); + log.error(""" + Failed execution of query [1] for binding [2], due to exception [3]. \ + The query [1] will be executed again with detailed logging turned on. \ + + \t - query [1]: " + {} + "\ + + \t - binding [2]: " + {} + "\ + + \t - exception [3]: " + {} + \"""" + , query, bindings, getStackTrace(ex)); } + log.error("Executing query [1] again to diagnose the cause ..."); - return execQuery( - queryExecutor, - QueryExecutionFactory.create(query, model, bindings), - true); + + try (QueryExecution qexec = QueryExecution.dataset(dataset) + .query(query) + .initialBinding(bindings) + .build()) { + return execQuery(queryExecutor, qexec, true); + } } private static T execQuery(QueryExecutor queryExecutor, QueryExecution execution, boolean isDebugEnabled) { @@ -205,7 +224,7 @@ public static String sparqlPrefixDeclarations(Model model, boolean includeExtraP Stream.concat( Stream.of(Pair.of("", JenaUtils.getNsPrefixURI(model, ""))),// default namespace Stream.of( - (includeExtraPrefixes // extra namspaces if included + (includeExtraPrefixes // extra namespaces if included ? ExtraPrefixes.getExtraPrefixes().entrySet().stream() .filter(e -> model.getNsPrefixURI(e.getKey()) == null && e.getValue() != null) : Stream.>of() diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/SPINUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/SPINUtils.java index a0fc0980b..ac84e10a9 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/SPINUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/SPINUtils.java @@ -25,7 +25,7 @@ public class SPINUtils { SPipesUtil.init(); } - private static final Set COMMON_PREFIXES = new HashSet() {{ + private static final Set COMMON_PREFIXES = new HashSet<>() {{ add("http://jena.hpl.hp.com/ARQ/function#"); add(SP.NS); add("http://spinrdf.org/spif#"); diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/VariableBindingUtils.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/VariableBindingUtils.java index b9c33b4d3..4cc901344 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/VariableBindingUtils.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/VariableBindingUtils.java @@ -17,7 +17,7 @@ public class VariableBindingUtils { * Returns new variables binding from provided variables binding restricted to listed variables. * @param variablesBinding Variables binding from which values are copied. * @param varNames Names of variables that should be copied to the new binding. - * @throws IllegalStateException If the provided variables binding does not contain a variable with the given name. + * @throws IllegalStateException If the provided variables binding do not contain a variable with the given name. * @return new variables binding */ public static VariablesBinding restrict(VariablesBinding variablesBinding, String... varNames) { @@ -37,7 +37,7 @@ public static VariablesBinding restrict(VariablesBinding variablesBinding, Strin * If the bindings contain conflicting values for the same variable, a warning is logged. * * @param targetVariablesBinding Binding being extended. - * @param extendingVariablesBindingURL Url from which binding is loaded and used to extend the target binding. + * @param extendingVariablesBindingURL Url, from which binding is loaded and used to extend the target binding. * @throws IOException If the binding cannot be loaded from the provided URL. */ public static void extendBindingFromURL(VariablesBinding targetVariablesBinding, URL extendingVariablesBindingURL) throws IOException { diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/util/query/OneStepBackExtendedResultSet.java b/s-pipes-core/src/main/java/cz/cvut/spipes/util/query/OneStepBackExtendedResultSet.java index d218e14ee..b3b2e7295 100644 --- a/s-pipes-core/src/main/java/cz/cvut/spipes/util/query/OneStepBackExtendedResultSet.java +++ b/s-pipes-core/src/main/java/cz/cvut/spipes/util/query/OneStepBackExtendedResultSet.java @@ -12,7 +12,7 @@ /** * ResultSet that extends the original result set by adding bindings from the previous query solution. - * The previous query solution is available under the same variable name with suffix "__previous". + * The previous query solution is available under the same variable name with the suffix "__previous". * *

Example use:

*
@@ -49,7 +49,7 @@ private static List getExtendedResultVars(List originalResultVar
                     "The result set already contains a variable with suffix " + PREVIOUS_BINDING_SUFFIX
                 );
             });
-        List joinedList = new ArrayList();
+        List joinedList = new ArrayList<>();
         joinedList.addAll(originalResultVars);
         joinedList.addAll(originalResultVars.stream()
             .map(v -> v + PREVIOUS_BINDING_SUFFIX)
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/util/JenaUtilsTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/util/JenaUtilsTest.java
index 57cd88cc1..686e176cb 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/util/JenaUtilsTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/util/JenaUtilsTest.java
@@ -20,7 +20,7 @@ public class JenaUtilsTest {
     private static final String HASH_FILE_PREFIX = "hash-example-";
 
     @Test
-    public void computeHash() throws Exception {
+    public void computeHash() {
 
         String[] exampleIds = {"1", "2", "3", "4"};
 
@@ -47,7 +47,7 @@ public void computeHash() throws Exception {
     }
 
     @Test
-    public void getQueryWithModelPrefixesReturnsAllPrefixesFromQuery() throws Exception {
+    public void getQueryWithModelPrefixesReturnsAllPrefixesFromQuery() {
         Model m = ModelFactory.createDefaultModel();
 
         Map prefixMapQuery = createExampleQueryPrefixMap();
@@ -78,7 +78,7 @@ public void getQueryWithModelPrefixesReturnsAllPrefixesFromQuery() throws Except
     }
 
     @Test
-    public void getQueryWithModelPrefixesReturnsAllPrefixesFromModel() throws Exception {
+    public void getQueryWithModelPrefixesReturnsAllPrefixesFromModel() {
         Model m = ModelFactory.createDefaultModel();
 
         Map prefixMapModel = createExampleModelPrefixMap();
@@ -109,7 +109,7 @@ public void getQueryWithModelPrefixesReturnsAllPrefixesFromModel() throws Except
     }
 
     @Test
-    public void getQueryWithModelPrefixesReturnsAllPrefixesFromQueryAndModel() throws Exception {
+    public void getQueryWithModelPrefixesReturnsAllPrefixesFromQueryAndModel() {
         Model m = ModelFactory.createDefaultModel();
 
         Map prefixMapQuery = createExampleQueryPrefixMap();
diff --git a/s-pipes-core/src/test/java/cz/cvut/spipes/util/VariableBindingUtilsTest.java b/s-pipes-core/src/test/java/cz/cvut/spipes/util/VariableBindingUtilsTest.java
index 70c388e3e..fc72aca6e 100644
--- a/s-pipes-core/src/test/java/cz/cvut/spipes/util/VariableBindingUtilsTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/spipes/util/VariableBindingUtilsTest.java
@@ -1,7 +1,5 @@
 package cz.cvut.spipes.util;
 
-import com.sun.net.httpserver.HttpExchange;
-import com.sun.net.httpserver.HttpHandler;
 import com.sun.net.httpserver.HttpServer;
 import cz.cvut.spipes.engine.VariablesBinding;
 import org.junit.jupiter.api.AfterEach;
@@ -21,19 +19,19 @@
 
 class VariableBindingUtilsTest {
 
-    private String testData = """
+    private final String testData = """
             PREFIX : 
             PREFIX s-pipes: 
             
-            :personId 
+            :personId
                s-pipes:has_bound_variable "personId" ;
                s-pipes:has_bound_value "robert-plant" ;
-            .                
+            .
             :personName
               s-pipes:has_bound_variable "personName" ;
               s-pipes:has_bound_value "Robert Plant" ;
             .
-                            
+            
             
               a s-pipes:query_solution ;
               s-pipes:has_binding :personId, :personName .
@@ -44,13 +42,10 @@ class VariableBindingUtilsTest {
     @BeforeEach
     void setup() throws IOException {
         server = HttpServer.create(new InetSocketAddress(0), 0);
-        server.createContext("/test.ttl", new HttpHandler() {
-            @Override
-            public void handle(HttpExchange exchange) throws IOException {
-                exchange.sendResponseHeaders(200, testData.getBytes().length);
-                exchange.getResponseBody().write(testData.getBytes());
-                exchange.close();
-            }
+        server.createContext("/test.ttl", exchange -> {
+            exchange.sendResponseHeaders(200, testData.getBytes().length);
+            exchange.getResponseBody().write(testData.getBytes());
+            exchange.close();
         });
         server.setExecutor(Executors.newCachedThreadPool());
         server.start();
diff --git a/s-pipes-modules/module-sparql-endpoint/src/main/java/cz/cvut/spipes/modules/ExternalSchemExModule.java b/s-pipes-modules/module-sparql-endpoint/src/main/java/cz/cvut/spipes/modules/ExternalSchemExModule.java
index 1bcaaa981..2602d2678 100644
--- a/s-pipes-modules/module-sparql-endpoint/src/main/java/cz/cvut/spipes/modules/ExternalSchemExModule.java
+++ b/s-pipes-modules/module-sparql-endpoint/src/main/java/cz/cvut/spipes/modules/ExternalSchemExModule.java
@@ -13,7 +13,6 @@
 import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.Paths;
 
 @SPipesModule(label = "external schemex", comment = "Compute schemex using external script for a specified sourceFilePath.")
 public class ExternalSchemExModule extends AnnotatedAbstractModule {
@@ -39,7 +38,7 @@ ExecutionContext executeSelf() {
             outputDir.toString()
         };
 
-        ExecUtils.execProgramWithoutExeption(programCall, null);
+        ExecUtils.execProgramWithoutException(programCall, null);
 
         InputStream is = null;
         return ExecutionContextFactory.createContext(

From 7b66dd4a5926903e405198300b74e00b12f74197 Mon Sep 17 00:00:00 2001
From: Evgenii Grigorev 
Date: Wed, 3 Sep 2025 10:18:26 +0200
Subject: [PATCH 14/16] [#324] Refactor s-pipes-core/test to reduce the number
 of warnings

---
 .../java/cz/cvut/jena/JenaIntegrationTest.java | 11 ++++++-----
 .../cz/cvut/jena/OntDocumentManagerTest.java   | 12 ++++--------
 .../cz/cvut/shacl/SHACLIntegrationTest.java    | 18 +++++++++---------
 3 files changed, 19 insertions(+), 22 deletions(-)

diff --git a/s-pipes-core/src/test/java/cz/cvut/jena/JenaIntegrationTest.java b/s-pipes-core/src/test/java/cz/cvut/jena/JenaIntegrationTest.java
index 98957a463..f7f1e632c 100644
--- a/s-pipes-core/src/test/java/cz/cvut/jena/JenaIntegrationTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/jena/JenaIntegrationTest.java
@@ -28,13 +28,14 @@ public void executeQueryWithCustomJavaFunction() {
 
         Query query = QueryFactory.create(queryString);
 
-        QueryExecution qexec = QueryExecutionFactory.create(query, model);
-        ResultSet results = qexec.execSelect();
+        try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
+            ResultSet results = qexec.execSelect();
 
-        assertTrue(results.hasNext(), "No results found");
+            assertTrue(results.hasNext(), "No results found");
 
-        QuerySolution soln = results.nextSolution();
-        assertEquals(soln.getLiteral("nextDay").getString(), "2022-01-02");
+            QuerySolution soln = results.nextSolution();
+            assertEquals("2022-01-02", soln.getLiteral("nextDay").getString());
+        }
     }
 
 }
diff --git a/s-pipes-core/src/test/java/cz/cvut/jena/OntDocumentManagerTest.java b/s-pipes-core/src/test/java/cz/cvut/jena/OntDocumentManagerTest.java
index 76e3a4075..2459c47ce 100644
--- a/s-pipes-core/src/test/java/cz/cvut/jena/OntDocumentManagerTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/jena/OntDocumentManagerTest.java
@@ -4,7 +4,6 @@
 import org.apache.jena.ontology.OntDocumentManager;
 import org.apache.jena.ontology.OntModel;
 import org.apache.jena.ontology.OntModelSpec;
-import org.apache.jena.rdf.model.Model;
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
@@ -18,13 +17,10 @@ public class OntDocumentManagerTest {
     public void getOntologyTriggersReadFailureHandler() {
         OntDocumentManager docManager = OntDocumentManager.getInstance();
         final boolean[] readFailureHandlerIsTriggered = {false};
-        OntDocumentManager.ReadFailureHandler handler = new OntDocumentManager.ReadFailureHandler() {
-            @Override
-            public void handleFailedRead(String url, Model model, Exception e) {
-                log.info("- url: " + url);
-                log.info("- model: " + model);
-                readFailureHandlerIsTriggered[0] = true;
-            }
+        OntDocumentManager.ReadFailureHandler handler = (url, model, e) -> {
+            log.info("- url: {}", url);
+            log.info("- model: {}", model);
+            readFailureHandlerIsTriggered[0] = true;
         };
         docManager.setReadFailureHandler(handler);
         Assertions.assertFalse(readFailureHandlerIsTriggered[0]);
diff --git a/s-pipes-core/src/test/java/cz/cvut/shacl/SHACLIntegrationTest.java b/s-pipes-core/src/test/java/cz/cvut/shacl/SHACLIntegrationTest.java
index 99990f728..70667709a 100644
--- a/s-pipes-core/src/test/java/cz/cvut/shacl/SHACLIntegrationTest.java
+++ b/s-pipes-core/src/test/java/cz/cvut/shacl/SHACLIntegrationTest.java
@@ -69,17 +69,17 @@ public void executeCustomSHACLRDFFunctionWithinQuery() {
 
         Query query = QueryFactory.create(queryString);
 
-        QueryExecution qexec = QueryExecutionFactory.create(query, model);
-        ResultSet results = qexec.execSelect();
-
-        assertTrue(results.hasNext(), "No results found");
+        try (QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
+            ResultSet results = qexec.execSelect();
 
-        QuerySolution soln = results.nextSolution();
-        assertEquals(
-            soln.getResource("sparqlServiceUrl").getURI(),
-            constructServiceUrl(repositoryUrl, graphId)
-        );
+            assertTrue(results.hasNext(), "No results found");
 
+            QuerySolution soln = results.nextSolution();
+            assertEquals(
+                    soln.getResource("sparqlServiceUrl").getURI(),
+                    constructServiceUrl(repositoryUrl, graphId)
+            );
+        }
     }
 
     @Test

From 9ad2b051e808ee86b714056de1dda0e246b1ebb6 Mon Sep 17 00:00:00 2001
From: Miroslav Blasko 
Date: Fri, 17 Oct 2025 23:18:02 +0200
Subject: [PATCH 15/16] [#342] Revert back isReplace beeing final

---
 .../cz/cvut/spipes/modules/BindBySelectModule.java    | 10 +++++++++-
 .../cvut/spipes/modules/BindWithConstantModule.java   | 10 +++++++++-
 .../cvut/spipes/modules/RetrievePrefixesModule.java   | 11 ++++++++++-
 3 files changed, 28 insertions(+), 3 deletions(-)

diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java
index c6102d27e..431b00ba0 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindBySelectModule.java
@@ -19,7 +19,7 @@ public class BindBySelectModule extends AnnotatedAbstractModule {
     private Select selectQuery;
 
     @Parameter(iri = SML.replace)
-    private final boolean isReplace = false;
+    private boolean isReplace = false;
 
     @Override
     public ExecutionContext executeSelf() {
@@ -67,4 +67,12 @@ public Select getSelectQuery() {
     public void setSelectQuery(Select selectQuery) {
         this.selectQuery = selectQuery;
     }
+
+    public boolean isReplace() {
+        return isReplace;
+    }
+
+    public void setReplace(boolean replace) {
+        isReplace = replace;
+    }
 }
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java
index 87438ee98..933041212 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/BindWithConstantModule.java
@@ -20,7 +20,7 @@ public class BindWithConstantModule extends AnnotatedAbstractModule  {
     RDFNode value;
 
     @Parameter(iri = SML.replace)
-    private final boolean isReplace = false;
+    private boolean isReplace = false;
 
     @Override
     public ExecutionContext executeSelf() {
@@ -57,4 +57,12 @@ public RDFNode getValue() {
     public void setValue(RDFNode value) {
         this.value = value;
     }
+
+    public boolean isReplace() {
+        return isReplace;
+    }
+
+    public void setReplace(boolean replace) {
+        isReplace = replace;
+    }
 }
diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java
index d462ee041..70111a088 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/modules/RetrievePrefixesModule.java
@@ -53,7 +53,7 @@ public class RetrievePrefixesModule extends AnnotatedAbstractModule {
     private static final String TYPE_URI = KBSS_MODULE.uri + "retrieve-prefixes";
 
     @Parameter(iri = SML.replace)
-    private final boolean isReplace = false;
+    private boolean isReplace = false;
 
     //TODO refactor -> should be part of execution context
     OntologyDocumentManager ontologyDocumentManager = OntoDocManager.getInstance();
@@ -94,4 +94,13 @@ public String getTypeURI() {
     void setOntologyDocumentManager(OntologyDocumentManager ontologyDocumentManager) {
         this.ontologyDocumentManager = ontologyDocumentManager;
     }
+
+    public boolean isReplace() {
+        return isReplace;
+    }
+
+    public void setReplace(boolean replace) {
+        isReplace = replace;
+    }
+
 }
\ No newline at end of file

From 960e9d57982e42fb108400da83efa520ba53c5dd Mon Sep 17 00:00:00 2001
From: Miroslav Blasko 
Date: Sun, 19 Oct 2025 22:58:25 +0200
Subject: [PATCH 16/16] [#342] Address raw-type warning properly

---
 .../cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java   | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java
index d739109b4..23434fc34 100644
--- a/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java
+++ b/s-pipes-core/src/main/java/cz/cvut/spipes/spin/util/SPINEnhancedNodeFactory.java
@@ -12,11 +12,11 @@
 
 public class SPINEnhancedNodeFactory extends Implementation {
     private final Node type;
-    private Constructor enhNodeConstructor;
+    private Constructor enhNodeConstructor;
 
     private static final Logger log = LoggerFactory.getLogger(SPINEnhancedNodeFactory.class);
 
-    public SPINEnhancedNodeFactory(Node type, Class implClass) {
+    public SPINEnhancedNodeFactory(Node type, Class implClass) {
         this.type = type;
         try {
             enhNodeConstructor = implClass.getConstructor(Node.class, EnhGraph.class);
@@ -29,7 +29,7 @@ public SPINEnhancedNodeFactory(Node type, Class implClass) {
     @Override
     public EnhNode wrap(Node node, EnhGraph eg) {
         try {
-            return (EnhNode) enhNodeConstructor.newInstance(node, eg);
+            return enhNodeConstructor.newInstance(node, eg);
         }
         catch (Throwable t) {
             log.error(t.getMessage(), t);