View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  
21  package org.waarp.vitam.common;
22  
23  import org.apache.commons.cli.CommandLine;
24  import org.apache.commons.cli.CommandLineParser;
25  import org.apache.commons.cli.DefaultParser;
26  import org.apache.commons.cli.Option;
27  import org.apache.commons.cli.Options;
28  import org.apache.commons.cli.ParseException;
29  import org.waarp.common.exception.InvalidArgumentException;
30  import org.waarp.common.logging.SysErrLogger;
31  import org.waarp.common.utility.ParametersChecker;
32  
33  import java.io.File;
34  import java.io.FileInputStream;
35  import java.io.IOException;
36  import java.io.InputStream;
37  import java.util.Properties;
38  
39  /**
40   * Utility common to Ingest and DIP
41   */
42  public class WaarpCommon {
43    public static final String FOR_SIMPLE_MANDATORY_ARGUMENTS =
44        "(*) for mandatory arguments";
45    public static final String FOR_MANDATORY_ARGUMENTS =
46        "(*) for mandatory arguments, (+) except if -o config option";
47    public static final String CONFIGURATION_FILE_CANNOT_BE_READ =
48        "Configuration file cannot be read: ";
49    private static final Option WAARP =
50        Option.builder("w").longOpt("waarp").hasArg(true).required(true)
51              .desc("(*) Waarp configuration file").build();
52    private static final Option WAARP_MODEL =
53        Option.builder("m").longOpt("model").hasArg(true).required(false).desc(
54            "Waarp model between R66 or a specific script file " +
55            "that do send to the partner").build();
56    private static final Option WAARP_NR =
57        Option.builder("w").longOpt("waarp").hasArg(true).required(false)
58              .desc("(*) Waarp configuration file").build();
59    private static final Option HELP =
60        Option.builder("h").longOpt("help").hasArg(false)
61              .desc("Get the corresponding help").build();
62    private static final Options HELP_ONLY = new Options().addOption(HELP);
63  
64    private WaarpCommon() {
65      // Nothing
66    }
67  
68    /**
69     * Check if help is required
70     *
71     * @param args
72     *
73     * @return True if help required
74     *
75     * @throws ParseException
76     */
77    public static boolean checkHelp(String[] args) {
78      CommandLineParser parser = new DefaultParser();
79      CommandLine first = null;
80      try {
81        first = parser.parse(HELP_ONLY, args, true);
82        return first.hasOption('h');
83      } catch (ParseException ignore) {//NOSONAR
84        SysErrLogger.FAKE_LOGGER.ignoreLog(ignore);
85      }
86      return false;
87    }
88  
89    /**
90     * TaskOption class
91     */
92    public static class TaskOption {
93      private static final Option FILE =
94          Option.builder("f").longOpt("file").required(true).hasArg(true)
95                .desc("(*) Path of the local file").build();
96      private static final Option TENANT =
97          Option.builder("t").longOpt("tenant").required(true).hasArg(true)
98                .type(Number.class).desc("(+) Tenant Id").build();
99      private static final Option ACCESS =
100         Option.builder("a").longOpt("access").required(true).hasArg(true)
101               .desc("(+) Access Contract").build();
102     private static final Option PARTNER =
103         Option.builder("p").longOpt("partner").required(true).hasArg(true)
104               .desc("(+) Waarp Partner").build();
105     private static final Option RULE =
106         Option.builder("r").longOpt("rule").required(true).hasArg(true)
107               .desc("(+) Waarp Rule").build();
108     private static final Option SESSION =
109         Option.builder("s").longOpt("session").hasArg(true)
110               .desc("Application Session Id").build();
111     private static final Option CERTIFICATE =
112         Option.builder("c").longOpt("certificate").hasArg(true)
113               .desc("Personal Certificate").build();
114     private static final Option CONF =
115         Option.builder("o").longOpt("conf").hasArg(true).desc(
116             "(+) Configuration file containing tenant, access, partner, rule," +
117             " waarp, certificate options. " +
118             "Any specific options set independently will " +
119             "replace the value contained in this file").build();
120     private static final Option TENANT_NR =
121         Option.builder(TENANT.getOpt()).longOpt(TENANT.getLongOpt())
122               .required(false).hasArg(true).type(Number.class)
123               .desc(TENANT.getDescription()).build();
124     private static final Option ACCESS_NR =
125         Option.builder(ACCESS.getOpt()).longOpt(ACCESS.getLongOpt())
126               .required(false).hasArg(true).desc(ACCESS.getDescription())
127               .build();
128     private static final Option PARTNER_NR =
129         Option.builder(PARTNER.getOpt()).longOpt(PARTNER.getLongOpt())
130               .required(false).hasArg(true).desc(PARTNER.getDescription())
131               .build();
132     private static final Option RULE_NR =
133         Option.builder(RULE.getOpt()).longOpt(RULE.getLongOpt()).required(false)
134               .hasArg(true).desc(RULE.getDescription()).build();
135     private static final Options STANDARD =
136         new Options().addOption(FILE).addOption(SESSION).addOption(CONF)
137                      .addOption(CERTIFICATE).addOption(TENANT_NR)
138                      .addOption(ACCESS_NR).addOption(PARTNER_NR)
139                      .addOption(RULE_NR).addOption(WAARP_MODEL)
140                      .addOption(WAARP_NR).addOption(HELP);
141     private static final Options MANDATORY_NO_CONF =
142         new Options().addOption(FILE).addOption(SESSION).addOption(CONF)
143                      .addOption(TENANT).addOption(ACCESS).addOption(CERTIFICATE)
144                      .addOption(PARTNER).addOption(RULE).addOption(WAARP_MODEL)
145                      .addOption(WAARP);
146 
147     private final String waarpConfigurationFile;
148     private final String path;
149     private final int tenantId;
150     private final String applicationSessionId;
151     private final String personalCertificate;
152     private final String accessContract;
153     private final String waarpPartner;
154     private final String waarpRule;
155     private final String waarpModel;
156 
157     public TaskOption(final String waarpConfigurationFile, final String path,
158                       final int tenantId, final String applicationSessionId,
159                       final String personalCertificate,
160                       final String accessContract, final String waarpPartner,
161                       final String waarpRule, final String waarpModel)
162         throws ParseException {
163       try {
164         ParametersChecker
165             .checkParameter("Arguments should be clean and not null",
166                             waarpConfigurationFile, path, accessContract,
167                             waarpPartner, waarpRule);
168         ParametersChecker
169             .checkSanityString(waarpConfigurationFile, path, accessContract,
170                                waarpPartner, waarpRule, waarpModel,
171                                applicationSessionId, personalCertificate);
172         if (tenantId < 0) {
173           throw new ParseException("Illegal value");
174         }
175       } catch (IllegalArgumentException | InvalidArgumentException e) {
176         throw new ParseException("Incorrect arguments");
177       }
178       this.waarpConfigurationFile = waarpConfigurationFile;
179       this.path = path;
180       this.tenantId = tenantId;
181       this.applicationSessionId = applicationSessionId;
182       this.personalCertificate = personalCertificate;
183       this.accessContract = accessContract;
184       this.waarpPartner = waarpPartner;
185       this.waarpRule = waarpRule;
186       this.waarpModel = waarpModel;
187     }
188 
189     /**
190      * Standard options for Task
191      *
192      * @param options
193      */
194     public static void setStandardTaskOptions(Options options) {
195       for (Option option : STANDARD.getOptions()) {
196         options.addOption(option);
197       }
198     }
199 
200     /**
201      * @param cmd
202      *
203      * @return the TaskOption from CommandLine
204      *
205      * @throws ParseException
206      */
207     public static TaskOption getTaskOption(final CommandLine cmd,
208                                            final String[] args)
209         throws ParseException {
210       CommandLineParser parser = new DefaultParser();
211       Properties properties = new Properties();
212       if (cmd.hasOption('o')) {
213         // Use Configuration file
214         File conf = new File(cmd.getOptionValue('o'));
215         if (!conf.canRead()) {
216           throw new ParseException(
217               CONFIGURATION_FILE_CANNOT_BE_READ + conf.getAbsolutePath());
218         }
219         try (InputStream inputStream = new FileInputStream(conf)) {
220           properties.load(inputStream);
221         } catch (IOException e) {
222           throw new ParseException(
223               CONFIGURATION_FILE_CANNOT_BE_READ + conf.getAbsolutePath() +
224               " since " + e.getMessage());
225         }
226       } else {
227         // Check mandatory parameters if not using Configuration file
228         parser.parse(MANDATORY_NO_CONF, args, true);
229       }
230       final String stenant = properties.getProperty(TENANT.getLongOpt(),
231                                                     cmd.getOptionValue(
232                                                         TENANT.getOpt()));
233       final String accessContract = properties.getProperty(ACCESS.getLongOpt(),
234                                                            cmd.getOptionValue(
235                                                                ACCESS
236                                                                    .getOpt()));
237       final String personalCertificate = properties
238           .getProperty(CERTIFICATE.getLongOpt(),
239                        cmd.getOptionValue(CERTIFICATE.getOpt(), null));
240       final String waarpPartner = properties.getProperty(PARTNER.getLongOpt(),
241                                                          cmd.getOptionValue(
242                                                              PARTNER.getOpt()));
243       final String waarpRule = properties
244           .getProperty(RULE.getLongOpt(), cmd.getOptionValue(RULE.getOpt()));
245       final String waarpConfiguration = properties
246           .getProperty(WAARP.getLongOpt(), cmd.getOptionValue(WAARP.getOpt()));
247       final String path = cmd.getOptionValue('f');
248       final String applicationSessionId;
249       final String waarpModel;
250 
251       if (cmd.hasOption('m')) {
252         String temp = cmd.getOptionValue('m');
253         if (temp.isEmpty()) {
254           temp = null;
255         }
256         waarpModel = temp;
257       } else {
258         waarpModel = null;
259       }
260       if (cmd.hasOption('s')) {
261         String temp = cmd.getOptionValue('s');
262         if (temp.isEmpty()) {
263           temp = null;
264         }
265         applicationSessionId = temp;
266       } else {
267         applicationSessionId = null;
268       }
269       final int tenantId;
270       try {
271         tenantId = Integer.parseInt(stenant);
272         if (tenantId < 0) {
273           throw new NumberFormatException("Tenant Id must be positive");
274         }
275       } catch (NumberFormatException e) {
276         throw new ParseException("Tenant Id must be a positive integer");
277       }
278       return new TaskOption(waarpConfiguration, path, tenantId,
279                             applicationSessionId, personalCertificate,
280                             accessContract, waarpPartner, waarpRule,
281                             waarpModel);
282     }
283 
284     public String getWaarpConfigurationFile() {
285       return waarpConfigurationFile;
286     }
287 
288     public String getPath() {
289       return path;
290     }
291 
292     public int getTenantId() {
293       return tenantId;
294     }
295 
296     public String getApplicationSessionId() {
297       return applicationSessionId;
298     }
299 
300     public String getPersonalCertificate() {
301       return personalCertificate;
302     }
303 
304     public String getAccessContract() {
305       return accessContract;
306     }
307 
308     public String getWaarpPartner() {
309       return waarpPartner;
310     }
311 
312     public String getWaarpRule() {
313       return waarpRule;
314     }
315 
316     public String getWaarpModel() {
317       return waarpModel;
318     }
319   }
320 
321   /**
322    * MonitorOption class
323    */
324   public static class MonitorOption {
325     private final String stopFilePath;
326     private final String waarpConfiguration;
327     private final int elapseInSecond;
328 
329     public MonitorOption(final String stopFilePath,
330                          final String waarpConfiguration,
331                          final int elapseInSecond) throws ParseException {
332       try {
333         ParametersChecker
334             .checkParameter("Arguments should be clean and not null",
335                             stopFilePath, waarpConfiguration);
336         ParametersChecker.checkSanityString(stopFilePath, waarpConfiguration);
337         if (elapseInSecond < 0) {
338           throw new ParseException("Illegal value");
339         }
340       } catch (IllegalArgumentException | InvalidArgumentException e) {
341         throw new ParseException("Incorrect arguments");
342       }
343       this.stopFilePath = stopFilePath;
344       this.waarpConfiguration = waarpConfiguration;
345       this.elapseInSecond = elapseInSecond;
346     }
347 
348     /**
349      * Standard options for Monitor
350      *
351      * @param options
352      */
353     public static void setStandardMonitorOptions(Options options) {
354       options
355           .addRequiredOption("s", "stopfile", true, "(*) Path of the stop file")
356           .addOption(Option.builder("e").longOpt("elapse").hasArg(true)
357                            .type(Number.class).desc("Elapse time in seconds")
358                            .build()).addOption(WAARP).addOption(HELP);
359     }
360 
361     /**
362      * Standard options for Monitor
363      *
364      * @param options
365      */
366     public static void addRetryMonitorOptions(Options options) {
367       options.addOption(
368           Option.builder("r").longOpt("retry").hasArg(true).type(Number.class)
369                 .desc("Retry for pooling operation (default 3)").build())
370              .addOption(Option.builder("d").longOpt("delay").hasArg(true)
371                               .type(Number.class).desc(
372                      "Delay between 2 retries for pooling in ms greater than " +
373                      "50 (default 100)").build());
374     }
375 
376     /**
377      * @param cmd
378      *
379      * @return the MonitorOption from CommandLine
380      *
381      * @throws ParseException
382      */
383     public static MonitorOption gestMonitorOption(CommandLine cmd,
384                                                   String[] args)
385         throws ParseException {
386       final String stopFilePath = cmd.getOptionValue('s');
387       final String waarpConfiguration = cmd.getOptionValue('w');
388       final int elapseInSecond;
389       if (cmd.hasOption('e')) {
390         final String selapse = cmd.getOptionValue('e');
391         try {
392           elapseInSecond = Integer.parseInt(selapse);
393           if (elapseInSecond < 1) {
394             throw new NumberFormatException("Elapse time must be positive");
395           }
396         } catch (NumberFormatException e) {
397           throw new ParseException("Elapse time must be a positive integer");
398         }
399       } else {
400         elapseInSecond = 10;
401       }
402       int retry = OperationCheck.getRetry();
403       int delay = OperationCheck.getDelay();
404       if (cmd.hasOption('r')) {
405         String sretry = cmd.getOptionValue('r');
406         try {
407           retry = Integer.parseInt(sretry);
408           if (retry < 1) {
409             throw new NumberFormatException("Retry must be positive");
410           }
411         } catch (NumberFormatException e) {
412           throw new ParseException("Retry must be a positive integer");
413         }
414       }
415       if (cmd.hasOption('d')) {
416         String sdelay = cmd.getOptionValue('d');
417         try {
418           delay = Integer.parseInt(sdelay);
419           if (delay < 50) {
420             throw new NumberFormatException("Delay must be greater than 50");
421           }
422         } catch (NumberFormatException e) {
423           throw new ParseException("Delay must be greater than 50");
424         }
425       }
426       OperationCheck.setRetry(retry, delay);
427       return new MonitorOption(stopFilePath, waarpConfiguration,
428                                elapseInSecond);
429     }
430 
431     public String getStopFilePath() {
432       return stopFilePath;
433     }
434 
435     public String getWaarpConfiguration() {
436       return waarpConfiguration;
437     }
438 
439     public int getElapseInSecond() {
440       return elapseInSecond;
441     }
442   }
443 
444 }