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;
}
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;
}
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()]);
}
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));
}
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();
});
}
Aggregations