List of usage examples for org.apache.commons.collections4 CollectionUtils find
@Deprecated public static <T> T find(final Iterable<T> collection, final Predicate<? super T> predicate)
From source file:com.github.rvesse.airline.parser.AbstractCommandParser.java
protected ParseState<T> parseGroup(PeekingIterator<String> tokens, ParseState<T> state) { Predicate<CommandGroupMetadata> findGroupPredicate; if (tokens.hasNext()) { //@formatter:off findGroupPredicate = state.getParserConfiguration().allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(tokens.peek(), state.getGlobal().getCommandGroups()) : new GroupFinder(tokens.peek()); //@formatter:on CommandGroupMetadata group = CollectionUtils.find(state.getGlobal().getCommandGroups(), findGroupPredicate);//from w ww . j a v a2 s. co m if (group != null) { tokens.next(); state = state.withGroup(group).pushContext(Context.GROUP); state = parseOptions(tokens, state, state.getGroup().getOptions()); // Possibly may have sub-groups specified while (tokens.hasNext() && state.getGroup().getSubGroups().size() > 0) { //@formatter:off findGroupPredicate = state.getParserConfiguration().allowsAbbreviatedCommands() ? new AbbreviatedGroupFinder(tokens.peek(), state.getGroup().getSubGroups()) : new GroupFinder(tokens.peek()); //@formatter:on group = CollectionUtils.find(state.getGroup().getSubGroups(), findGroupPredicate); if (group != null) { tokens.next(); state = state.withGroup(group).pushContext(Context.GROUP); state = parseOptions(tokens, state, state.getGroup().getOptions()); } else { // Either a group that has a mixture of sub-groups and // commands in which case we need to break out of this // loop and flow will go onto to try the token as a // command name instead or actually invalid input and // we'll hit an error break; } } } } return state; }
From source file:com.github.rvesse.airline.model.MetadataLoader.java
public static <C> GlobalMetadata<C> loadGlobal(Class<?> cliClass) { Annotation annotation = cliClass.getAnnotation(com.github.rvesse.airline.annotations.Cli.class); if (annotation == null) throw new IllegalArgumentException( String.format("Class %s does not have the @Cli annotation", cliClass)); com.github.rvesse.airline.annotations.Cli cliConfig = (com.github.rvesse.airline.annotations.Cli) annotation; // Prepare commands CommandMetadata defaultCommand = null; if (!cliConfig.defaultCommand().equals(com.github.rvesse.airline.annotations.Cli.NO_DEFAULT.class)) { defaultCommand = loadCommand(cliConfig.defaultCommand()); }/* w ww. j av a 2s . co m*/ List<CommandMetadata> defaultGroupCommands = new ArrayList<CommandMetadata>(); for (Class<?> cls : cliConfig.commands()) { defaultGroupCommands.add(loadCommand(cls)); } // Prepare parser configuration ParserMetadata<C> parserConfig = cliConfig.parserConfiguration() != null ? MetadataLoader.<C>loadParser(cliConfig.parserConfiguration()) : MetadataLoader.<C>loadParser(cliClass); // Prepare restrictions // We find restrictions in the following order: // 1 - Those declared via annotations // 2 - Those declared via the restrictions field of the @Cli annotation // 3 - Standard restrictions if the includeDefaultRestrctions field of // the @Cli annotation is true List<GlobalRestriction> restrictions = new ArrayList<GlobalRestriction>(); for (Class<? extends Annotation> annotationClass : RestrictionRegistry .getGlobalRestrictionAnnotationClasses()) { annotation = cliClass.getAnnotation(annotationClass); if (annotation == null) continue; GlobalRestriction restriction = RestrictionRegistry.getGlobalRestriction(annotationClass, annotation); if (restriction != null) restrictions.add(restriction); } for (Class<? extends GlobalRestriction> cls : cliConfig.restrictions()) { restrictions.add(ParserUtil.createInstance(cls)); } if (cliConfig.includeDefaultRestrictions()) { restrictions.addAll(AirlineUtils.arrayToList(GlobalRestriction.DEFAULTS)); } // Prepare groups // We sort sub-groups by name length then lexically // This means that when we build the groups hierarchy we'll ensure we // build the parent groups first wherever possible Map<String, CommandGroupMetadata> subGroups = new TreeMap<String, CommandGroupMetadata>( new StringHierarchyComparator()); List<CommandGroupMetadata> groups = new ArrayList<CommandGroupMetadata>(); for (Group groupAnno : cliConfig.groups()) { String groupName = groupAnno.name(); String subGroupPath = null; if (StringUtils.containsWhitespace(groupName)) { // Normalize the path subGroupPath = StringUtils.join(StringUtils.split(groupAnno.name()), ' '); } // Maybe a top level group we've already seen CommandGroupMetadata group = CollectionUtils.find(groups, new GroupFinder(groupName)); if (group == null) { // Maybe a sub-group we've already seen group = subGroups.get(subGroupPath); } List<CommandMetadata> groupCommands = new ArrayList<CommandMetadata>(); for (Class<?> cls : groupAnno.commands()) { groupCommands.add(loadCommand(cls)); } if (group == null) { // Newly discovered group //@formatter:off group = loadCommandGroup(subGroupPath != null ? subGroupPath : groupName, groupAnno.description(), groupAnno.hidden(), Collections.<CommandGroupMetadata>emptyList(), !groupAnno.defaultCommand().equals(Group.NO_DEFAULT.class) ? loadCommand(groupAnno.defaultCommand()) : null, groupCommands); //@formatter:on if (subGroupPath == null) { groups.add(group); } else { // Remember sub-groups for later subGroups.put(subGroupPath, group); } } else { for (CommandMetadata cmd : groupCommands) { group.addCommand(cmd); } } } // Build sub-group hierarchy buildGroupsHierarchy(groups, subGroups); // Find all commands List<CommandMetadata> allCommands = new ArrayList<CommandMetadata>(); allCommands.addAll(defaultGroupCommands); if (defaultCommand != null && !defaultGroupCommands.contains(defaultCommand)) { allCommands.add(defaultCommand); } for (CommandGroupMetadata group : groups) { allCommands.addAll(group.getCommands()); if (group.getDefaultCommand() != null) { allCommands.add(group.getDefaultCommand()); } Queue<CommandGroupMetadata> subGroupsQueue = new LinkedList<CommandGroupMetadata>(); subGroupsQueue.addAll(group.getSubGroups()); while (subGroupsQueue.size() > 0) { CommandGroupMetadata subGroup = subGroupsQueue.poll(); allCommands.addAll(subGroup.getCommands()); if (subGroup.getDefaultCommand() != null) allCommands.add(subGroup.getDefaultCommand()); subGroupsQueue.addAll(subGroup.getSubGroups()); } } // Post-process to find possible further group assignments loadCommandsIntoGroupsByAnnotation(allCommands, groups, defaultGroupCommands); return loadGlobal(cliConfig.name(), cliConfig.description(), defaultCommand, defaultGroupCommands, groups, restrictions, parserConfig); }
From source file:com.github.rvesse.airline.TestSingleCommand.java
/** * Make sure that if there are args with multiple names (e.g. "-log" and * "-verbose"), the usage will only display it once. *///from w ww .j a v a2 s.c om @Test public void repeatedArgs() { SingleCommand<Args1> parser = singleCommand(Args1.class); CommandMetadata command = CollectionUtils.find(AirlineUtils.singletonList(parser.getCommandMetadata()), new CommandFinder("Args1")); assertEquals(command.getAllOptions().size(), 8); }
From source file:com.github.rvesse.airline.TestSubGroups.java
@Test public void sub_groups_cli_annotation_02() { Cli<Object> cli = new Cli<Object>(SubGroupsCli02.class); GlobalMetadata<Object> global = cli.getMetadata(); Assert.assertEquals(global.getDefaultGroupCommands().size(), 0); Assert.assertEquals(global.getCommandGroups().size(), 1); CommandGroupMetadata parentGroup = global.getCommandGroups().get(0); Assert.assertNull(parentGroup.getParent()); Assert.assertEquals(parentGroup.getName(), "foo"); Assert.assertEquals(parentGroup.getCommands().size(), 0); Assert.assertEquals(parentGroup.getSubGroups().size(), 2); CommandGroupMetadata subGroup = CollectionUtils.find(parentGroup.getSubGroups(), new GroupFinder("bar")); Assert.assertNotNull(subGroup);/*from www.j a va2 s . com*/ Assert.assertEquals(parentGroup, subGroup.getParent()); Assert.assertEquals(subGroup.getName(), "bar"); Assert.assertEquals(subGroup.getCommands().size(), 1); Assert.assertEquals(subGroup.getDefaultCommand().getType(), Help.class); subGroup = CollectionUtils.find(parentGroup.getSubGroups(), new GroupFinder("baz")); Assert.assertNotNull(subGroup); Assert.assertEquals(parentGroup, subGroup.getParent()); Assert.assertEquals(subGroup.getName(), "baz"); Assert.assertEquals(subGroup.getCommands().size(), 0); Assert.assertNull(subGroup.getDefaultCommand()); Object cmd = cli.parse("foo", "bar"); Assert.assertTrue(cmd instanceof Help); }
From source file:com.sunchenbin.store.feilong.core.util.CollectionsUtil.java
/** * Finds the first element in the given collection which matches the given predicate. * /* w w w.jav a2s. c o m*/ * <p> * If the input collection or predicate is null, or no element of the collection matches the predicate, null is returned. * </p> * * @param <O> * the generic type * @param <V> * the value type * @param objectCollection * the object collection * @param propertyName * the property name * @param value * the value * @return the first element of the collection which matches the predicate or null if none could be found * @see CollectionUtils#find(Iterable, Predicate) */ public static <O, V> O find(Collection<O> objectCollection, String propertyName, V value) { Predicate<O> predicate = new ObjectPropertyEqualsPredicate<O>(propertyName, value); return CollectionUtils.find(objectCollection, predicate); }
From source file:de.tor.tribes.types.Attack.java
@Override public String[] getReplacements(boolean pExtended) { String sendVal = null;/*from www. j a va 2 s . c o m*/ String arrivetVal = null; Date aTime = getArriveTime(); Date sTime = getSendTime(); if (pExtended) { if (ServerSettings.getSingleton().isMillisArrival()) { sendVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss.'[size=8]'SSS'[/size]'").format(sTime); arrivetVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss.'[size=8]'SSS'[/size]'").format(aTime); } else { sendVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(sTime); arrivetVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(aTime); } } else { if (ServerSettings.getSingleton().isMillisArrival()) { sendVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss.SSS").format(sTime); arrivetVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss.SSS").format(aTime); } else { sendVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(sTime); arrivetVal = new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(aTime); } } String typeVal = ""; switch (type) { case Attack.CLEAN_TYPE: { typeVal = "Angriff (Clean-Off)"; break; } case Attack.FAKE_TYPE: { typeVal = "Angriff (Fake)"; break; } case Attack.SNOB_TYPE: { typeVal = "Angriff (AG)"; break; } case Attack.SUPPORT_TYPE: { typeVal = "Untersttzung"; break; } default: { typeVal = "Angriff"; } } String stdName = "Unbenannt"; StandardAttack a = StandardAttackManager.getSingleton().getElementByIcon(getType()); if (a != null) { stdName = a.getName(); } String attackerVal = ""; if (source.getTribe() != Barbarians.getSingleton()) { attackerVal = source.getTribe().toBBCode(); } else { attackerVal = "Barbaren"; } String sourceVal = source.toBBCode(); String unitVal = ""; if (pExtended) { unitVal = "[unit]" + getUnit().getPlainName() + "[/unit]"; } else { unitVal = getUnit().getName(); } String defenderVal = ""; if (target.getTribe() != Barbarians.getSingleton()) { defenderVal = target.getTribe().toBBCode(); } else { defenderVal = "Barbaren"; } String targetVal = target.toBBCode(); //replace place var String baseURL = ServerManager.getServerURL(GlobalOptions.getSelectedServer()) + "/"; String placeURL = baseURL + "game.php?village="; int uvID = -1; List<UserProfile> serverProfiles = Arrays .asList(ProfileManager.getSingleton().getProfiles(GlobalOptions.getSelectedServer())); //get attacker and look for UserProfile for this attacker final Tribe attacker = source.getTribe(); UserProfile profileForAttacker = (UserProfile) CollectionUtils.find(serverProfiles, new Predicate() { @Override public boolean evaluate(Object o) { UserProfile profile = (UserProfile) o; if (attacker != null && profile.getTribe() != null) { return profile.getTribe().getId() == attacker.getId(); } //no attacker found return false; } }); if (profileForAttacker != null) { //profile for attacker exists...check if it is set to UV if (profileForAttacker.isUVAccount()) { uvID = profileForAttacker.getTribe().getId(); } else { uvID = -1; } } else { //no profile found...should be no UV uvID = -1; } if (uvID >= 0) { placeURL = baseURL + "game.php?t=" + uvID + "&village="; } placeURL += source.getId() + "&screen=place&mode=command&target=" + target.getId(); String placeURLVal = placeURL; return new String[] { typeVal, stdName, attackerVal, sourceVal, unitVal, defenderVal, targetVal, sendVal, arrivetVal, "[url=\"" + placeURL + "\"]Versammlungsplatz[/url]", placeURLVal }; }
From source file:com.github.rvesse.airline.help.cli.bash.BashCompletionGenerator.java
private void generateCommandCompletionFunction(Writer writer, GlobalMetadata<T> global, CommandGroupMetadata group, CommandMetadata command) throws IOException { // Start Function writeCommandFunctionName(writer, global, group, command, true); // Prepare variables writer.append(" # Get completion data").append(NEWLINE); writer.append(" COMPREPLY=()").append(NEWLINE); writer.append(" CURR_WORD=${COMP_WORDS[COMP_CWORD]}").append(NEWLINE); writer.append(" PREV_WORD=${COMP_WORDS[COMP_CWORD-1]}").append(NEWLINE); writer.append(" COMMANDS=$1").append(DOUBLE_NEWLINE); // Prepare the option information Set<String> flagOpts = new HashSet<>(); Set<String> argOpts = new HashSet<>(); for (OptionMetadata option : command.getAllOptions()) { if (option.isHidden() && !this.includeHidden()) continue; if (option.getArity() == 0) { flagOpts.addAll(option.getOptions()); } else {/*from w w w . j a v a 2 s . c o m*/ argOpts.addAll(option.getOptions()); } } writeWordListVariable(writer, 2, "FLAG_OPTS", flagOpts.iterator()); writeWordListVariable(writer, 2, "ARG_OPTS", argOpts.iterator()); writer.append(NEWLINE); // Check whether we are completing a value for an argument flag if (argOpts.size() > 0) { writer.append(" $( containsElement ${PREV_WORD} ${ARG_OPTS[@]} )").append(NEWLINE); writer.append(" SAW_ARG=$?").append(NEWLINE); // If we previously saw an argument then we are completing that // argument writer.append(" if [[ ${SAW_ARG} -eq 0 ]]; then").append(NEWLINE); writer.append(" ARG_VALUES=").append(NEWLINE); writer.append(" ARG_GENERATED_VALUES=").append(NEWLINE); writer.append(" case ${PREV_WORD} in").append(NEWLINE); for (OptionMetadata option : command.getAllOptions()) { if (option.isHidden() || option.getArity() == 0) continue; // Add cases for the names indent(writer, 6); Iterator<String> names = option.getOptions().iterator(); while (names.hasNext()) { writer.append(names.next()); if (names.hasNext()) writer.append('|'); } writer.append(")\n"); // Then generate the completions for the option BashCompletion completion = getCompletionData(option); if (completion != null && StringUtils.isNotEmpty(completion.command())) { indent(writer, 8); writer.append("ARG_GENERATED_VALUES=$( ").append(completion.command()).append(" )") .append(NEWLINE); } AbstractAllowedValuesRestriction allowedValues = (AbstractAllowedValuesRestriction) CollectionUtils .find(option.getRestrictions(), new AllowedValuesOptionFinder()); if (allowedValues != null && allowedValues.getAllowedValues().size() > 0) { writeWordListVariable(writer, 8, "ARG_VALUES", allowedValues.getAllowedValues().iterator()); } writeCompletionGeneration(writer, 8, true, getCompletionData(option), "ARG_VALUES", "ARG_GENERATED_VALUES"); indent(writer, 8); writer.append(";;").append(NEWLINE); } writer.append(" esac").append(NEWLINE); writer.append(" fi").append(DOUBLE_NEWLINE); } // If we previously saw a flag we could see another option or an // argument if supported BashCompletion completion = null; if (command.getArguments() != null) { completion = getCompletionData(command.getArguments()); if (completion != null && StringUtils.isNotEmpty(completion.command())) { writer.append(" ARGUMENTS=$( ").append(completion.command()).append(" )").append(NEWLINE); } else { writer.append(" ARGUMENTS=").append(NEWLINE); } } else { writer.append(" ARGUMENTS=").append(NEWLINE); } writeCompletionGeneration(writer, 2, true, completion, "FLAG_OPTS", "ARG_OPTS", "ARGUMENTS"); // End Function writer.append('}').append(DOUBLE_NEWLINE); }
From source file:com.github.rvesse.airline.TestHelp.java
@Test public void testOptionsHidden02() throws IOException { //@formatter:off CliBuilder<Object> builder = Cli.builder("test").withDescription("Test commandline") .withDefaultCommand(Help.class).withCommands(Help.class, OptionsHidden.class); Cli<Object> parser = builder.build(); ByteArrayOutputStream out = new ByteArrayOutputStream(); AbstractCommandUsageGenerator generator = new CliCommandUsageGenerator(true); CommandMetadata metadata = CollectionUtils.find(parser.getMetadata().getDefaultGroupCommands(), new CommandFinder("OptionsHidden")); Assert.assertNotNull(metadata);/*from w ww .j ava2 s . c o m*/ generator.usage("test", null, "OptionsHidden", metadata, null, out); assertEquals(new String(out.toByteArray(), utf8), "NAME\n" + " test OptionsHidden -\n" + "\n" + "SYNOPSIS\n" + " test OptionsHidden [ --hidden <hiddenOption> ]\n" + " [ --optional <optionalOption> ]\n" + "\n" + "OPTIONS\n" + " --hidden <hiddenOption>\n" + "\n\n" + " --optional <optionalOption>\n" + "\n" + "\n"); //@formatter:on }
From source file:com.github.rvesse.airline.model.MetadataLoader.java
public static void loadCommandsIntoGroupsByAnnotation(List<CommandMetadata> allCommands, List<CommandGroupMetadata> commandGroups, List<CommandMetadata> defaultCommandGroup) { List<CommandMetadata> newCommands = new ArrayList<CommandMetadata>(); // first, create any groups explicitly annotated createGroupsFromAnnotations(allCommands, newCommands, commandGroups, defaultCommandGroup); for (CommandMetadata command : allCommands) { boolean addedToGroup = false; // now add the command to any groupNames specified in the Command // annotation for (String groupName : command.getGroupNames()) { CommandGroupMetadata group = CollectionUtils.find(commandGroups, new GroupFinder(groupName)); if (group != null) { // Add to existing top level group group.addCommand(command); addedToGroup = true;//from w ww . j a va 2s.c om } else { if (StringUtils.containsWhitespace(groupName)) { // Add to sub-group String[] groups = StringUtils.split(groupName); CommandGroupMetadata subGroup = null; for (int i = 0; i < groups.length; i++) { if (i == 0) { // Find/create the necessary top level group subGroup = CollectionUtils.find(commandGroups, new GroupFinder(groups[i])); if (subGroup == null) { subGroup = new CommandGroupMetadata(groups[i], "", false, Collections.<OptionMetadata>emptyList(), Collections.<CommandGroupMetadata>emptyList(), null, Collections.<CommandMetadata>emptyList()); commandGroups.add(subGroup); } } else { // Find/create the next sub-group CommandGroupMetadata nextSubGroup = CollectionUtils.find(subGroup.getSubGroups(), new GroupFinder(groups[i])); if (nextSubGroup == null) { nextSubGroup = new CommandGroupMetadata(groups[i], "", false, Collections.<OptionMetadata>emptyList(), Collections.<CommandGroupMetadata>emptyList(), null, Collections.<CommandMetadata>emptyList()); } subGroup.addSubGroup(nextSubGroup); subGroup = nextSubGroup; } } if (subGroup == null) throw new IllegalStateException("Failed to resolve sub-group path"); subGroup.addCommand(command); addedToGroup = true; } else { // Add to newly created top level group CommandGroupMetadata newGroup = loadCommandGroup(groupName, "", false, Collections.<CommandGroupMetadata>emptyList(), null, Collections.singletonList(command)); commandGroups.add(newGroup); addedToGroup = true; } } } if (addedToGroup && defaultCommandGroup.contains(command)) { defaultCommandGroup.remove(command); } } allCommands.addAll(newCommands); }
From source file:com.github.rvesse.airline.model.MetadataLoader.java
@SuppressWarnings("rawtypes") private static void createGroupsFromAnnotations(List<CommandMetadata> allCommands, List<CommandMetadata> newCommands, List<CommandGroupMetadata> commandGroups, List<CommandMetadata> defaultCommandGroup) { // We sort sub-groups by name length then lexically // This means that when we build the groups hierarchy we'll ensure we // build the parent groups first wherever possible Map<String, CommandGroupMetadata> subGroups = new TreeMap<String, CommandGroupMetadata>( new StringHierarchyComparator()); for (CommandMetadata command : allCommands) { boolean addedToGroup = false; // first, create any groups explicitly annotated for (Group groupAnno : command.getGroups()) { Class defaultCommandClass = null; CommandMetadata defaultCommand = null; // load default command if needed if (!groupAnno.defaultCommand().equals(Group.NO_DEFAULT.class)) { defaultCommandClass = groupAnno.defaultCommand(); defaultCommand = CollectionUtils.find(allCommands, new CommandTypeFinder(defaultCommandClass)); if (null == defaultCommand) { defaultCommand = loadCommand(defaultCommandClass); newCommands.add(defaultCommand); }//from w w w. ja v a 2 s . c om } // load other commands if needed List<CommandMetadata> groupCommands = new ArrayList<CommandMetadata>(groupAnno.commands().length); CommandMetadata groupCommand = null; for (Class commandClass : groupAnno.commands()) { groupCommand = CollectionUtils.find(allCommands, new CommandTypeFinder(commandClass)); if (null == groupCommand) { groupCommand = loadCommand(commandClass); newCommands.add(groupCommand); groupCommands.add(groupCommand); } } // Find the group metadata // May already exist as a top level group CommandGroupMetadata groupMetadata = CollectionUtils.find(commandGroups, new GroupFinder(groupAnno.name())); if (groupMetadata == null) { // Not a top level group String subGroupPath = null; if (StringUtils.containsWhitespace(groupAnno.name())) { // Is this a sub-group we've already seen? // Make sure to normalize white space in the path subGroupPath = StringUtils.join(StringUtils.split(groupAnno.name()), " "); groupMetadata = subGroups.get(subGroupPath); } if (groupMetadata == null) { // Newly discovered group groupMetadata = loadCommandGroup(groupAnno.name(), groupAnno.description(), groupAnno.hidden(), Collections.<CommandGroupMetadata>emptyList(), defaultCommand, groupCommands); if (!StringUtils.containsWhitespace(groupAnno.name())) { // Add as top level group commandGroups.add(groupMetadata); } else { // This is a new sub-group, put aside for now and // we'll build the sub-group tree later subGroups.put(subGroupPath, groupMetadata); } } } groupMetadata.addCommand(command); addedToGroup = true; } if (addedToGroup && defaultCommandGroup.contains(command)) { defaultCommandGroup.remove(command); } } buildGroupsHierarchy(commandGroups, subGroups); }