use of org.apache.commons.cli.DefaultParser in project accumulo by apache.
the class ShellPluginConfigurationCommand method getPluginClass.
public static <T> Class<? extends T> getPluginClass(final String tableName, final Shell shellState, final Class<T> clazz, final Property pluginProp) {
Map<String, String> props;
try {
props = shellState.getAccumuloClient().tableOperations().getConfiguration(tableName);
} catch (AccumuloException | TableNotFoundException e) {
return null;
}
for (Entry<String, String> ent : props.entrySet()) {
if (ent.getKey().equals(pluginProp.toString())) {
Class<? extends T> pluginClazz;
String[] args = new String[2];
try {
Options o = new Options();
o.addOption(OptUtil.tableOpt());
args[0] = "-t";
args[1] = tableName;
CommandLine cl = new DefaultParser().parse(o, args);
pluginClazz = shellState.getClassLoader(cl, shellState).loadClass(ent.getValue()).asSubclass(clazz);
} catch (ClassNotFoundException e) {
LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Class not found {}", e.getMessage());
return null;
} catch (ParseException e) {
LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Error parsing table: {} {}", Arrays.toString(args), e.getMessage());
return null;
} catch (TableNotFoundException e) {
LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Table not found: {} {}", tableName, e.getMessage());
return null;
} catch (Exception e) {
LoggerFactory.getLogger(ShellPluginConfigurationCommand.class).error("Error: {}", e.getMessage());
return null;
}
return pluginClazz;
}
}
return null;
}
use of org.apache.commons.cli.DefaultParser in project accumulo by apache.
the class Shell method execCommand.
public void execCommand(String input, boolean ignoreAuthTimeout, boolean echoPrompt) throws IOException {
audit.info("{}", sanitize(getDefaultPrompt() + input));
if (echoPrompt) {
writer.print(getDefaultPrompt());
writer.println(input);
}
if (input.startsWith(COMMENT_PREFIX)) {
return;
}
String[] fields;
try {
fields = new QuotedStringTokenizer(input).getTokens();
} catch (BadArgumentException e) {
printException(e);
++exitCode;
return;
}
if (fields.length == 0) {
return;
}
String command = fields[0];
fields = fields.length > 1 ? Arrays.copyOfRange(fields, 1, fields.length) : new String[] {};
Command sc = null;
if (command.isEmpty()) {
++exitCode;
printException(new BadArgumentException("Unrecognized empty command", command, -1));
} else {
try {
// Obtain the command from the command table
sc = commandFactory.get(command);
if (sc == null) {
writer.println(String.format("Unknown command \"%s\". Enter \"help\" for a list possible commands.", command));
writer.flush();
return;
}
long duration = System.nanoTime() - lastUserActivity;
if (!(sc instanceof ExitCommand) && !ignoreAuthTimeout && (duration < 0 || duration > authTimeout)) {
writer.println("Shell has been idle for too long. Please re-authenticate.");
boolean authFailed = true;
do {
String pwd = readMaskedLine("Enter current password for '" + accumuloClient.whoami() + "': ", '*');
if (pwd == null) {
writer.println();
return;
}
try {
authFailed = !accumuloClient.securityOperations().authenticateUser(accumuloClient.whoami(), new PasswordToken(pwd));
} catch (Exception e) {
++exitCode;
printException(e);
}
if (authFailed) {
writer.print("Invalid password. ");
}
} while (authFailed);
lastUserActivity = System.nanoTime();
}
// Get the options from the command on how to parse the string
Options parseOpts = sc.getOptionsWithHelp();
// Parse the string using the given options
CommandLine cl = new DefaultParser().parse(parseOpts, fields);
int actualArgLen = cl.getArgs().length;
int expectedArgLen = sc.numArgs();
if (cl.hasOption(helpOption)) {
// Display help if asked to; otherwise execute the command
sc.printHelp(this);
} else if (expectedArgLen != NO_FIXED_ARG_LENGTH_CHECK && actualArgLen != expectedArgLen) {
++exitCode;
// Check for valid number of fixed arguments (if not
// negative; negative means it is not checked, for
// vararg-like commands)
printException(new IllegalArgumentException(String.format("Expected %d argument%s. There %s %d.", expectedArgLen, expectedArgLen == 1 ? "" : "s", actualArgLen == 1 ? "was" : "were", actualArgLen)));
sc.printHelp(this);
} else {
int tmpCode = sc.execute(input, cl, this);
exitCode += tmpCode;
writer.flush();
}
} catch (ConstraintViolationException e) {
++exitCode;
printConstraintViolationException(e);
} catch (TableNotFoundException e) {
++exitCode;
if (getTableName().equals(e.getTableName())) {
setTableName("");
}
printException(e);
} catch (ParseException e) {
if (e instanceof MissingOptionException && Stream.of(fields).anyMatch(IS_HELP_OPT)) {
// not really an error if the exception shows a required option is missing
// and the user is asking for help
} else {
++exitCode;
printException(e);
}
sc.printHelp(this);
} catch (UserInterruptException e) {
++exitCode;
} catch (Exception e) {
++exitCode;
printException(e);
}
}
writer.flush();
}
use of org.apache.commons.cli.DefaultParser in project accumulo by apache.
the class ListTabletsCommandTest method mockTest.
@Test
public void mockTest() throws Exception {
ListTabletsCommand cmd = new TestListTabletsCommand();
AccumuloClient client = EasyMock.createMock(AccumuloClient.class);
ClientContext context = EasyMock.createMock(ClientContext.class);
TableOperations tableOps = EasyMock.createMock(TableOperations.class);
InstanceOperations instOps = EasyMock.createMock(InstanceOperations.class);
Shell shellState = EasyMock.createMock(Shell.class);
Options opts = cmd.getOptions();
CommandLineParser parser = new DefaultParser();
String[] args = { "-t", tableName };
CommandLine cli = parser.parse(opts, args);
EasyMock.expect(shellState.getAccumuloClient()).andReturn(client).anyTimes();
EasyMock.expect(shellState.getContext()).andReturn(context).anyTimes();
EasyMock.expect(client.tableOperations()).andReturn(tableOps).anyTimes();
Map<String, String> idMap = new TreeMap<>();
idMap.put(tableName, tableId.canonical());
EasyMock.expect(tableOps.tableIdMap()).andReturn(idMap);
assertEquals("Incorrect number of rows: " + rows, rows.size(), 3);
EasyMock.replay(client, context, tableOps, instOps, shellState);
cmd.execute("listTablets -t " + tableName, cli, shellState);
EasyMock.verify(client, context, tableOps, instOps, shellState);
}
use of org.apache.commons.cli.DefaultParser in project MassBank-web by MassBank.
the class AddMetaData method main.
public static void main(String[] arguments) throws Exception {
// load version and print
final Properties properties = new Properties();
try {
properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("project.properties"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("AddMetaData version: " + properties.getProperty("version"));
// parse command line
Options options = new Options();
options.addOption("a", "all", false, "execute all operations");
options.addOption("p", "publication", false, "format PUBLICATION tag from given DOI to follow the guidelines of ACS");
options.addOption("n", "name", false, "fix common problems in CH$NAME tag");
options.addOption("l", "link", false, "add links to CH$LINK tag");
options.addOption("r", "rewrite", false, "read and rewrite the file.");
options.addOption("ms_focused_ion", false, "Inspect MS$FOCUSED_ION");
options.addOption(null, "add-inchikey", false, "Add or fix InChIKey from the value in CH$IUPAC");
options.addOption(null, "add-pubchemcid", false, "Add or fix PubChem CID from InChIKey and flag Problems.");
CommandLine cmd = null;
try {
cmd = new DefaultParser().parse(options, arguments);
} catch (ParseException e) {
// oops, something went wrong
System.err.println("Parsing command line failed. Reason: " + e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AddMetaData [OPTIONS] <FILE|DIR> [<FILE|DIR> ...]", options);
System.exit(1);
}
if (cmd.getArgList().size() == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("AddMetaData [OPTIONS] <FILE|DIR> [<FILE|DIR> ...]", options);
System.exit(1);
}
// find all files in arguments and all *.txt files in directories and subdirectories
// specified in arguments
List<File> recordfiles = new ArrayList<>();
for (String argument : cmd.getArgList()) {
File argumentf = new File(argument);
if (argumentf.isFile() && FilenameUtils.getExtension(argument).equals("txt")) {
recordfiles.add(argumentf);
} else if (argumentf.isDirectory()) {
recordfiles.addAll(FileUtils.listFiles(argumentf, new String[] { "txt" }, true));
} else {
logger.warn("Argument " + argument + " could not be processed.");
}
}
if (recordfiles.size() == 0) {
logger.error("No files found.");
System.exit(1);
}
// validate all files
logger.trace("Validating " + recordfiles.size() + " files");
AtomicBoolean doAddPubchemCid = new AtomicBoolean(cmd.hasOption("add-pubchemcid"));
recordfiles.parallelStream().forEach(filename -> {
String recordString;
logger.info("Working on " + filename + ".");
try {
recordString = FileUtils.readFileToString(filename, StandardCharsets.UTF_8);
// read record in less strict mode
Set<String> config = new HashSet<String>();
config.add("legacy");
config.add("weak");
Record record = Validator.validate(recordString, "", config);
if (record == null) {
System.err.println("Validation of \"" + filename + "\" failed. Exiting.");
System.exit(1);
} else if (record.DEPRECATED()) {
System.exit(0);
}
String recordstring2 = recordString;
if (doAddPubchemCid.get()) {
recordstring2 = doAddPubchemCID(record);
}
config = new HashSet<String>();
if (!recordString.equals(recordstring2)) {
Record record2 = Validator.validate(recordString, "", config);
if (record2 == null) {
System.err.println("Validation of new created record file failed. Do not write.");
} else {
try {
FileUtils.write(filename, recordstring2, StandardCharsets.UTF_8);
} catch (IOException exp) {
System.err.println("Writing file \"" + filename + "\" failed. Reason: " + exp.getMessage());
System.exit(1);
}
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
});
}
use of org.apache.commons.cli.DefaultParser in project MassBank-web by MassBank.
the class RecordExporter method main.
/*
.ms2 text format: peptides
-----------------
https://skyline.ms/wiki/home/software/BiblioSpec/page.view?name=BiblioSpec%20input%20and%20output%20file%20formats
This format is recongnized by proteowizard's msconvert and can be converted into other formats such as .mzXML.
In an .ms2 file there are four types of lines.
Lines beginning with 'H' are header lines and contain information about how the data was collected as well as comments. They appear at the beginning of the file.
Lines beginning with 'S' are followed by the scan number and the precursor m/z.
Lines beginning with 'Z' give the charge state followed by the mass of the ion at that charge state.
Lines beginning with 'D' contain information relevant to the preceeding charge state. BlibToMs2's output will include D-lines with the sequence and modified sequence.
The file is arranged with these S, Z and D lines for one spectrum followed by a peak list:
a pair of values giving each peaks m/z and intensity. Here is an example file
H CreationDate Mon Apr 12 15:12:14 2010
H Extractor BlibToMs2
H Library /home/me/research/search/demo.blib
S 1 1 636.34
Z 2 1253.36
D seq FKNGFQTGSASK
D modified seq FKNGFQTGSASK
187.40 12.5
193.10 19.5
242.30 14.2
244.30 9.0
S 2 2 745.3
Z 2 1471.7
D seq NFLETVELQVGLK
D modified seq NFLETVELQVGLK
1224.60 7.9
1228.70 468.9
1230.40 658.5
1231.50 144.2
BlibBuild .ssl file:
--------------------
https://skyline.ms/wiki/home/software/BiblioSpec/page.view?name=BiblioSpec%20input%20and%20output%20file%20formats
NIST *.msp file:
----------------
https://chemdata.nist.gov/mass-spc/ftp/mass-spc/PepLib.pdf
(section 'Spectrum Fields and Format')
Name: KDLGEEHFK/2
MW: 1103.561
Comment: Spec=Consensus Pep=N-Semitryp_irreg/miss_good Fullname=F.KDLGEEHFK.G/2 Mods=0 Parent=551.781 Inst=it Mz_diff=0.544 Mz_exact=551.7805 Mz_av=552.114 Protein="sp|P02769|ALBU_BOVIN Serum albumin precursor (Allergen Bos d 6) (BSA) - Bos taurus (Bovine)." Pseq=131/1 Organism="Protein" Se=4^X12:ex=0.00037/0.0003992,td=25.85/1379,sd=0/0,hs=38.5/1.433,bs=0.00027,b2=0.00028,bd=133^O10:ex=0.0002435/0.0009314,td=74.85/3.186e+004,pr=3.235e-007/8.612e-007,bs=2.73e-005,b2=5.56e-005,bd=1.56^I1:ex=0.0339/0,dc=0.939/0,do=6.14/0,bs=0.0339,bd=0.939^C1:ex=0.032/0,td=0/0,sd=0/0,hs=555/0,bs=0.032 Sample=7/bsa_cam,2,6/bsa_cam_different_voltages,1,3/bsa_none,0,1/nist_yl_31011_sigma_t9253_bsa_cam,4,6/nist_yl_31011_sigma_t9253_bsa_time_cam,4,6/nist_yl_31611_sigma_t9253_bsa_cam,0,3/nist_yl_sgma_t9253_bsa_none,1,2 Nreps=12/27 Missing=0.1916/0.0688 Parent_med=552.3075/0.22 Max2med_orig=100.0/0.0 Dotfull=0.743/0.044 Dot_cons=0.809/0.048 Unassign_all=0.173 Unassigned=0.105 Dotbest=0.83 Flags=12,9,1 Naa=9 DUScorr=1.5/0.71/2.9 Dottheory=0.84 Pfin=4.6e+008 Probcorr=6.7 Tfratio=6e+003 Pfract=0 Unassigned_corrected=0.011
Num peaks: 124
201.2 149 "? 11/10 0.7"
209.1 238 "b2-35/-0.02 11/11 0.7"
226.3 779 "b2-18/0.18 12/12 1.7"
227.3 484 "b2-17/0.18 12/12 0.9"
228.4 62 "b2-17i/1.28 7/10 0.2"
*/
public static void main(String[] arguments) {
// load version and print
final Properties properties = new Properties();
try {
properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("project.properties"));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
System.out.println("Exporter version: " + properties.getProperty("version"));
// parse command line
Options options = new Options();
options.addRequiredOption("o", "outfile", true, "name of output file");
options.addOption("f", "format", true, "output format; possible values: RIKEN_MSP, NIST_MSP; default is RIKEN_MSP");
CommandLine cmd = null;
try {
cmd = new DefaultParser().parse(options, arguments);
} catch (ParseException e) {
// oops, something went wrong
System.err.println("Parsing command line failed. Reason: " + e.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("RecordExporter [OPTIONS] <FILE|DIR> [<FILE|DIR> ...]", options);
System.exit(1);
}
if (cmd.getArgList().size() == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("RecordExporter [OPTIONS] <FILE|DIR> [<FILE|DIR> ...]", options);
System.exit(1);
}
String format = cmd.getOptionValue("f");
if (format != null) {
if (!Arrays.asList("RIKEN_MSP", "NIST_MSP").contains(format)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("RecordExporter [OPTIONS] <FILE|DIR> [<FILE|DIR> ...]", options);
System.exit(1);
}
}
// loop over all arguments
// find all files in arguments and all *.txt files in directories and subdirectories
// specified in arguments
List<Record> records = cmd.getArgList().parallelStream().map(argument -> {
// find all files in arguments and all *.txt files in directories and subdirectories
// specified in arguments
File argumentFile = new File(argument);
List<File> filesToProcess = new ArrayList<File>();
if (argumentFile.isFile() && FilenameUtils.getExtension(argument).equals("txt")) {
filesToProcess.add(argumentFile);
} else if (argumentFile.isDirectory()) {
if (!argumentFile.getName().startsWith("."))
filesToProcess.addAll(FileUtils.listFiles(argumentFile, new String[] { "txt" }, true));
} else {
logger.warn("Argument " + argument + " could not be processed.");
}
// read all files and process to Record
List<Record> argumentRecords = filesToProcess.parallelStream().map(filename -> {
Record record = null;
try {
String recordString = FileUtils.readFileToString(filename, StandardCharsets.UTF_8);
Set<String> config = new HashSet<String>();
config.add("legacy");
record = Validator.validate(recordString, "", config);
} catch (IOException e) {
e.printStackTrace();
}
return record;
}).collect(Collectors.toList());
return argumentRecords;
}).flatMap(Collection::stream).filter(Objects::nonNull).collect(Collectors.toList());
// System.out.println(recordfiles.toString());
File outfile = new File(cmd.getOptionValue("o"));
// default output format is RIREN_MSP
if (format == null) {
format = "RIKEN_MSP";
}
switch(format) {
case "RIKEN_MSP":
RecordToRIKEN_MSP.recordsToRIKEN_MSP(outfile, records);
break;
case "NIST_MSP":
RecordToNIST_MSP.recordsToNIST_MSP(outfile, records);
break;
default:
logger.error("This code should not run.");
System.exit(1);
}
}
Aggregations