1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package eu.ehri.project.commands;
21
22 import com.tinkerpop.frames.FramedGraph;
23 import eu.ehri.project.models.base.Accessor;
24 import eu.ehri.project.api.Api;
25 import eu.ehri.project.api.ApiFactory;
26 import org.apache.commons.cli.CommandLine;
27 import org.apache.commons.cli.CommandLineParser;
28 import org.apache.commons.cli.DefaultParser;
29 import org.apache.commons.cli.HelpFormatter;
30 import org.apache.commons.cli.Options;
31 import org.apache.commons.cli.ParseException;
32 import org.slf4j.Logger;
33
34 import java.io.PrintWriter;
35 import java.io.StringWriter;
36 import java.util.Optional;
37
38
39
40
41
42
43
44
45
46
47
48
49 public abstract class BaseCommand implements Command {
50
51 static final Logger logger = org.slf4j.LoggerFactory.getLogger(Command.class);
52 protected final Options options = new Options();
53 private final CommandLineParser parser = new DefaultParser();
54
55 protected void setCustomOptions(Options options) {
56 }
57
58 public abstract String getHelp();
59
60 public abstract String getUsage();
61
62
63
64
65
66
67
68
69
70 public final int exec(FramedGraph<?> graph, String[] args) throws Exception {
71 setCustomOptions(options);
72 return execWithOptions(graph, parser.parse(options, args));
73 }
74
75 @Override
76 public String getDetailedHelp() {
77 HelpFormatter formatter = new HelpFormatter();
78 setCustomOptions(options);
79 StringWriter out = new StringWriter();
80 formatter.printHelp(
81 new PrintWriter(out), 80, getUsage(), "\n" + getHelp() + "\n\n",
82 options, 5, 0, "\n" + getHelpFooter());
83 return out.toString();
84 }
85
86
87
88
89
90
91
92
93
94
95 public abstract int execWithOptions(FramedGraph<?> graph,
96 CommandLine cmdLine) throws Exception;
97
98
99
100
101
102
103
104
105 CommandLine getCmdLine(String[] args) throws ParseException {
106 setCustomOptions(options);
107 return parser.parse(options, args);
108 }
109
110 protected Api api(FramedGraph<?> graph, Accessor accessor) {
111 return ApiFactory.withLogging(graph, accessor);
112 }
113
114
115
116
117
118
119
120
121 Optional<String> getLogMessage(String msg) {
122 return (msg == null || msg.trim().isEmpty()) ? Optional.empty() : Optional.of(msg);
123 }
124 }