Search in sources :

Example 1 with Collections2

use of com.google.common.collect.Collections2 in project opennms by OpenNMS.

the class JmxDatacollectionConfiggenerator method queryMbeanServer.

private QueryResult queryMbeanServer(List<String> ids, MBeanServerConnection mBeanServerConnection, boolean runStandardVmBeans) throws MBeanServerQueryException {
    final MBeanServerQuery query = new MBeanServerQuery().withFilters(ids).fetchValues(// we do not fetch values to improve collection speed
    false).showMBeansWithoutAttributes(// we don't need them
    false).sort(// sorting makes finding attributes easier
    true);
    if (!runStandardVmBeans) {
        query.withIgnoresFilter(Collections2.transform(standardVmBeans, input -> input + ":*"));
    }
    final QueryResult result = query.execute(mBeanServerConnection);
    return result;
}
Also used : MBeanServerQuery(org.opennms.features.jmxconfiggenerator.jmxconfig.query.MBeanServerQuery) LogAdapter(org.opennms.features.jmxconfiggenerator.log.LogAdapter) JmxCollection(org.opennms.netmgt.config.collectd.jmx.JmxCollection) MBeanAttributeInfo(javax.management.MBeanAttributeInfo) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) ArrayList(java.util.ArrayList) QueryResult(org.opennms.features.jmxconfiggenerator.jmxconfig.query.QueryResult) Map(java.util.Map) FilterCriteria(org.opennms.features.jmxconfiggenerator.jmxconfig.query.FilterCriteria) AttributeType(org.opennms.netmgt.collection.api.AttributeType) JaxbUtils(org.opennms.core.xml.JaxbUtils) MBeanServerConnection(javax.management.MBeanServerConnection) Collection(java.util.Collection) Set(java.util.Set) CompositeData(javax.management.openmbean.CompositeData) IOException(java.io.IOException) ObjectName(javax.management.ObjectName) CompAttrib(org.opennms.netmgt.config.collectd.jmx.CompAttrib) File(java.io.File) JmxDatacollectionConfig(org.opennms.netmgt.config.collectd.jmx.JmxDatacollectionConfig) Rrd(org.opennms.netmgt.config.collectd.jmx.Rrd) List(java.util.List) Mbean(org.opennms.netmgt.config.collectd.jmx.Mbean) CompMember(org.opennms.netmgt.config.collectd.jmx.CompMember) JMException(javax.management.JMException) Attrib(org.opennms.netmgt.config.collectd.jmx.Attrib) MBeanServerQueryException(org.opennms.features.jmxconfiggenerator.jmxconfig.query.MBeanServerQueryException) NameCutter(org.opennms.features.namecutter.NameCutter) MBeanServerQuery(org.opennms.features.jmxconfiggenerator.jmxconfig.query.MBeanServerQuery) QueryResult(org.opennms.features.jmxconfiggenerator.jmxconfig.query.QueryResult)

Example 2 with Collections2

use of com.google.common.collect.Collections2 in project raml-module-builder by folio-org.

the class AnnotationGrabber method generateMappings.

// ^http.*?//.*?/apis/patrons/.*?/fines/.*
// ^http.*?\/\/.*?\/apis\/patrons\/?(.+?)*
// ^http.*?\/\/.*?\/apis\/([^\/]+)\/([^\/]+)(\?.*)
public static JsonObject generateMappings() throws Exception {
    /* this class is one of the drivers for the client generation
     * check if the plugin set the system property in the pom and only if
     * so generate */
    String clientGen = System.getProperty("client.generate");
    String modDescr = System.getProperty("modDescrptor.generate");
    if (clientGen != null) {
        generateClient = true;
    }
    if ("true".equals(modDescr)) {
        generateModDescrptor = true;
    }
    JsonObject globalClassMapping = new JsonObject();
    // get classes in generated package
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(RTFConsts.INTERFACE_PACKAGE);
    Collection<Object> classNames = Collections2.transform(classes, new Function<ClassPath.ClassInfo, Object>() {

        @Override
        public Object apply(ClassPath.ClassInfo input) {
            log.info("Mapping functions in " + input.getName() + " class to appropriate urls");
            // not needed - dont need transform function,
            return input.getName();
        // remove
        }
    });
    // loop over all the classes from the package
    classNames.forEach(val -> {
        try {
            ClientGenerator cGen = new ClientGenerator();
            // ----------------- class level annotations -----------------------//
            // -----------------------------------------------------------------//
            // will contain all mappings for a specific class in the package
            JsonObject classSpecificMapping = new JsonObject();
            // get annotations via reflection for a class
            Annotation[] annotations = Class.forName(val.toString()).getAnnotations();
            // create an entry for the class name = ex. "class":"com.sling.rest.jaxrs.resource.BibResource"
            classSpecificMapping.put(CLASS_NAME, val.toString());
            classSpecificMapping.put(INTERFACE_NAME, val.toString());
            // needed info - these are class level annotation - not method level
            for (int i = 0; i < annotations.length; i++) {
                // get the annotation type - example in jersey would we javax.ws.rs.Path
                Class<? extends Annotation> type = annotations[i].annotationType();
                // function
                for (Method method : type.getDeclaredMethods()) {
                    Object value = method.invoke(annotations[i], (Object[]) null);
                    if (type.isAssignableFrom(Path.class)) {
                        classSpecificMapping.put(CLASS_URL, "^/" + value);
                        if (generateClient) {
                            cGen.generateClassMeta(val.toString(), value);
                        }
                        if (generateModDescrptor && classSpecificMapping.getString(CLASS_URL) != null) {
                            String url = classSpecificMapping.getString(CLASS_URL).substring(2);
                            if (!url.contains("rmbtests")) {
                                MDGenerator.ProvidesEntry pe = MDGenerator.INSTANCE.new ProvidesEntry();
                                if (url.contains("_/tenant")) {
                                    url = "_tenant";
                                }
                                pe.setId(url);
                                MDGenerator.INSTANCE.addProvidesEntry(pe);
                            }
                        }
                    }
                }
            }
            // ----------------- method level annotations ------------ //
            // ------------------------------------------------------- //
            /**
             * will be used only if ModuleDescriptor generation is turned on
             * maps all http verbs to a single url
             */
            mdUrl2Verbs = new HashMap<>();
            JsonArray methodsInAPath;
            // iterate over all functions in the class
            Method[] methods = Class.forName(val.toString()).getMethods();
            for (int i = 0; i < methods.length; i++) {
                JsonObject methodObj = new JsonObject();
                JsonObject params = getParameterNames(methods[i]);
                // get annotations on the method and add all info per method to its
                // own methodObj
                Annotation[] methodAn = methods[i].getAnnotations();
                // System.out.println(methods[i].getName());
                // put the name of the function
                methodObj.put(FUNCTION_NAME, methods[i].getName());
                methodObj.put(METHOD_PARAMS, params);
                for (int j = 0; j < methodAn.length; j++) {
                    Class<? extends Annotation> type = methodAn[j].annotationType();
                    // System.out.println("Values of " + type.getName());
                    if (RTFConsts.POSSIBLE_HTTP_METHOD.contains(type.getName())) {
                        // put the method - get or post, etc..
                        methodObj.put(HTTP_METHOD, type.getName());
                    }
                    boolean replaceAccept = false;
                    if (type.isAssignableFrom(Produces.class)) {
                        // this is the accept header, right now can not send */*
                        // so if accept header equals any/ - change this to */*
                        replaceAccept = true;
                    }
                    for (Method method : type.getDeclaredMethods()) {
                        Object value = method.invoke(methodAn[j], (Object[]) null);
                        if (value.getClass().isArray()) {
                            List<Object> retList = new ArrayList<>();
                            for (int k = 0; k < Array.getLength(value); k++) {
                                if (replaceAccept) {
                                    // replace any/any with */* to allow declaring accpet */* which causes compilation issues
                                    // when declared in raml. so declare any/any in raml instead and replaced here
                                    retList.add(((String) Array.get(value, k)).replaceAll("any/any", ""));
                                } else {
                                    retList.add(Array.get(value, k));
                                }
                            }
                            // put generically things like consumes, produces as arrays
                            // since they can have multi values
                            methodObj.put(type.getName(), retList);
                        } else {
                            if (type.isAssignableFrom(Path.class)) {
                                String path = classSpecificMapping.getString(CLASS_URL) + URL_PATH_DELIMITER + value;
                                String regexPath = getRegexForPath(path);
                                // put path to function
                                methodObj.put(METHOD_URL, path);
                                // put regex path to function
                                methodObj.put(REGEX_URL, regexPath);
                            }
                        // System.out.println(" " + method.getName() + ": " + value.toString());
                        }
                    }
                }
                if (generateClient) {
                    cGen.generateMethodMeta(methodObj.getString(FUNCTION_NAME), methodObj.getJsonObject(METHOD_PARAMS), methodObj.getString(METHOD_URL), methodObj.getString(HTTP_METHOD), methodObj.getJsonArray(CONSUMES), methodObj.getJsonArray(PRODUCES));
                }
                // class
                if (methodObj.getString(METHOD_URL) == null) {
                    methodObj.put(METHOD_URL, classSpecificMapping.getString(CLASS_URL));
                    methodObj.put(REGEX_URL, getRegexForPath(classSpecificMapping.getString(CLASS_URL)));
                }
                if (generateModDescrptor) {
                    String verb = methodObj.getString(HTTP_METHOD);
                    verb = verb.substring(verb.lastIndexOf(".") + 1);
                    String rootURL4Service = classSpecificMapping.getString(CLASS_URL).substring(1);
                    /*if(mdUrl2Verbs.get(path.substring(1)) != null){
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            } else {
              mdUrl2Verbs.put(path.substring(1), new JsonArray());
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            }*/
                    if (mdUrl2Verbs.get(rootURL4Service) != null) {
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    } else {
                        mdUrl2Verbs.put(rootURL4Service, new HashSet<String>());
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    }
                }
                // this is the key - the regex path is the key to the functions
                // represented by this url
                // an array of functions which answer to this url (with get, delete,
                // post, etc... methods)
                methodsInAPath = classSpecificMapping.getJsonArray(methodObj.getString(REGEX_URL));
                if (methodsInAPath == null) {
                    methodsInAPath = new JsonArray();
                    classSpecificMapping.put(methodObj.getString(REGEX_URL), methodsInAPath);
                }
                methodsInAPath.add(methodObj);
            }
            // System.out.println( val.toString() );
            globalClassMapping.put(classSpecificMapping.getString(CLASS_URL), classSpecificMapping);
            if (generateClient) {
                cGen.generateClass(classSpecificMapping);
            }
            if (generateModDescrptor) {
                BiConsumer<String, Set<String>> biConsumer = (key, value) -> {
                    if (!key.contains("_/tenant") && !key.contains("rmbtests")) {
                        MDGenerator.RoutingEntry re = MDGenerator.INSTANCE.new RoutingEntry();
                        JsonArray ja = new JsonArray();
                        value.forEach(verb -> {
                            ja.add(verb);
                        });
                        re.setMethods(ja);
                        re.setEntryPath(key);
                        re.setLevel("30");
                        re.setType("request-response");
                        MDGenerator.INSTANCE.addRoutingEntry(re);
                    }
                };
                mdUrl2Verbs.forEach(biConsumer);
                MDGenerator.INSTANCE.generateMD();
                // this is needed when the MDGenerator is used to generate
                // partial MDs in submodules. the system variable is maintained
                // across the sub module builds and if not reset will generate a
                // partial MD for all sub modules
                System.setProperty("modDescrptor.generate", "false");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    });
    // writeMappings(globalClassMapping);
    return globalClassMapping;
}
Also used : PathParam(javax.ws.rs.PathParam) Array(java.lang.reflect.Array) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QueryParam(javax.ws.rs.QueryParam) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) JsonObject(io.vertx.core.json.JsonObject) ClassPath(com.google.common.reflect.ClassPath) Logger(io.vertx.core.logging.Logger) Method(java.lang.reflect.Method) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Annotation(java.lang.annotation.Annotation) ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Example 3 with Collections2

use of com.google.common.collect.Collections2 in project CitizensAPI by CitizensDev.

the class PersistenceLoader method getFieldsFromClass.

private static PersistField[] getFieldsFromClass(Class<?> clazz) {
    List<Field> toFilter = Lists.newArrayList(clazz.getDeclaredFields());
    Class<?> superClass = clazz.getSuperclass();
    while (superClass != Object.class && superClass != null) {
        toFilter.addAll(Arrays.asList(superClass.getDeclaredFields()));
        superClass = superClass.getSuperclass();
    }
    Iterator<Field> itr = toFilter.iterator();
    while (itr.hasNext()) {
        Field field = itr.next();
        field.setAccessible(true);
        Persist persistAnnotation = field.getAnnotation(Persist.class);
        if (persistAnnotation == null) {
            itr.remove();
            continue;
        }
        DelegatePersistence delegate = field.getAnnotation(DelegatePersistence.class);
        if (delegate == null)
            continue;
        Class<? extends Persister<?>> delegateClass = delegate.value();
        ensureDelegateLoaded(delegateClass);
        Persister<?> in = loadedDelegates.get(delegateClass);
        if (in == null) {
            // class couldn't be loaded earlier, we can't deserialise.
            itr.remove();
            continue;
        }
    }
    return Collections2.transform(toFilter, (a) -> new PersistField(a)).toArray(new PersistField[toFilter.size()]);
}
Also used : Arrays(java.util.Arrays) Iterator(java.util.Iterator) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) Collections2(com.google.common.collect.Collections2) Field(java.lang.reflect.Field) Constructor(java.lang.reflect.Constructor) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) ItemStack(org.bukkit.inventory.ItemStack) Primitives(com.google.common.primitives.Primitives) List(java.util.List) Lists(com.google.common.collect.Lists) ParameterizedType(java.lang.reflect.ParameterizedType) Location(org.bukkit.Location) Type(java.lang.reflect.Type) EulerAngle(org.bukkit.util.EulerAngle) Modifier(java.lang.reflect.Modifier) Map(java.util.Map) DataKey(net.citizensnpcs.api.util.DataKey) EnumSet(java.util.EnumSet) WeakHashMap(java.util.WeakHashMap) Field(java.lang.reflect.Field)

Example 4 with Collections2

use of com.google.common.collect.Collections2 in project rxrabbit by meltwater.

the class RxRabbitTests method mulitple_publishers_recover_from_connection_shutdown.

@Test
public void mulitple_publishers_recover_from_connection_shutdown() throws Exception {
    RabbitPublisher publisher = publisherFactory.createPublisher();
    RabbitPublisher publisher2 = publisherFactory.createPublisher();
    RabbitPublisher publisher3 = publisherFactory.createPublisher();
    final int nrMessages = 30_000;
    List<Observable<PublishedMessage>> sent = new ArrayList<>();
    sent.add(sendNMessagesAsync(nrMessages, 0, publisher));
    sent.add(sendNMessagesAsync(nrMessages, nrMessages + 1, publisher2));
    sent.add(sendNMessagesAsync(nrMessages, nrMessages * 2 + 1, publisher3));
    Observable<PublishedMessage> merge = Observable.merge(sent);
    final Semaphore ugly = new Semaphore(0);
    final List<PublishedMessage> res = new ArrayList<>();
    merge.subscribe(new Subscriber<PublishedMessage>() {

        @Override
        public void onCompleted() {
            ugly.release();
        }

        @Override
        public void onError(Throwable e) {
            log.errorWithParams("got error", e);
        }

        @Override
        public void onNext(PublishedMessage m) {
            res.add(m);
            if (res.size() == nrMessages) {
                try {
                    log.infoWithParams("Closing connection");
                    List<String> connectionNames = getConnectionNames();
                    log.infoWithParams("Nr connections", "is", connectionNames.size());
                    deleteConnections(connectionNames);
                } catch (Exception e) {
                    log.infoWithParams("Got exception, THIS SHOULD NEVER HAPPEN", e);
                }
            }
        }
    });
    log.infoWithParams("Waiting for all publish confirms");
    ugly.acquire();
    publisher.close();
    publisher2.close();
    publisher3.close();
    AdminChannel channel = channelFactory.createAdminChannel();
    deleteQueue(inputQueue, channel);
    declareAndBindQueue(channel, inputQueue, new Exchange(inputExchange));
    channel.close();
    assertThat(res.size(), equalTo(nrMessages * 3));
    final List<PublishedMessage> fails = new ArrayList<>(Collections2.filter(res, input -> input.failed));
    assertThat(fails.size(), equalTo(0));
}
Also used : SortedSet(java.util.SortedSet) DockerContainers(com.meltwater.rxrabbit.docker.DockerContainers) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) Collections2(com.google.common.collect.Collections2) MonitoringTestThreadFactory(com.meltwater.rxrabbit.util.MonitoringTestThreadFactory) Assert.assertThat(org.junit.Assert.assertThat) RabbitTestUtils.waitForNumQueuesToBePresent(com.meltwater.rxrabbit.RabbitTestUtils.waitForNumQueuesToBePresent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Map(java.util.Map) Schedulers(rx.schedulers.Schedulers) RxJavaHooks(rx.plugins.RxJavaHooks) TakeAndAckTransformer(com.meltwater.rxrabbit.util.TakeAndAckTransformer) AfterClass(org.junit.AfterClass) Collection(java.util.Collection) Set(java.util.Set) RabbitTestUtils.declareAndBindQueue(com.meltwater.rxrabbit.RabbitTestUtils.declareAndBindQueue) Scheduler(rx.Scheduler) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) DefaultChannelFactory(com.meltwater.rxrabbit.impl.DefaultChannelFactory) RabbitTestUtils.realm(com.meltwater.rxrabbit.RabbitTestUtils.realm) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Matchers.is(org.hamcrest.Matchers.is) CachedThreadScheduler(rx.internal.schedulers.CachedThreadScheduler) Subscription(rx.Subscription) RabbitTestUtils.waitForAllConnectionsToClose(com.meltwater.rxrabbit.RabbitTestUtils.waitForAllConnectionsToClose) RabbitTestUtils.createQueues(com.meltwater.rxrabbit.RabbitTestUtils.createQueues) BeforeClass(org.junit.BeforeClass) ConfirmListener(com.rabbitmq.client.ConfirmListener) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) MINUTES(java.util.concurrent.TimeUnit.MINUTES) AtomicReference(java.util.concurrent.atomic.AtomicReference) TreeSet(java.util.TreeSet) Observable(rx.Observable) ArrayList(java.util.ArrayList) ConstantBackoffAlgorithm(com.meltwater.rxrabbit.util.ConstantBackoffAlgorithm) HashSet(java.util.HashSet) AsyncHttpClient(com.ning.http.client.AsyncHttpClient) Timeout(org.junit.rules.Timeout) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Response(com.ning.http.client.Response) Before(org.junit.Before) ExampleCode(com.meltwater.rxrabbit.example.ExampleCode) Subscriber(rx.Subscriber) Semaphore(java.util.concurrent.Semaphore) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) Logger(com.meltwater.rxrabbit.util.Logger) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Rule(org.junit.Rule) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) AMQP(com.rabbitmq.client.AMQP) ArrayList(java.util.ArrayList) Semaphore(java.util.concurrent.Semaphore) Observable(rx.Observable) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) List(java.util.List) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 5 with Collections2

use of com.google.common.collect.Collections2 in project LanternServer by LanternPowered.

the class CommandHelp method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Comparator<CommandMapping> comparator = Comparator.comparing(CommandMapping::getPrimaryAlias);
    specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("command")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String nextArg = args.nextIfPresent().orElse("");
            return Lantern.getGame().getCommandManager().getAliases().stream().filter(new StartsWithPredicate(nextArg)).collect(Collectors.toList());
        }
    })).description(Text.of("View a list of all commands")).extendedDescription(Text.of("View a list of all commands. Hover over\n" + " a command to view its description. Click\n" + " a command to insert it into your chat bar.")).executor((src, args) -> {
        Optional<String> command = args.getOne("command");
        if (command.isPresent()) {
            Optional<? extends CommandMapping> mapping = Sponge.getCommandManager().get(command.get());
            if (mapping.isPresent()) {
                CommandCallable callable = mapping.get().getCallable();
                Optional<? extends Text> desc;
                // command name in the usage message
                if (callable instanceof CommandSpec) {
                    Text.Builder builder = Text.builder();
                    callable.getShortDescription(src).ifPresent(des -> builder.append(des, Text.NEW_LINE));
                    builder.append(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
                    Text extendedDescription;
                    try {
                        // TODO: Why is there no method :(
                        extendedDescription = (Text) extendedDescriptionField.get(callable);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                    if (extendedDescription != null) {
                        builder.append(Text.NEW_LINE, extendedDescription);
                    }
                    src.sendMessage(builder.build());
                } else if ((desc = callable.getHelp(src)).isPresent()) {
                    src.sendMessage(desc.get());
                } else {
                    src.sendMessage(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
                }
                return CommandResult.success();
            }
            throw new CommandException(Text.of("No such command: ", command.get()));
        }
        Lantern.getGame().getScheduler().submitAsyncTask(() -> {
            TreeSet<CommandMapping> commands = new TreeSet<>(comparator);
            commands.addAll(Collections2.filter(Sponge.getCommandManager().getAll().values(), input -> input.getCallable().testPermission(src)));
            final Text title = Text.builder("Available commands:").color(TextColors.DARK_GREEN).build();
            final List<Text> lines = commands.stream().map(c -> getDescription(src, c)).collect(Collectors.toList());
            // Console sources cannot see/use the pagination
            if (!(src instanceof ConsoleSource)) {
                Sponge.getGame().getServiceManager().provide(PaginationService.class).get().builder().title(title).padding(Text.of(TextColors.DARK_GREEN, "=")).contents(lines).sendTo(src);
            } else {
                src.sendMessage(title);
                src.sendMessages(lines);
            }
            return null;
        });
        return CommandResult.success();
    });
}
Also used : ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandMapping(org.spongepowered.api.command.CommandMapping) Collections2(com.google.common.collect.Collections2) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) GenericArguments(org.spongepowered.api.command.args.GenericArguments) TreeSet(java.util.TreeSet) PaginationList(org.spongepowered.api.service.pagination.PaginationList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) TextStyles(org.spongepowered.api.text.format.TextStyles) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Field(java.lang.reflect.Field) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) Lantern(org.lanternpowered.server.game.Lantern) Optional(java.util.Optional) Comparator(java.util.Comparator) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) TreeSet(java.util.TreeSet) CommandMapping(org.spongepowered.api.command.CommandMapping) PaginationList(org.spongepowered.api.service.pagination.PaginationList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) Nullable(javax.annotation.Nullable)

Aggregations

Collections2 (com.google.common.collect.Collections2)11 Collection (java.util.Collection)9 Set (java.util.Set)9 List (java.util.List)8 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 Collections (java.util.Collections)5 ImmutableSet (com.google.common.collect.ImmutableSet)4 File (java.io.File)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 TreeSet (java.util.TreeSet)3 Preconditions (com.google.common.base.Preconditions)2 Iterables (com.google.common.collect.Iterables)2 Lists (com.google.common.collect.Lists)2 Maps (com.google.common.collect.Maps)2 Sets (com.google.common.collect.Sets)2 Field (java.lang.reflect.Field)2 Arrays (java.util.Arrays)2