From f95a3931936fa4c9af29b69951ee152af8ee8d39 Mon Sep 17 00:00:00 2001 From: Andy Seaborne Date: Wed, 20 Nov 2024 16:31:10 +0000 Subject: [PATCH 1/5] Typo and formatting --- .../main/java/org/apache/jena/fuseki/main/cmds/DSGSetup.java | 2 +- .../java/org/apache/jena/fuseki/main/sys/FusekiModules.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/cmds/DSGSetup.java b/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/cmds/DSGSetup.java index 72a684b1189..763d33af7a1 100644 --- a/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/cmds/DSGSetup.java +++ b/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/cmds/DSGSetup.java @@ -107,7 +107,7 @@ private static void setupTDB2(Logger log, String directory, ServerArgs serverArg serverArgs.datasetDescription = "in-memory, with files loaded"; serverArgs.dsg = DatasetGraphFactory.createTxnMem(); - for(String filename : filenames ) { + for ( String filename : filenames ) { String pathname = filename; if ( filename.startsWith("file:") ) pathname = filename.substring("file:".length()); diff --git a/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/sys/FusekiModules.java b/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/sys/FusekiModules.java index a0af6600d7c..8075d644d2b 100644 --- a/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/sys/FusekiModules.java +++ b/jena-fuseki2/jena-fuseki-main/src/main/java/org/apache/jena/fuseki/main/sys/FusekiModules.java @@ -37,7 +37,7 @@ public class FusekiModules { private static FusekiModules systemFusekiModules = autoLoadedFusekiModules; /** - * There is a system wide set of modules used when o other are indicated. + * There is a system wide set of modules used when no other modules are indicated. * These default to the automatically discovered modules. */ public static void setSystemDefault(FusekiModules fusekiModules) { From ca109a3773802664316a95e2c6c5387a3d49752d Mon Sep 17 00:00:00 2001 From: Andy Seaborne Date: Wed, 20 Nov 2024 16:56:28 +0000 Subject: [PATCH 2/5] Mutable list needed to track output settings --- jena-cmds/src/main/java/shacl/shacl_parse.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jena-cmds/src/main/java/shacl/shacl_parse.java b/jena-cmds/src/main/java/shacl/shacl_parse.java index aabdf892775..d0ed0f06825 100644 --- a/jena-cmds/src/main/java/shacl/shacl_parse.java +++ b/jena-cmds/src/main/java/shacl/shacl_parse.java @@ -19,6 +19,7 @@ package shacl; import java.io.PrintStream; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; @@ -96,10 +97,11 @@ protected void processModulesAndArgs() { String[] a = x.split(","); return Arrays.stream(a); }; - List values = getValues(argOutput).stream() + List outputValues = getValues(argOutput).stream() .flatMap(f) .map(s->s.toLowerCase()) .toList(); + List values = new ArrayList<>(outputValues); // Mutable. printText = values.remove("text") || values.remove("t"); printCompact = values.remove("compact") || values.remove("c"); printRDF = values.remove("rdf") || values.remove("r") || values.remove("ttl"); From ac30377732306f0c98bb497a5d9e7a10c2642a42 Mon Sep 17 00:00:00 2001 From: Andy Seaborne Date: Wed, 20 Nov 2024 22:52:05 +0000 Subject: [PATCH 3/5] Don't log when resetting the IRI provider --- .../src/main/java/org/apache/jena/irix/SystemIRIx.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/jena-core/src/main/java/org/apache/jena/irix/SystemIRIx.java b/jena-core/src/main/java/org/apache/jena/irix/SystemIRIx.java index 7fea3d4219f..747edc8b014 100644 --- a/jena-core/src/main/java/org/apache/jena/irix/SystemIRIx.java +++ b/jena-core/src/main/java/org/apache/jena/irix/SystemIRIx.java @@ -40,7 +40,6 @@ private enum ProviderImpl { IRI0, IRI3986 } //private static final ProviderImpl providerImpl = ProviderImpl.IRI3986; // -- System-wide provider. - private static IRIProvider provider = makeFreshSystemProvider(); /** @@ -57,6 +56,7 @@ private enum ProviderImpl { IRI0, IRI3986 } public static final String sysPropertyProvider = "jena.iriprovider"; public static IRIProvider makeFreshSystemProvider() { + ProviderImpl sysProviderImpl = getProviderImpl(); // ** This is the implementation choice point. ** @@ -90,13 +90,11 @@ private static ProviderImpl getProviderImpl() { case "IRI0" -> ProviderImpl.IRI0; default -> null; }; - if ( impl != null ) { - sysProviderImpl = impl; - Log.info(SystemIRIx.class, "IRI Provider: "+impl); - } else { + if ( impl == null ) { Log.error(SystemIRIx.class, "IRI Provider not recognized: "+pNorm); - System.exit(1); + return sysProviderImpl; } + sysProviderImpl = impl; } return sysProviderImpl; } From f6e9c5b0d6665a71eddf4690c2fae142b6074b37 Mon Sep 17 00:00:00 2001 From: Andy Seaborne Date: Thu, 21 Nov 2024 09:18:03 +0000 Subject: [PATCH 4/5] Reformat code --- .../src/main/java/arq/cmdline/ModAlgebra.java | 59 ++--- .../src/main/java/arq/cmdline/ModItem.java | 56 ++-- .../src/main/java/arq/cmdline/ModQueryIn.java | 123 +++++---- jena-cmds/src/main/java/arq/qexpr.java | 247 ++++++++---------- jena-cmds/src/main/java/arq/rupdate.java | 72 +++-- 5 files changed, 254 insertions(+), 303 deletions(-) diff --git a/jena-cmds/src/main/java/arq/cmdline/ModAlgebra.java b/jena-cmds/src/main/java/arq/cmdline/ModAlgebra.java index baa0087fb80..8eb205e6672 100644 --- a/jena-cmds/src/main/java/arq/cmdline/ModAlgebra.java +++ b/jena-cmds/src/main/java/arq/cmdline/ModAlgebra.java @@ -23,59 +23,50 @@ import org.apache.jena.cmd.CmdArgModule; import org.apache.jena.cmd.CmdGeneral; import org.apache.jena.cmd.ModBase; -import org.apache.jena.sparql.algebra.Op ; -import org.apache.jena.sparql.sse.SSE ; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.sse.SSE; -public class ModAlgebra extends ModBase -{ - protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "query", "file") ; +public class ModAlgebra extends ModBase { + protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "query", "file"); - private String queryFilename = null ; - private String queryString = null ; - private Op op = null ; + private String queryFilename = null; + private String queryString = null; + private Op op = null; @Override - public void registerWith(CmdGeneral cmdLine) - { - cmdLine.getUsage().startCategory("Query") ; - cmdLine.add(queryFileDecl, - "--query, --file", - "File containing an algebra query") ; + public void registerWith(CmdGeneral cmdLine) { + cmdLine.getUsage().startCategory("Query"); + cmdLine.add(queryFileDecl, "--query, --file", "File containing an algebra query"); } @Override - public void processArgs(CmdArgModule cmdLine) - { - if ( cmdLine.contains(queryFileDecl) ) - { - queryFilename = cmdLine.getValue(queryFileDecl) ; - queryString = IO.readWholeFileAsUTF8(queryFilename) ; + public void processArgs(CmdArgModule cmdLine) { + if ( cmdLine.contains(queryFileDecl) ) { + queryFilename = cmdLine.getValue(queryFileDecl); + queryString = IO.readWholeFileAsUTF8(queryFilename); } if ( cmdLine.getNumPositional() == 0 && queryFilename == null ) - cmdLine.cmdError("No query string or query file") ; + cmdLine.cmdError("No query string or query file"); if ( cmdLine.getNumPositional() > 1 ) - cmdLine.cmdError("Only one query string allowed") ; + cmdLine.cmdError("Only one query string allowed"); if ( cmdLine.getNumPositional() == 1 && queryFilename != null ) - cmdLine.cmdError("Either query string or query file - not both") ; + cmdLine.cmdError("Either query string or query file - not both"); - - if ( queryFilename == null ) - { - String qs = cmdLine.getPositionalArg(0) ; - queryString = cmdLine.indirect(qs) ; + if ( queryFilename == null ) { + String qs = cmdLine.getPositionalArg(0); + queryString = cmdLine.indirect(qs); } } - public Op getOp() - { + public Op getOp() { if ( op != null ) - return op ; - op = SSE.parseOp(queryString) ; + return op; + op = SSE.parseOp(queryString); if ( op == null ) - System.err.println("Failed to parse : "+queryString) ; - return op ; + System.err.println("Failed to parse : " + queryString); + return op; } } diff --git a/jena-cmds/src/main/java/arq/cmdline/ModItem.java b/jena-cmds/src/main/java/arq/cmdline/ModItem.java index c3570463052..c16f67e19e6 100644 --- a/jena-cmds/src/main/java/arq/cmdline/ModItem.java +++ b/jena-cmds/src/main/java/arq/cmdline/ModItem.java @@ -23,57 +23,51 @@ import org.apache.jena.cmd.CmdArgModule; import org.apache.jena.cmd.CmdGeneral; import org.apache.jena.cmd.ModBase; -import org.apache.jena.sparql.sse.Item ; -import org.apache.jena.sparql.sse.SSE ; +import org.apache.jena.sparql.sse.Item; +import org.apache.jena.sparql.sse.SSE; -public class ModItem extends ModBase -{ - protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "file") ; +public class ModItem extends ModBase { + protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "file"); - private String filename = null ; - private String parseString = null ; - private Item item = null ; + private String filename = null; + private String parseString = null; + private Item item = null; @Override - public void registerWith(CmdGeneral cmdLine) - { - cmdLine.getUsage().startCategory("Item") ; - cmdLine.add(queryFileDecl, "--file=", "File") ; + public void registerWith(CmdGeneral cmdLine) { + cmdLine.getUsage().startCategory("Item"); + cmdLine.add(queryFileDecl, "--file=", "File"); } @Override - public void processArgs(CmdArgModule cmdLine) - { - if ( cmdLine.contains(queryFileDecl) ) - { - filename = cmdLine.getValue(queryFileDecl) ; - parseString = IO.readWholeFileAsUTF8(filename) ; - return ; + public void processArgs(CmdArgModule cmdLine) { + if ( cmdLine.contains(queryFileDecl) ) { + filename = cmdLine.getValue(queryFileDecl); + parseString = IO.readWholeFileAsUTF8(filename); + return; } if ( cmdLine.getNumPositional() == 0 && filename == null ) - cmdLine.cmdError("No query string or query file") ; + cmdLine.cmdError("No query string or query file"); if ( cmdLine.getNumPositional() > 1 ) - cmdLine.cmdError("Only one query string allowed") ; + cmdLine.cmdError("Only one query string allowed"); if ( cmdLine.getNumPositional() == 1 && filename != null ) - cmdLine.cmdError("Either query string or query file - not both") ; + cmdLine.cmdError("Either query string or query file - not both"); - if ( filename == null ) - { - String qs = cmdLine.getPositionalArg(0) ; - parseString = cmdLine.indirect(qs) ; + if ( filename == null ) { + String qs = cmdLine.getPositionalArg(0); + parseString = cmdLine.indirect(qs); } } - public Item getItem() - { + public Item getItem() { if ( item != null ) - return item ; + return item; // Need to get the (outer) prologue. - item = SSE.parseItem(parseString) ; - return item ; + item = SSE.parseItem(parseString); + return item; } } diff --git a/jena-cmds/src/main/java/arq/cmdline/ModQueryIn.java b/jena-cmds/src/main/java/arq/cmdline/ModQueryIn.java index 712a4d92faa..c866c91f54b 100644 --- a/jena-cmds/src/main/java/arq/cmdline/ModQueryIn.java +++ b/jena-cmds/src/main/java/arq/cmdline/ModQueryIn.java @@ -16,99 +16,99 @@ * limitations under the License. */ -package arq.cmdline ; +package arq.cmdline; -import java.io.IOException ; +import java.io.IOException; import org.apache.jena.cmd.*; -import org.apache.jena.query.Query ; -import org.apache.jena.query.QueryFactory ; -import org.apache.jena.query.Syntax ; -import org.apache.jena.shared.JenaException ; +import org.apache.jena.query.Query; +import org.apache.jena.query.QueryFactory; +import org.apache.jena.query.Syntax; +import org.apache.jena.shared.JenaException; import org.apache.jena.shared.NotFoundException; -import org.apache.jena.sparql.ARQInternalErrorException ; -import org.apache.jena.util.FileUtils ; +import org.apache.jena.sparql.ARQInternalErrorException; +import org.apache.jena.util.FileUtils; public class ModQueryIn extends ModBase { - protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "query", "file") ; - protected final ArgDecl querySyntaxDecl = new ArgDecl(ArgDecl.HasValue, "syntax", "syn", "in") ; - protected final ArgDecl queryBaseDecl = new ArgDecl(ArgDecl.HasValue, "base") ; + protected final ArgDecl queryFileDecl = new ArgDecl(ArgDecl.HasValue, "query", "file"); + protected final ArgDecl querySyntaxDecl = new ArgDecl(ArgDecl.HasValue, "syntax", "syn", "in"); + protected final ArgDecl queryBaseDecl = new ArgDecl(ArgDecl.HasValue, "base"); - private Syntax defaultQuerySyntax = Syntax.syntaxARQ ; - private Syntax querySyntax = null ; - private String queryFilename = null ; - private String queryString = null ; - private Query query = null ; - private String baseURI = null ; + private Syntax defaultQuerySyntax = Syntax.syntaxARQ; + private Syntax querySyntax = null; + private String queryFilename = null; + private String queryString = null; + private Query query = null; + private String baseURI = null; public ModQueryIn(Syntax defaultSyntax) { - defaultQuerySyntax = defaultSyntax ; - querySyntax = defaultSyntax ; + defaultQuerySyntax = defaultSyntax; + querySyntax = defaultSyntax; } @Override public void registerWith(CmdGeneral cmdLine) { - cmdLine.getUsage().startCategory("Query") ; - cmdLine.add(queryFileDecl, "--query, --file", "File containing a query") ; - cmdLine.add(querySyntaxDecl, "--syntax, --in", "Syntax of the query") ; - cmdLine.add(queryBaseDecl, "--base", "Base URI for the query") ; + cmdLine.getUsage().startCategory("Query"); + cmdLine.add(queryFileDecl, "--query, --file", "File containing a query"); + cmdLine.add(querySyntaxDecl, "--syntax, --in", "Syntax of the query"); + cmdLine.add(queryBaseDecl, "--base", "Base URI for the query"); } @Override public void processArgs(CmdArgModule cmdline) throws IllegalArgumentException { if ( cmdline.contains(queryBaseDecl) ) - baseURI = cmdline.getValue(queryBaseDecl) ; + baseURI = cmdline.getValue(queryBaseDecl); if ( cmdline.contains(queryFileDecl) ) { - queryFilename = cmdline.getValue(queryFileDecl) ; - querySyntax = Syntax.guessQueryFileSyntax(queryFilename, defaultQuerySyntax) ; + queryFilename = cmdline.getValue(queryFileDecl); + querySyntax = Syntax.guessQueryFileSyntax(queryFilename, defaultQuerySyntax); } if ( cmdline.getNumPositional() == 0 && queryFilename == null ) - cmdline.cmdError("No query string or query file") ; + cmdline.cmdError("No query string or query file"); if ( cmdline.getNumPositional() > 1 ) - cmdline.cmdError("Only one query string allowed") ; + cmdline.cmdError("Only one query string allowed"); if ( cmdline.getNumPositional() == 1 && queryFilename != null ) - cmdline.cmdError("Either query string or query file - not both") ; + cmdline.cmdError("Either query string or query file - not both"); if ( queryFilename == null ) { // One positional argument. - String qs = cmdline.getPositionalArg(0) ; + String qs = cmdline.getPositionalArg(0); if ( cmdline.matchesIndirect(qs) ) - querySyntax = Syntax.guessQueryFileSyntax(qs, defaultQuerySyntax) ; + querySyntax = Syntax.guessQueryFileSyntax(qs, defaultQuerySyntax); - queryString = cmdline.indirect(qs) ; + queryString = cmdline.indirect(qs); } // Set syntax if ( cmdline.contains(querySyntaxDecl) ) { // short name - String s = cmdline.getValue(querySyntaxDecl) ; - Syntax syn = Syntax.lookup(s) ; + String s = cmdline.getValue(querySyntaxDecl); + Syntax syn = Syntax.lookup(s); if ( syn == null ) - cmdline.cmdError("Unrecognized syntax: " + s) ; - querySyntax = syn ; + cmdline.cmdError("Unrecognized syntax: " + s); + querySyntax = syn; } } public Syntax getQuerySyntax() { - return querySyntax ; + return querySyntax; } public Query getQuery() { if ( query != null ) - return query ; + return query; if ( queryFilename != null && queryString != null ) { - System.err.println("Both query string and query file name given") ; - throw new TerminationException(1) ; + System.err.println("Both query string and query file name given"); + throw new TerminationException(1); } if ( queryFilename == null && queryString == null ) { - System.err.println("No query string and no query file name given") ; - throw new TerminationException(1) ; + System.err.println("No query string and no query file name given"); + throw new TerminationException(1); } try { @@ -116,40 +116,39 @@ public Query getQuery() { if ( queryFilename.equals("-") ) { try { // Stderr? - queryString = FileUtils.readWholeFileAsUTF8(System.in) ; + queryString = FileUtils.readWholeFileAsUTF8(System.in); // And drop into next if } catch (IOException ex) { - throw new CmdException("Error reading stdin", ex) ; + throw new CmdException("Error reading stdin", ex); } } else { try { - query = QueryFactory.read(queryFilename, baseURI, getQuerySyntax()) ; - return query ; + query = QueryFactory.read(queryFilename, baseURI, getQuerySyntax()); + return query; } catch (NotFoundException ex) { - throw new JenaException("Failed to load Query: "+ex.getMessage()); + throw new JenaException("Failed to load Query: " + ex.getMessage()); } } } - query = QueryFactory.create(queryString, baseURI, getQuerySyntax()) ; - return query ; + query = QueryFactory.create(queryString, baseURI, getQuerySyntax()); + return query; } catch (ARQInternalErrorException intEx) { - System.err.println(intEx.getMessage()) ; + System.err.println(intEx.getMessage()); if ( intEx.getCause() != null ) { - System.err.println("Cause:") ; - intEx.getCause().printStackTrace(System.err) ; - System.err.println() ; + System.err.println("Cause:"); + intEx.getCause().printStackTrace(System.err); + System.err.println(); } - intEx.printStackTrace(System.err) ; - throw new TerminationException(99) ; - } - catch (JenaException ex) { - System.err.println(ex.getMessage()) ; - throw new TerminationException(2) ; + intEx.printStackTrace(System.err); + throw new TerminationException(99); + } catch (JenaException ex) { + System.err.println(ex.getMessage()); + throw new TerminationException(2); } catch (Exception ex) { - System.out.flush() ; - ex.printStackTrace(System.err) ; - throw new TerminationException(98) ; + System.out.flush(); + ex.printStackTrace(System.err); + throw new TerminationException(98); } } } diff --git a/jena-cmds/src/main/java/arq/qexpr.java b/jena-cmds/src/main/java/arq/qexpr.java index 5b66138a23c..74bde00486d 100644 --- a/jena-cmds/src/main/java/arq/qexpr.java +++ b/jena-cmds/src/main/java/arq/qexpr.java @@ -18,215 +18,194 @@ package arq; -import org.apache.jena.Jena ; -import org.apache.jena.atlas.io.IndentedWriter ; -import org.apache.jena.atlas.logging.LogCtl ; +import org.apache.jena.Jena; +import org.apache.jena.atlas.io.IndentedWriter; +import org.apache.jena.atlas.logging.LogCtl; import org.apache.jena.cmd.ArgDecl; import org.apache.jena.cmd.CmdException; import org.apache.jena.cmd.CmdLineArgs; import org.apache.jena.cmd.TerminationException; -import org.apache.jena.graph.Node ; -import org.apache.jena.query.ARQ ; -import org.apache.jena.query.QueryParseException ; -import org.apache.jena.riot.out.NodeFmtLib ; -import org.apache.jena.shared.PrefixMapping ; -import org.apache.jena.sparql.ARQConstants ; -import org.apache.jena.sparql.core.Prologue ; -import org.apache.jena.sparql.engine.ExecutionContext ; -import org.apache.jena.sparql.expr.Expr ; -import org.apache.jena.sparql.expr.ExprEvalException ; -import org.apache.jena.sparql.expr.ExprLib ; -import org.apache.jena.sparql.expr.NodeValue ; -import org.apache.jena.sparql.function.FunctionEnv ; -import org.apache.jena.sparql.sse.WriterSSE ; -import org.apache.jena.sparql.util.ExprUtils ; -import org.apache.jena.sparql.util.NodeFactoryExtra ; -import org.apache.jena.sys.JenaSystem ; +import org.apache.jena.graph.Node; +import org.apache.jena.query.ARQ; +import org.apache.jena.query.QueryParseException; +import org.apache.jena.riot.out.NodeFmtLib; +import org.apache.jena.shared.PrefixMapping; +import org.apache.jena.sparql.ARQConstants; +import org.apache.jena.sparql.core.Prologue; +import org.apache.jena.sparql.engine.ExecutionContext; +import org.apache.jena.sparql.expr.Expr; +import org.apache.jena.sparql.expr.ExprEvalException; +import org.apache.jena.sparql.expr.ExprLib; +import org.apache.jena.sparql.expr.NodeValue; +import org.apache.jena.sparql.function.FunctionEnv; +import org.apache.jena.sparql.sse.WriterSSE; +import org.apache.jena.sparql.util.ExprUtils; +import org.apache.jena.sparql.util.NodeFactoryExtra; +import org.apache.jena.sys.JenaSystem; /** A program to execute expressions from the command line. */ -public class qexpr -{ +public class qexpr { static { - LogCtl.setLogging() ; - JenaSystem.init() ; + LogCtl.setLogging(); + JenaSystem.init(); } - public static void main (String... argv) - { + public static void main(String...argv) { try { - main2(argv) ; - } - catch (TerminationException ex) { System.exit(ex.getCode()) ; } - catch (CmdException ex) - { - System.err.println(ex.getMessage()) ; + main2(argv); + } catch (TerminationException ex) { + System.exit(ex.getCode()); + } catch (CmdException ex) { + System.err.println(ex.getMessage()); if ( ex.getCause() != null ) - ex.getCause().printStackTrace(System.err) ; + ex.getCause().printStackTrace(System.err); } } - public static void execAndReturn(String... argv) - { + public static void execAndReturn(String...argv) { try { - main2(argv) ; - } - catch (TerminationException ex) { return ; } - catch (CmdException ex) - { - System.err.println(ex.getMessage()) ; + main2(argv); + } catch (TerminationException ex) { + return; + } catch (CmdException ex) { + System.err.println(ex.getMessage()); if ( ex.getCause() != null ) - ex.getCause().printStackTrace(System.err) ; + ex.getCause().printStackTrace(System.err); } } - public static void main2(String... argv) - { + public static void main2(String...argv) { - CmdLineArgs cl = new CmdLineArgs(argv) ; + CmdLineArgs cl = new CmdLineArgs(argv); - ArgDecl helpDecl = new ArgDecl(ArgDecl.NoValue, "h", "help") ; - cl.add(helpDecl) ; + ArgDecl helpDecl = new ArgDecl(ArgDecl.NoValue, "h", "help"); + cl.add(helpDecl); - ArgDecl verboseDecl = new ArgDecl(ArgDecl.NoValue, "v", "verbose") ; - cl.add(verboseDecl) ; + ArgDecl verboseDecl = new ArgDecl(ArgDecl.NoValue, "v", "verbose"); + cl.add(verboseDecl); - ArgDecl versionDecl = new ArgDecl(ArgDecl.NoValue, "ver", "version", "V") ; - cl.add(versionDecl) ; + ArgDecl versionDecl = new ArgDecl(ArgDecl.NoValue, "ver", "version", "V"); + cl.add(versionDecl); - ArgDecl quietDecl = new ArgDecl(ArgDecl.NoValue, "q", "quiet") ; - cl.add(quietDecl) ; + ArgDecl quietDecl = new ArgDecl(ArgDecl.NoValue, "q", "quiet"); + cl.add(quietDecl); - ArgDecl reduceDecl = new ArgDecl(ArgDecl.NoValue, "reduce", "fold", "simplify" ) ; - cl.add(reduceDecl) ; + ArgDecl reduceDecl = new ArgDecl(ArgDecl.NoValue, "reduce", "fold", "simplify"); + cl.add(reduceDecl); - ArgDecl strictDecl = new ArgDecl(ArgDecl.NoValue, "strict") ; - cl.add(strictDecl) ; + ArgDecl strictDecl = new ArgDecl(ArgDecl.NoValue, "strict"); + cl.add(strictDecl); - ArgDecl printDecl = new ArgDecl(ArgDecl.HasValue, "print") ; - cl.add(printDecl) ; + ArgDecl printDecl = new ArgDecl(ArgDecl.HasValue, "print"); + cl.add(printDecl); try { - cl.process() ; - } catch (IllegalArgumentException ex) - { - System.err.println(ex.getMessage()) ; - usage(System.err) ; - throw new CmdException() ; + cl.process(); + } catch (IllegalArgumentException ex) { + System.err.println(ex.getMessage()); + usage(System.err); + throw new CmdException(); } - if ( cl.contains(helpDecl) ) - { - usage() ; - throw new TerminationException(0) ; + if ( cl.contains(helpDecl) ) { + usage(); + throw new TerminationException(0); } - if ( cl.contains(versionDecl) ) - { - System.out.println("ARQ Version: "+ARQ.VERSION+" (Jena: "+Jena.VERSION+")") ; - throw new TerminationException(0) ; + if ( cl.contains(versionDecl) ) { + System.out.println("ARQ Version: " + ARQ.VERSION + " (Jena: " + Jena.VERSION + ")"); + throw new TerminationException(0); } // ==== General things - boolean verbose = cl.contains(verboseDecl) ; - boolean quiet = cl.contains(quietDecl) ; + boolean verbose = cl.contains(verboseDecl); + boolean quiet = cl.contains(quietDecl); if ( cl.contains(strictDecl) ) - ARQ.setStrictMode() ; + ARQ.setStrictMode(); - boolean actionCopySubstitute = cl.contains(reduceDecl) ; - boolean actionPrintPrefix = false ; - boolean actionPrintSPARQL = false ; - boolean actionPrint = cl.contains(printDecl) ; + boolean actionCopySubstitute = cl.contains(reduceDecl); + boolean actionPrintPrefix = false; + boolean actionPrintSPARQL = false; + boolean actionPrint = cl.contains(printDecl); - for ( String v : cl.getValues( printDecl ) ) - { - if ( v.equalsIgnoreCase( "prefix" ) || v.equalsIgnoreCase( "op" ) ) - { + for ( String v : cl.getValues(printDecl) ) { + if ( v.equalsIgnoreCase("prefix") || v.equalsIgnoreCase("op") ) { actionPrintPrefix = true; - } - else if ( v.equalsIgnoreCase( "expr" ) ) - { + } else if ( v.equalsIgnoreCase("expr") ) { actionPrintSPARQL = true; - } - else - { - System.err.println( "Unknown print form: " + v ); - throw new TerminationException( 0 ); + } else { + System.err.println("Unknown print form: " + v); + throw new TerminationException(0); } } // ==== Do it - for ( int i = 0 ; i < cl.getNumPositional() ; i++ ) - { - String exprStr = cl.getPositionalArg(i) ; - exprStr = cl.indirect(exprStr) ; + for ( int i = 0 ; i < cl.getNumPositional() ; i++ ) { + String exprStr = cl.getPositionalArg(i); + exprStr = cl.indirect(exprStr); try { - PrefixMapping pmap = PrefixMapping.Factory.create() ; - pmap.setNsPrefixes(ARQConstants.getGlobalPrefixMap()) ; - pmap.setNsPrefix("", "http://example/") ; - pmap.setNsPrefix("ex", "http://example/ns#") ; + PrefixMapping pmap = PrefixMapping.Factory.create(); + pmap.setNsPrefixes(ARQConstants.getGlobalPrefixMap()); + pmap.setNsPrefix("", "http://example/"); + pmap.setNsPrefix("ex", "http://example/ns#"); - Expr expr = ExprUtils.parse(exprStr, pmap) ; - if ( actionPrint ) - { - IndentedWriter iOut = IndentedWriter.stdout; + Expr expr = ExprUtils.parse(exprStr, pmap); + if ( actionPrint ) { + IndentedWriter iOut = IndentedWriter.stdout; if ( actionPrintSPARQL ) { ExprUtils.fmtSPARQL(iOut, expr); iOut.ensureStartOfLine(); } if ( actionPrintPrefix ) { - WriterSSE.out(iOut, expr, new Prologue(pmap)) ; + WriterSSE.out(iOut, expr, new Prologue(pmap)); iOut.ensureStartOfLine(); } iOut.flush(); - continue ; + continue; } if ( verbose ) - System.out.print(expr.toString()+" => ") ; + System.out.print(expr.toString() + " => "); try { - if ( actionCopySubstitute ) - { - Expr e = ExprLib.foldConstants(expr) ; - System.out.println(e) ; - } - else - { + if ( actionCopySubstitute ) { + Expr e = ExprLib.foldConstants(expr); + System.out.println(e); + } else { // Default action - ARQ.getContext().set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime()) ; - FunctionEnv env = new ExecutionContext(ARQ.getContext(), null, null, null) ; - NodeValue r = expr.eval(null, env) ; - //System.out.println(r.asQuotedString()) ; - Node n = r.asNode() ; - String s = NodeFmtLib.displayStr(n) ; - System.out.println(s) ; + ARQ.getContext().set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime()); + FunctionEnv env = new ExecutionContext(ARQ.getContext(), null, null, null); + NodeValue r = expr.eval(null, env); + // System.out.println(r.asQuotedString()) ; + Node n = r.asNode(); + String s = NodeFmtLib.displayStr(n); + System.out.println(s); } - } catch (ExprEvalException ex) - { + } catch (ExprEvalException ex) { ex.printStackTrace(); - System.out.println("Exception: "+ex.getMessage()) ; - throw new TerminationException(2) ; + System.out.println("Exception: " + ex.getMessage()); + throw new TerminationException(2); } - } catch (QueryParseException ex) - { - System.err.println("Parse error: "+ex.getMessage()) ; - throw new TerminationException(2) ; + } catch (QueryParseException ex) { + System.err.println("Parse error: " + ex.getMessage()); + throw new TerminationException(2); } } } - static void usage() { usage(System.out) ; } + static void usage() { + usage(System.out); + } - static void usage(java.io.PrintStream out) - { - out.println("Usage: [--print=[prefix|expr]] expression") ; + static void usage(java.io.PrintStream out) { + out.println("Usage: [--print=[prefix|expr]] expression"); } - } +} diff --git a/jena-cmds/src/main/java/arq/rupdate.java b/jena-cmds/src/main/java/arq/rupdate.java index 92139a27400..3888ef40669 100644 --- a/jena-cmds/src/main/java/arq/rupdate.java +++ b/jena-cmds/src/main/java/arq/rupdate.java @@ -18,75 +18,63 @@ package arq; -import java.util.List ; +import java.util.List; import org.apache.jena.cmd.ArgDecl; import org.apache.jena.cmd.CmdException; import org.apache.jena.update.*; -import arq.cmdline.CmdARQ ; -import arq.cmdline.ModRemote ; +import arq.cmdline.CmdARQ; +import arq.cmdline.ModRemote; -public class rupdate extends CmdARQ -{ - static final ArgDecl updateArg = new ArgDecl(ArgDecl.HasValue, "update", "file") ; +public class rupdate extends CmdARQ { + static final ArgDecl updateArg = new ArgDecl(ArgDecl.HasValue, "update", "file"); - protected ModRemote modRemote = new ModRemote() ; + protected ModRemote modRemote = new ModRemote(); - List requestFiles = null ; + List requestFiles = null; - public static void main(String... argv) - { - new rupdate(argv).mainRun() ; + public static void main(String...argv) { + new rupdate(argv).mainRun(); } - protected rupdate(String[] argv) - { - super(argv) ; - super.add(updateArg, "--update=FILE", "Update commands to execute") ; - super.addModule(modRemote) ; + protected rupdate(String[] argv) { + super(argv); + super.add(updateArg, "--update=FILE", "Update commands to execute"); + super.addModule(modRemote); } @Override - protected void processModulesAndArgs() - { - requestFiles = getValues(updateArg) ; // ???? - super.processModulesAndArgs() ; + protected void processModulesAndArgs() { + requestFiles = getValues(updateArg); // ???? + super.processModulesAndArgs(); } - @Override - protected String getSummary() - { - return getCommandName()+" --service=URL --update=" ; + protected String getSummary() { + return getCommandName() + " --service=URL --update="; } @Override - protected void exec() - { - if ( modRemote.getServiceURL() == null ) - { - throw new CmdException("No endpoint given") ; + protected void exec() { + if ( modRemote.getServiceURL() == null ) { + throw new CmdException("No endpoint given"); } - String endpoint = modRemote.getServiceURL() ; + String endpoint = modRemote.getServiceURL(); - for ( String filename : requestFiles ) - { - UpdateRequest req = UpdateFactory.read( filename ); - exec( endpoint, req ); + for ( String filename : requestFiles ) { + UpdateRequest req = UpdateFactory.read(filename); + exec(endpoint, req); } - for ( String requestString : super.getPositional() ) - { - requestString = indirect( requestString ); - UpdateRequest req = UpdateFactory.create( requestString ); - exec( endpoint, req ); + for ( String requestString : super.getPositional() ) { + requestString = indirect(requestString); + UpdateRequest req = UpdateFactory.create(requestString); + exec(endpoint, req); } } - private void exec(String endpoint, UpdateRequest req) - { + private void exec(String endpoint, UpdateRequest req) { UpdateExecution.service(endpoint).update(req).execute(); } } - From d1e91ea757e37bec748a5f461762f37c8e9e635c Mon Sep 17 00:00:00 2001 From: Andy Seaborne Date: Wed, 20 Nov 2024 17:30:16 +0000 Subject: [PATCH 5/5] GH-2862: Command line arguments from a file --- jena-cmds/pom.xml | 12 ++ .../org/apache/jena/cmd/ArgModuleGeneral.java | 6 +- .../main/java/org/apache/jena/cmd/Args.java | 136 ++++++++++++++++++ .../org/apache/jena/cmd/CmdArgModule.java | 2 +- .../java/org/apache/jena/cmd/CmdGeneral.java | 1 - .../java/org/apache/jena/cmd/CmdLineArgs.java | 11 +- .../main/java/org/apache/jena/cmd/Usage.java | 91 ++++++------ .../org/apache/jena/cmds/TestCmdLine.java | 90 +++++++++++- jena-cmds/testing/cmd/args-bad-1 | 2 + jena-cmds/testing/cmd/args-good-1 | 12 ++ jena-cmds/testing/cmd/args-good-2 | 5 + jena-cmds/testing/cmd/args-good-3 | 2 + 12 files changed, 308 insertions(+), 62 deletions(-) create mode 100644 jena-cmds/src/main/java/org/apache/jena/cmd/Args.java create mode 100644 jena-cmds/testing/cmd/args-bad-1 create mode 100644 jena-cmds/testing/cmd/args-good-1 create mode 100644 jena-cmds/testing/cmd/args-good-2 create mode 100644 jena-cmds/testing/cmd/args-good-3 diff --git a/jena-cmds/pom.xml b/jena-cmds/pom.xml index 46e56aac951..b19565e4da8 100644 --- a/jena-cmds/pom.xml +++ b/jena-cmds/pom.xml @@ -171,6 +171,18 @@ test + + org.junit.jupiter + junit-jupiter-params + test + + + + org.junit.platform + junit-platform-suite-engine + test + + diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/ArgModuleGeneral.java b/jena-cmds/src/main/java/org/apache/jena/cmd/ArgModuleGeneral.java index 20aa017cd5f..00da6b785e9 100644 --- a/jena-cmds/src/main/java/org/apache/jena/cmd/ArgModuleGeneral.java +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/ArgModuleGeneral.java @@ -19,6 +19,10 @@ package org.apache.jena.cmd; public interface ArgModuleGeneral extends ArgModule { - // Registration phase for usage messages + /** Registration phase for arguments, including usage messages */ public abstract void registerWith(CmdGeneral cmdLine); + + /** Processing phase after the command line has been parsed and the arguments present are known. */ + @Override + public default void processArgs(CmdArgModule cmdLine) {} } diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/Args.java b/jena-cmds/src/main/java/org/apache/jena/cmd/Args.java new file mode 100644 index 00000000000..31fd84fe5ce --- /dev/null +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/Args.java @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.jena.cmd; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class Args { + // ---- Arguments in a file. + + /** + * Pre-process the command line. + *

+ * If the command line is "@file", then take the argument from the contents of the file. + * If there is no "@file", return the function parameter string array object. + *

+ * The file format is: + *

    + *
  • One line per argument or argument value. Lines are striped of horizontal white space.
  • + *
  • Any "@file" in the file is not processed
  • + *
  • Lines can be "--argument", "--argument value". The line is tokenized at the first space after non-white space
  • + *
  • Using "--argument=value" is preferred.
  • + *
  • Arguments are ended by end-of-file, a line which is "--", or a line which does not start with "-". Subsequent lines are positional values.
  • + *
  • There is no escape mechanism. The arguments/argument-values are processed as if they appeared on the command line after shell escaping.
  • + *
  • Comments are lines with first non-whitespace character of {@code #} + *
  • Blank lines and lines of only horizontal white space are ignores
  • + * Example: + *
    +     * # Example arguments file
    +     *     ## Another comment
    +     * --arg1
    +     * --arg2 value
    +     *   --arg3=value
    +     * # Use --arg= for an empty string value
    +     * --empty=
    +     *   -q
    +     *
    +     *   # Previous line ignored
    +     *   ## --notAnArgument
    +     * 
+ * @return The command line for argument and values. + */ + public static String[] argsPrepare(String[] argv) { + List argsList = Arrays.asList(argv); + // Count! + List indirects = argsList.stream().filter(s->s.startsWith("@")).toList(); + if ( indirects.isEmpty() ) + return argv; + if ( indirects.size() > 1 ) + throw new CmdException("Multiple arguments files"); + if ( argsList.size() > 1 ) + // @args and something else + throw new CmdException("Arguments file must be the only item on the command line"); + String indirect = indirects.get(0); + String fn = indirect.substring(1); + try { + if ( fn.isEmpty() ) + throw new CmdException("Empty arguments file name"); + Path path = Path.of(fn); + if ( ! Files.exists(path) ) + throw new CmdException("No such file: "+fn); + List lines = Files.readAllLines(path); + String[] args2 = toArgsArray(lines); + return args2; + } catch (NoSuchFileException ex) { + throw new CmdException("No such file: "+fn); + } catch (IOException ex) { + ex.printStackTrace(); + throw new CmdException("Failed to process args file: "+ex.getMessage()); + } + } + + /** Convert the lines of the file to argument/value pairs. */ + private static String[] toArgsArray(List lines) { + // Each line is "--arg" or "--arg SPC value" + List outcome = new ArrayList<>(); + boolean positionalsStarted = false; + for ( String s : lines ) { + s = s.strip(); + if ( s.startsWith("#") ) + // Comment + continue; + if ( s.isEmpty() ) + continue; + if ( positionalsStarted ) { + outcome.add(s); + continue; + } + + if ( s.startsWith("@") ) + throw new CmdException("Argument file may not contain an argument file reference"); + if ( ! s.startsWith("-") ) { + // positional + //throw new CmdException("Command line in file does not start with a '-': "+s); + positionalsStarted = true; + outcome.add(s); + continue; + } + + // argument or argument and value + // Split on first space after argument, if any. + int idx = s.indexOf(' '); + if ( idx == -1 ) { + outcome.add(s.stripTrailing()); + continue; + } + + String a = s.substring(0,idx); + String v = s.substring(idx+1).strip(); + outcome.add(a); + outcome.add(v); + } + return outcome.toArray(new String[outcome.size()]); + } +} diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdArgModule.java b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdArgModule.java index bc13b9dde6e..545e601beee 100644 --- a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdArgModule.java +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdArgModule.java @@ -23,7 +23,7 @@ public abstract class CmdArgModule extends CmdMain { - List modules = new ArrayList<>(); + private List modules = new ArrayList<>(); protected CmdArgModule(String[] argv) { super(argv); diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdGeneral.java b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdGeneral.java index f917302b71b..6054b7c63c2 100644 --- a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdGeneral.java +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdGeneral.java @@ -27,7 +27,6 @@ public abstract class CmdGeneral extends CmdArgModule { protected ModGeneral modGeneral = new ModGeneral(this::printHelp); protected ModVersion modVersion = new ModVersion(true); - // Could be turned into a module but these are convenient as inherited flags protected CmdGeneral(String[] argv) { super(argv); diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdLineArgs.java b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdLineArgs.java index 1d42c4eff00..73192f5310d 100644 --- a/jena-cmds/src/main/java/org/apache/jena/cmd/CmdLineArgs.java +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/CmdLineArgs.java @@ -50,7 +50,7 @@ public void process() throws IllegalArgumentException { // ---- Setting the ArgDecls - /** Add an argument to those to be accepted on the command line. + /** Add an argument declaration sto those to be accepted on the command line. * @param argName Name * @param hasValue True if the command takes a (string) value * @return The command line processor object @@ -59,7 +59,7 @@ public CmdLineArgs add(String argName, boolean hasValue) { return add(new ArgDecl(hasValue, argName)); } - /** Add an argument to those to be accepted on the command line. + /** Add an argument declaration to those to be accepted on the command line. * Argument order reflects ArgDecl. * @param hasValue True if the command takes a (string) value * @param argName Name @@ -69,7 +69,7 @@ public CmdLineArgs add(boolean hasValue, String argName) { return add(new ArgDecl(hasValue, argName)); } - /** Add an argument object + /** Add an argument declaration * @param argDecl Argument to add * @return The command line processor object */ @@ -83,7 +83,7 @@ public CmdLineArgs add(ArgDecl argDecl) { } /** - * Remove an argument and any values set for this argument. + * Remove an argument declaration and any values set for this argument. * @param argDecl Argument to remove * @return The command line processor object */ @@ -194,7 +194,7 @@ private CmdLineArgs addArgWorker(Arg arg, String value) { // ---- Indirection - static final String DefaultIndirectMarker = "@"; + static final String DefaultIndirectMarker = "^"; public boolean matchesIndirect(String s) { return matchesIndirect(s, DefaultIndirectMarker); } public boolean matchesIndirect(String s, String marker) { return s.startsWith(marker); } @@ -243,7 +243,6 @@ public String indirect(String s, String marker) { public boolean hasArg(ArgDecl argDecl) { return getArg(argDecl) != null; } - /** Get the argument associated with the argument declaration. * Actually returns the LAST one seen * @param argDecl Argument declaration to find diff --git a/jena-cmds/src/main/java/org/apache/jena/cmd/Usage.java b/jena-cmds/src/main/java/org/apache/jena/cmd/Usage.java index 766044313a5..8713c3dd5e9 100644 --- a/jena-cmds/src/main/java/org/apache/jena/cmd/Usage.java +++ b/jena-cmds/src/main/java/org/apache/jena/cmd/Usage.java @@ -27,7 +27,7 @@ public class Usage { - public static class Category { + private static class Category { String desc; List entries = new ArrayList<>(); Category(String desc) { @@ -35,60 +35,53 @@ public static class Category { } } - private static class Entry { - String arg; - String msg; - Entry(String arg, String msg) { - this.arg = arg; - this.msg = msg; - } - } + private record Entry(String arg, String msg) {} - private List categories = new ArrayList<>(); + private List categories = new ArrayList<>(); - public Usage() { - // Start with an unnamed category - startCategory(null); - } + public Usage() { + // Start with an unnamed category + startCategory(null); + } - public void startCategory(String desc) { - categories.add(new Category(desc)); - } + public void startCategory(String desc) { + categories.add(new Category(desc)); + } - public void addUsage(String argName, String msg) { - current().entries.add(new Entry(argName, msg)); - } + public void addUsage(String argName, String msg) { + current().entries.add(new Entry(argName, msg)); + } - public void output(PrintStream out) { - output(new IndentedWriter(out)); - } + public void output(PrintStream out) { + output(new IndentedWriter(out)); + } - public void output(IndentedWriter out) { - int INDENT1 = 2; - int INDENT2 = 4; - out.incIndent(INDENT1); + public void output(IndentedWriter out) { + int INDENT1 = 2; + int INDENT2 = 4; + out.incIndent(INDENT1); - Iter.reverseIterate(categories, c->{ - if ( c.desc != null ) { - out.println(c.desc); - } - out.incIndent(INDENT2); - for ( final Entry e : c.entries ) { - out.print(e.arg); - if ( e.msg != null ) { - out.pad(20); - out.print(" "); - out.print(e.msg); - } - out.println(); - } - out.decIndent(INDENT2); - }); - out.decIndent(INDENT1); - out.flush(); - } + Iter.reverseIterate(categories, c->{ + if ( c.desc != null ) { + out.println(c.desc); + } + out.incIndent(INDENT2); + for ( final Entry e : c.entries ) { + out.print(e.arg); + if ( e.msg != null ) { + out.pad(20); + out.print(" "); + out.print(e.msg); + } + out.println(); + } + out.decIndent(INDENT2); + }); + out.decIndent(INDENT1); + out.flush(); + } - private Category current() { - return categories.get(categories.size() - 1); - } + private Category current() { + return categories.get(categories.size() - 1); + } } diff --git a/jena-cmds/src/test/java/org/apache/jena/cmds/TestCmdLine.java b/jena-cmds/src/test/java/org/apache/jena/cmds/TestCmdLine.java index 7555c552a1b..43cd231c7b7 100644 --- a/jena-cmds/src/test/java/org/apache/jena/cmds/TestCmdLine.java +++ b/jena-cmds/src/test/java/org/apache/jena/cmds/TestCmdLine.java @@ -18,20 +18,29 @@ package org.apache.jena.cmds; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.util.Arrays; import java.util.Iterator; -import org.junit.Test; - import org.apache.jena.cmd.Arg; +import org.apache.jena.cmd.Args; import org.apache.jena.cmd.ArgDecl; import org.apache.jena.cmd.CmdException; import org.apache.jena.cmd.CmdLineArgs; public class TestCmdLine { + + private static String DIR = "testing/cmd/"; + @Test public void test_Simple1() { String args[] = {""}; @@ -117,7 +126,7 @@ public void test_addSetting() { } - @Test(expected = CmdException.class) + @Test public void test_removeArg1() { String args[] = {"--arg=V1", "-v"}; CmdLineArgs cl = new CmdLineArgs(args); @@ -125,6 +134,79 @@ public void test_removeArg1() { cl.add(argA); cl.removeArg(argA); // Exception. - cl.process(); + assertThrows(CmdException.class, ()->cl.process()); + } + + + @Test + public void args_no_file_1() { + String[] args = {}; + testArgsFileGood(args, new String[0]); } + + @Test + public void args_no_file_2() { + String[] args = {"-q", "-v", "positional"}; + testArgsFileGood(args, "-q", "-v", "positional"); + } + + @Test + public void args_file_01() { + String[] args = {"@"+DIR+"args-good-1"}; + testArgsFileGood(args, "--arg", "--arg1", "value1", "--arg2=value2", "--empty=", "--trailingspaces", "-q", "positional 1", "positional 2"); + } + + @Test + public void args_file_02() { + String[] args = {"@"+DIR+"args-good-2"}; + testArgsFileGood(args, "-arg", "--", "positional"); + } + + @Test + public void args_file_03() { + String[] args = {"@"+DIR+"args-good-3"}; + testArgsFileGood(args, "text"); + } + + + @Test + public void args_file_bad_01() { + String[] args = {"@"+DIR+"args-good-1", "--another"}; + testArgsFileBad(args); + } + + @Test + public void args_file_bad_02() { + String[] args = {"@"+DIR+"args-good-1", "@"+DIR+"args-good-2"}; + testArgsFileBad(args); + } + + @Test + public void args_file_bad_03() { + String[] args = {"@"}; + testArgsFileBad(args); + } + + @Test + public void args_file_bad_04() { + String[] args = {"@ filename"}; + testArgsFileBad(args); + } + + @Test + public void args_file_bad_file_01() { + String[] args = {"@"+DIR+"args-bad-1"}; + testArgsFileBad(args); + } + + private void testArgsFileGood(String[] args, String...expected) { + String[] args2 = Args.argsPrepare(args); + //assertArrayEquals(expected, args2, ()->{ return "Expected: "+Arrays.asList(expected)+" Got: "+Arrays.asList(args2)}); + assertArrayEquals(expected, args2, ()->("Expected: "+Arrays.asList(expected)+" Got: "+Arrays.asList(args2))); + } + + private void testArgsFileBad(String[] args) { + assertThrows(CmdException.class, ()->Args.argsPrepare(args)); + } + } diff --git a/jena-cmds/testing/cmd/args-bad-1 b/jena-cmds/testing/cmd/args-bad-1 new file mode 100644 index 00000000000..b540d783ff3 --- /dev/null +++ b/jena-cmds/testing/cmd/args-bad-1 @@ -0,0 +1,2 @@ +# Bad argument file. +@another diff --git a/jena-cmds/testing/cmd/args-good-1 b/jena-cmds/testing/cmd/args-good-1 new file mode 100644 index 00000000000..7eecbdaa603 --- /dev/null +++ b/jena-cmds/testing/cmd/args-good-1 @@ -0,0 +1,12 @@ +# Comment. First blank line has zero chars the second has 4 spaces +--arg + +--arg1 value1 +--arg2=value2 +--empty= + + --trailingspaces +-q + # comment +positional 1 +positional 2 diff --git a/jena-cmds/testing/cmd/args-good-2 b/jena-cmds/testing/cmd/args-good-2 new file mode 100644 index 00000000000..5017ecff7c3 --- /dev/null +++ b/jena-cmds/testing/cmd/args-good-2 @@ -0,0 +1,5 @@ +-arg +-- +positional + + diff --git a/jena-cmds/testing/cmd/args-good-3 b/jena-cmds/testing/cmd/args-good-3 new file mode 100644 index 00000000000..9c9cfbffa5f --- /dev/null +++ b/jena-cmds/testing/cmd/args-good-3 @@ -0,0 +1,2 @@ +# A word, no leading - +text