List of usage examples for com.google.common.base Predicates instanceOf
@GwtIncompatible("Class.isInstance") public static Predicate<Object> instanceOf(Class<?> clazz)
From source file:org.eclipse.sirius.diagram.editor.properties.sections.style.edgestyledescription.EdgeStyleDescriptionCenteredSourceMappingsPropertySection.java
@Override protected List<?> getChoiceOfValues(List<?> currentValues) { List<?> choiceOfValues = super.getChoiceOfValues(currentValues); removeUnrelatedMappings(choiceOfValues); Collection<?> collection = Collections2.filter(choiceOfValues, Predicates.instanceOf(AbstractNodeMapping.class)); return new ArrayList<Object>(collection); }
From source file:org.eclipse.sirius.diagram.ui.tools.internal.layout.DiagramLayoutCustomization.java
private int findPaddingFromSelection(final Collection selectedObjects) { int foundPadding = 30; Collection<IGraphicalEditPart> filteredSelection = Collections2.filter(selectedObjects, Predicates.instanceOf(GraphicalEditPart.class)); for (final IGraphicalEditPart obj : filteredSelection) { foundPadding = getEditPartPadding(obj); if (foundPadding != 30) break; }/*from w w w . j a v a2s.com*/ return foundPadding; }
From source file:org.eclipse.sirius.ui.tools.internal.views.common.modelingproject.OpenRepresentationsFileJob.java
/** * Launch this job when all other openRepresentationFile's job are finished. * * @param elements/*www .j av a 2s.c o m*/ * A list of URIs of the representations files to open or a list * of the modeling projects to initialize and open. * @param user * <code>true</code> if this job is a user-initiated job, and * <code>false</code> otherwise. */ public static void scheduleNewWhenPossible(List<? extends Object> elements, boolean user) { if (!(Iterators.all(elements.iterator(), Predicates.instanceOf(URI.class)) || Iterators.all(elements.iterator(), Predicates.instanceOf(ModelingProject.class)))) { throw new IllegalArgumentException(Messages.OpenRepresentationsFileJob_errorInvalidInputList); } // Just wait other job if some are already in progress OpenRepresentationsFileJob.waitOtherJobs(); // Schedule a new job for this representations file. Job job = new OpenRepresentationsFileJob(elements); job.setUser(user); job.setPriority(Job.SHORT); job.schedule(); }
From source file:edu.buaa.satla.analysis.util.CFATraversal.java
/** * Returns a new instance of this class which behaves exactly like the current * instance, except it ignores summary edges ({@link FunctionSummaryEdge}s). * It will not call the visitor for them, and it will not follow this edge * during traversing.// w w w .ja va 2 s .c o m */ public CFATraversal ignoreSummaryEdges() { return new CFATraversal(edgeSupplier, successorSupplier, Predicates.<CFAEdge>or(ignoreEdge, Predicates.instanceOf(FunctionSummaryEdge.class))); }
From source file:org.apache.aurora.scheduler.config.CliOptions.java
/** * Gets a custom options object of a particular type. * * @param customOptionType Custom option type class. * @param <T> Custom option type./* ww w .j a v a 2s .co m*/ * @return The matching custom option object. */ @SuppressWarnings("unchecked") public <T> T getCustom(Class<T> customOptionType) { return (T) FluentIterable.from(custom).firstMatch(Predicates.instanceOf(customOptionType)).get(); }
From source file:org.apache.brooklyn.entity.group.zoneaware.BalancingNodePlacementStrategy.java
protected Collection<Entity> pickNewest(Collection<Entity> contenders, Integer numToPick) { // choose newest entity that is stoppable; sort so newest is first List<Entity> stoppables = Lists .newLinkedList(Iterables.filter(contenders, Predicates.instanceOf(Startable.class))); Collections.sort(stoppables, new Comparator<Entity>() { @Override//from ww w. j a va 2 s .c o m public int compare(Entity a, Entity b) { return (int) (b.getCreationTime() - a.getCreationTime()); } }); return stoppables.subList(0, Math.min(numToPick, stoppables.size())); }
From source file:com.netflix.priam.defaultimpl.PriamGuiceModule.java
@Provides @Singleton/* w w w . j a v a 2s . c o m*/ HostAndPort providePort(PriamConfiguration configuration) { ServerFactory serverFactory = configuration.getServerFactory(); // Our method for obtaining connector factories from the server factory varies depending on the latter's type List<ConnectorFactory> connectorFactories; if (serverFactory instanceof DefaultServerFactory) { connectorFactories = ((DefaultServerFactory) serverFactory).getApplicationConnectors(); } else if (serverFactory instanceof SimpleServerFactory) { connectorFactories = Collections.singletonList(((SimpleServerFactory) serverFactory).getConnector()); } else { throw new IllegalStateException("Encountered an unexpected ServerFactory type"); } // Find the first connector that matches and return its port information (in practice there should // be one, and just one, match) try { HttpConnectorFactory httpConnectorFactory = (HttpConnectorFactory) Iterables.find(connectorFactories, Predicates.instanceOf(HttpConnectorFactory.class)); String host = httpConnectorFactory.getBindHost(); if (host == null) { host = InetAddress.getLocalHost().getHostAddress(); } int port = httpConnectorFactory.getPort(); return HostAndPort.fromParts(host, port); } catch (UnknownHostException ex) { throw new IllegalStateException("Unable to determine the local host address for the server", ex); } catch (NoSuchElementException ex) { throw new IllegalStateException("Did not find a valid HttpConnector for the server", ex); } }
From source file:controllers.ModuleController.java
private static List<ModuleModel> getNextModules(String input) { // get all the supplied view models. List<ViewModel> suppliedViewModels = Lists.newArrayList(); JsonNode inputJson = Json.parse(input); // convert json nodes to view models. if (inputJson != null && inputJson.isArray()) { suppliedViewModels = Lists//from w w w .j av a2 s . c om .newArrayList(Iterators.transform(inputJson.getElements(), new Function<JsonNode, ViewModel>() { @Override @Nullable public ViewModel apply(@Nullable JsonNode input) { if (!input.isTextual()) { return null; } return createViewModelQuietly( fetchResource(UuidUtils.create(input.asText()), PersistentObject.class), null); } })); } else if (inputJson != null && inputJson.isObject()) { suppliedViewModels.add(createViewModelQuietly(inputJson, null)); } suppliedViewModels = Lists.newArrayList(Iterables.filter(suppliedViewModels, Predicates.notNull())); // get all the modules that can use these inputs. Map<Module, Double> nullModulesMap = Maps.newHashMap(); Map<Module, Double> modulesMap = Maps.newHashMap(); Reflections reflections = new Reflections("controllers.modules", Play.application().classloader()); for (Class<? extends Module> moduleClass : reflections.getSubTypesOf(Module.class)) { // we're not interested in abstract classes. if (Modifier.isAbstract(moduleClass.getModifiers())) { continue; } // get the Module.Requires/Requireses annotation for each module class. // the requirements within each Module.Require are ANDed. // the requirements across multiple Module.Require annotations are ORed. List<Module.Requires> requireds = Lists.newArrayList(); if (moduleClass.isAnnotationPresent(Module.Requires.class)) { requireds.add(moduleClass.getAnnotation(Module.Requires.class)); } if (moduleClass.isAnnotationPresent(Module.Requireses.class)) { Collections.addAll(requireds, moduleClass.getAnnotation(Module.Requireses.class).value()); } if (requireds.size() == 0) { requireds.add(null); } for (Module.Requires required : requireds) { final Set<Class<? extends ViewModel>> requiredViewModelClasses = Sets.newHashSet(); if (required != null) { Collections.addAll(requiredViewModelClasses, required.value()); } // get all the supplied view modules that are relevant to this module. List<ViewModel> usefulViewModels = Lists .newArrayList(Iterables.filter(suppliedViewModels, new Predicate<ViewModel>() { @Override public boolean apply(@Nullable ViewModel input) { // if this class is required, then return true. if (requiredViewModelClasses.contains(input.getClass())) { return true; } // if any of its super classes are required, that also works. for (Class<?> superClass : ClassUtils.getAllSuperclasses(input.getClass())) { if (requiredViewModelClasses.contains(superClass)) { return true; } } return false; } })); // if all the requirements were satisfied. if (usefulViewModels.size() >= requiredViewModelClasses.size()) { // try to create an instance of the module. Module module = null; try { module = moduleClass.newInstance(); module.setViewModels(usefulViewModels); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { module = null; } finally { // if no module was created, just ignore. if (module == null) { continue; } } // let's not divide by zero! double relevancyScore = suppliedViewModels.size() != 0 ? usefulViewModels.size() / (double) suppliedViewModels.size() : 1.0; // keep null modules separate. Map<Module, Double> targetModulesMap = null; if (requiredViewModelClasses.size() > 0) { // if a module of this type does not exist, add it. if (Maps.filterKeys(modulesMap, Predicates.instanceOf(moduleClass)).size() == 0) { targetModulesMap = modulesMap; } } else { targetModulesMap = nullModulesMap; } if (targetModulesMap != null) { targetModulesMap.put(module, relevancyScore); } } } } // use null modules only if there are no regular ones. if (modulesMap.size() == 0) { modulesMap = nullModulesMap; } // convert to view models. Set<ModuleModel> moduleViewModels = Sets.newHashSet( Iterables.transform(modulesMap.entrySet(), new Function<Entry<Module, Double>, ModuleModel>() { @Override @Nullable public ModuleModel apply(@Nullable Entry<Module, Double> input) { return new ModuleModel(input.getKey()).setRelevancyScore(input.getValue()); } })); // order first by relevance and then by name. return Ordering.from(new Comparator<ModuleModel>() { @Override public int compare(ModuleModel o1, ModuleModel o2) { int relDiff = (int) Math.round((o2.relevancyScore - o1.relevancyScore) * 1000); if (relDiff == 0) { return o1.name.compareTo(o2.name); } return relDiff; } }).sortedCopy(moduleViewModels); }
From source file:com.cloudera.impala.planner.PlanFragment.java
/** * Finalize plan tree and create stream sink, if needed. * If this fragment is hash partitioned, ensures that the corresponding partition * exprs of all hash-partitioning senders are cast to identical types. * Otherwise, the hashes generated for identical partition values may differ * among senders if the partition-expr types are not identical. *//* w ww.ja v a 2s . co m*/ public void finalize(Analyzer analyzer) throws InternalException, NotImplementedException { if (planRoot_ != null) computeCanAddSlotFilters(planRoot_); if (destNode_ != null) { Preconditions.checkState(sink_ == null); // we're streaming to an exchange node DataStreamSink streamSink = new DataStreamSink(destNode_, outputPartition_); streamSink.setFragment(this); sink_ = streamSink; } if (!dataPartition_.isHashPartitioned()) return; // This fragment is hash partitioned. Gather all exchange nodes and ensure // that all hash-partitioning senders hash on exprs-values of the same type. List<ExchangeNode> exchNodes = Lists.newArrayList(); planRoot_.collect(Predicates.instanceOf(ExchangeNode.class), exchNodes); // Contains partition-expr lists of all hash-partitioning sender fragments. List<List<Expr>> senderPartitionExprs = Lists.newArrayList(); for (ExchangeNode exchNode : exchNodes) { Preconditions.checkState(!exchNode.getChildren().isEmpty()); PlanFragment senderFragment = exchNode.getChild(0).getFragment(); Preconditions.checkNotNull(senderFragment); if (!senderFragment.getOutputPartition().isHashPartitioned()) continue; List<Expr> partExprs = senderFragment.getOutputPartition().getPartitionExprs(); // All hash-partitioning senders must have compatible partition exprs, otherwise // this fragment's data partition must not be hash partitioned. Preconditions.checkState(partExprs.size() == dataPartition_.getPartitionExprs().size()); senderPartitionExprs.add(partExprs); } // Cast all corresponding hash partition exprs of all hash-partitioning senders // to their compatible types. Also cast the data partition's exprs for consistency, // although not strictly necessary. They should already be type identical to the // exprs of one of the senders and they are not directly used for hashing in the BE. senderPartitionExprs.add(dataPartition_.getPartitionExprs()); try { analyzer.castToUnionCompatibleTypes(senderPartitionExprs); } catch (AnalysisException e) { // Should never happen. Analysis should have ensured type compatibility already. throw new IllegalStateException(e); } }
From source file:com.googlecode.blaisemath.style.AttributeSet.java
/** * Return attributes of the given type, whether in this set or the parent set. * @param type attribute type//from ww w . ja va 2 s . c o m * @return attribute keys */ public Set<String> getAllAttributes(Class type) { Map<String, Object> filtered = Maps.filterValues(attributeMap, Predicates.instanceOf(type)); if (parent.isPresent()) { return Sets.union(filtered.keySet(), parent.get().getAllAttributes(type)); } else { return filtered.keySet(); } }