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.jclouds.aws.ec2.EC2ContextBuilder.java
@Override public Injector buildInjector() { try {/*from w ww .j a v a2 s . c o m*/ Iterables.find(modules, Predicates.instanceOf(ConfigureELBModule.class)); } catch (NoSuchElementException e) { Iterable<Module> infra = Iterables.filter(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class) || input.getClass().isAnnotationPresent(ConfiguresHttpCommandExecutorService.class) || instanceOf(LoggingModule.class).apply(input); } }); modules.add(new ConfigureELBModule(infra, properties)); } return super.buildInjector(); }
From source file:org.testatoo.core.ListSelection.java
@Override public <O> Selection<O> transform(Class<? extends O> type) { return filter(Predicates.instanceOf(type)).transform(Selector.to(type)); }
From source file:com.google.api.server.spi.config.ApiConfigLoader.java
/** * Creates a {@link ApiConfigLoader}./* www . ja v a 2 s .c om*/ * * @param configFactory Factory class in charge of creating {@link ApiConfig}s. * @param typeLoader Utility class for dealing with types in endpoint config generation. * @param annotationSource Config source which reads annotations in endpoint classes. * @param apiConfigSources Additional config sources, if any, to operate on endpoints. * @throws IllegalArgumentException if {@code apiConfigSources} includes another instance * of ApiConfigAnnotationReader. */ public ApiConfigLoader(ApiConfig.Factory configFactory, TypeLoader typeLoader, ApiConfigAnnotationReader annotationSource, ApiConfigSource... apiConfigSources) { this.configFactory = Preconditions.checkNotNull(configFactory); this.typeLoader = Preconditions.checkNotNull(typeLoader); this.annotationSource = Preconditions.checkNotNull(annotationSource); this.apiConfigSources = ImmutableList.copyOf(apiConfigSources); Preconditions.checkArgument( !Iterables.any(this.apiConfigSources, Predicates.instanceOf(ApiConfigAnnotationReader.class)), "Multiple instances of the of ApiConfigAnnotationReader were passed in"); }
From source file:org.polymap.core.data.image.cache304.ClearCacheAction.java
@Override public void selectionChanged(IAction action, ISelection selection) { selected.clear();/*from w ww . j a v a 2 s . c om*/ action.setEnabled(false); for (ILayer layer : new SelectionAdapter(selection).elementsOfType(ILayer.class)) { // check permissions if (!ACLUtils.checkPermission(layer, AclPermission.WRITE, false)) { return; } // check cache processor in pipeline try { IService service = layer.getGeoResource().service(null); Pipeline pipeline = new DefaultPipelineIncubator().newPipeline(LayerUseCase.ENCODED_IMAGE, layer.getMap(), layer, service); PipelineProcessor found = Iterables.find(pipeline, Predicates.instanceOf(ImageCacheProcessor.class), null); if (found == null) { return; } } catch (Exception e) { log.warn("", e); return; } selected.add(layer); } action.setEnabled(true); }
From source file:org.apache.aurora.scheduler.thrift.aop.UserCapabilityInterceptor.java
@Override public Object invoke(MethodInvocation invocation) throws Throwable { Objects.requireNonNull(capabilityValidator, "Session validator has not yet been set."); // Ensure ROOT is always permitted. ImmutableList.Builder<Capability> whitelistBuilder = ImmutableList.<Capability>builder() .add(Capability.ROOT);// w ww .j a v a 2 s . co m Method method = invocation.getMethod(); Requires requires = method.getAnnotation(Requires.class); if (requires != null) { whitelistBuilder.add(requires.whitelist()); } List<Capability> whitelist = whitelistBuilder.build(); LOG.fine("Operation " + method.getName() + " may be performed by: " + whitelist); Optional<SessionKey> sessionKey = FluentIterable.from(Arrays.asList(invocation.getArguments())) .firstMatch(Predicates.instanceOf(SessionKey.class)).transform(CAST); if (!sessionKey.isPresent()) { LOG.severe("Interceptor should only be applied to methods accepting a SessionKey, but " + method + " does not."); return invocation.proceed(); } String key = capabilityValidator.toString(sessionKey.get()); for (Capability user : whitelist) { LOG.fine("Attempting to validate " + key + " against " + user); try { capabilityValidator.checkAuthorized(sessionKey.get(), user, AuditCheck.NONE); LOG.info("Permitting " + key + " to act as " + user + " and perform action " + method.getName()); return invocation.proceed(); } catch (AuthFailedException e) { LOG.fine("Auth failed: " + e); } } // User is not permitted to perform this operation. return Util.addMessage(Util.emptyResponse(), ResponseCode.AUTH_FAILED, "Session identified by '" + key + "' does not have the required capability to perform this action: " + whitelist); }
From source file:com.twitter.aurora.scheduler.thrift.aop.UserCapabilityInterceptor.java
@Override public Object invoke(MethodInvocation invocation) throws Throwable { Preconditions.checkNotNull(capabilityValidator, "Session validator has not yet been set."); // Ensure ROOT is always permitted. ImmutableList.Builder<Capability> whitelistBuilder = ImmutableList.<Capability>builder() .add(Capability.ROOT);//from w w w.j a va 2 s . co m Method method = invocation.getMethod(); Requires requires = method.getAnnotation(Requires.class); if (requires != null) { whitelistBuilder.add(requires.whitelist()); } List<Capability> whitelist = whitelistBuilder.build(); LOG.fine("Operation " + method.getName() + " may be performed by: " + whitelist); Optional<SessionKey> sessionKey = FluentIterable.from(Arrays.asList(invocation.getArguments())) .firstMatch(Predicates.instanceOf(SessionKey.class)).transform(CAST); if (!sessionKey.isPresent()) { LOG.severe("Interceptor should only be applied to methods accepting a SessionKey, but " + method + " does not."); return invocation.proceed(); } String key = capabilityValidator.toString(sessionKey.get()); for (Capability user : whitelist) { LOG.fine("Attempting to validate " + key + " against " + user); try { capabilityValidator.checkAuthorized(sessionKey.get(), user, AuditCheck.NONE); LOG.info("Permitting " + key + " to act as " + user + " and perform action " + method.getName()); return invocation.proceed(); } catch (AuthFailedException e) { LOG.fine("Auth failed: " + e); } } // User is not permitted to perform this operation. return Interceptors.properlyTypedResponse(method, ResponseCode.AUTH_FAILED, "Session identified by '" + key + "' does not have the required capability to perform this action: " + whitelist); }
From source file:org.eclipse.sirius.diagram.tools.internal.validation.description.constraints.RepresentationExtensionDescriptionRegexConstraint.java
@Override public IStatus validate(IValidationContext ctx) { IStatus status = null;/* w w w . j a va 2 s. c o m*/ EObject target = ctx.getTarget(); if (target instanceof RepresentationExtensionDescription) { RepresentationExtensionDescription representationExtensionDescription = (RepresentationExtensionDescription) target; Matcher representationNameMatcher = REGEX_PATTERN .matcher(representationExtensionDescription.getRepresentationName()); Matcher viewpointURIMatcher = REGEX_PATTERN .matcher(representationExtensionDescription.getViewpointURI()); if (representationNameMatcher.matches() && viewpointURIMatcher.matches()) { status = ctx.createSuccessStatus(); } else { // Check that the diagram extension contains only additional // layers if (!Iterables.all(representationExtensionDescription.eContents(), Predicates.instanceOf(AdditionalLayer.class))) { status = ctx.createFailureStatus( MessageFormat.format(ERROR_MESSAGE, representationExtensionDescription.getName())); } else if (!(representationExtensionDescription instanceof DiagramExtensionDescription)) { status = ctx.createFailureStatus( MessageFormat.format(ERROR_MESSAGE, representationExtensionDescription.getName())); } else { // Check that all additional layers of diagram extension // contains only style // customizations. for (AdditionalLayer additionalLayer : ((DiagramExtensionDescription) representationExtensionDescription) .getLayers()) { if (!Iterables.all(additionalLayer.eContents(), Predicates.instanceOf(Customization.class))) { status = ctx.createFailureStatus(MessageFormat.format(ERROR_MESSAGE, representationExtensionDescription.getName())); } } } } } if (status == null) { status = ctx.createSuccessStatus(); } return status; }
From source file:vazkii.botania.common.item.equipment.bauble.ItemDivaCharm.java
@SubscribeEvent public void onEntityDamaged(LivingHurtEvent event) { if (event.getSource().getEntity() instanceof EntityPlayer && event.getEntityLiving() instanceof EntityLiving && !event.getEntityLiving().worldObj.isRemote && Math.random() < 0.6F) { EntityPlayer player = (EntityPlayer) event.getSource().getEntity(); ItemStack amulet = BaublesApi.getBaubles(player).getStackInSlot(6); if (amulet != null && amulet.getItem() == this) { final int cost = 250; if (ManaItemHandler.requestManaExact(amulet, player, cost, false)) { final int range = 20; List mobs = player.worldObj.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(event.getEntityLiving().posX - range, event.getEntityLiving().posY - range, event.getEntityLiving().posZ - range, event.getEntityLiving().posX + range, event.getEntityLiving().posY + range, event.getEntityLiving().posZ + range), Predicates.instanceOf(IMob.class)); if (mobs.size() > 1) { if (SubTileHeiseiDream.brainwashEntity((EntityLiving) event.getEntityLiving(), (List<IMob>) mobs)) { if (event.getEntityLiving() instanceof EntityCreeper) ReflectionHelper.setPrivateValue(EntityCreeper.class, (EntityCreeper) event.getEntityLiving(), 2, LibObfuscation.TIME_SINCE_IGNITED); event.getEntityLiving().heal(event.getEntityLiving().getMaxHealth()); if (event.getEntityLiving().isDead) event.getEntityLiving().isDead = false; ManaItemHandler.requestManaExact(amulet, player, cost, true); player.worldObj.playSound(null, player.posX, player.posY, player.posZ, BotaniaSoundEvents.divaCharm, SoundCategory.PLAYERS, 1F, 1F); double x = event.getEntityLiving().posX; double y = event.getEntityLiving().posY; double z = event.getEntityLiving().posZ; for (int i = 0; i < 50; i++) Botania.proxy.sparkleFX(x + Math.random() * event.getEntityLiving().width, y + Math.random() * event.getEntityLiving().height, z + Math.random() * event.getEntityLiving().width, 1F, 1F, 0.25F, 1F, 3); }/*from w ww .j av a2 s. c o m*/ } } } } }
From source file:org.pentaho.di.trans.dataservice.optimization.cache.CachedServiceLoader.java
ListenableFuture<Integer> replay(DataServiceExecutor dataServiceExecutor) throws KettleException { final Trans serviceTrans = dataServiceExecutor.getServiceTrans(), genTrans = dataServiceExecutor.getGenTrans(); final CountDownLatch startReplay = new CountDownLatch(1); final RowProducer rowProducer = dataServiceExecutor.addRowProducer(); List<Runnable> startTrans = dataServiceExecutor.getListenerMap() .get(DataServiceExecutor.ExecutionPoint.START), postOptimization = dataServiceExecutor.getListenerMap() .get(DataServiceExecutor.ExecutionPoint.READY); Iterables.removeIf(postOptimization, Predicates.instanceOf(DefaultTransWiring.class)); Iterables.removeIf(startTrans, new Predicate<Runnable>() { @Override/* w w w. ja v a 2s .c o m*/ public boolean apply(Runnable runnable) { return runnable instanceof TransStarter && ((TransStarter) runnable).getTrans().equals(serviceTrans); } }); postOptimization.add(new Runnable() { @Override public void run() { serviceTrans.stopAll(); for (StepMetaDataCombi stepMetaDataCombi : serviceTrans.getSteps()) { stepMetaDataCombi.step.setOutputDone(); stepMetaDataCombi.step.dispose(stepMetaDataCombi.meta, stepMetaDataCombi.data); stepMetaDataCombi.step.markStop(); } } }); startTrans.add(new Runnable() { @Override public void run() { startReplay.countDown(); } }); ListenableFutureTask<Integer> replay = ListenableFutureTask.create(new Callable<Integer>() { @Override public Integer call() throws Exception { Preconditions.checkState(startReplay.await(30, TimeUnit.SECONDS), "Cache replay did not start"); int rowCount = 0; for (Iterator<RowMetaAndData> iterator = rowSupplier.get(); iterator.hasNext() && genTrans.isRunning();) { RowMetaAndData metaAndData = iterator.next(); boolean rowAdded = false; RowMetaInterface rowMeta = metaAndData.getRowMeta(); Object[] rowData = rowMeta.cloneRow(metaAndData.getData()); while (!rowAdded && genTrans.isRunning()) { rowAdded = rowProducer.putRowWait(rowMeta, rowData, 10, TimeUnit.SECONDS); } if (rowAdded) { rowCount += 1; } } rowProducer.finished(); return rowCount; } }); executor.execute(replay); return replay; }
From source file:org.eclipse.incquery.patternlanguage.emf.ui.contentassist.PatternImporter.java
@Override public void apply(final IDocument document, final ConfigurableCompletionProposal proposal) throws BadLocationException { if (document instanceof IXtextDocument) { IXtextDocument xtextDocument = (IXtextDocument) document; if (targetPattern == null || Strings.isNullOrEmpty(targetPattern.getName())) return; importStatus = ((IXtextDocument) document).readOnly(new IUnitOfWork<ImportState, XtextResource>() { @Override/*from ww w . j av a2 s . co m*/ public ImportState exec(XtextResource state) throws Exception { final PatternModel model = (PatternModel) Iterators.find(state.getAllContents(), Predicates.instanceOf(PatternModel.class)); if (targetPackage.equals(model.getPackageName())) { return ImportState.SAMEPACKAGE; } final XImportSection importSection = model.getImportPackages(); PatternImport relatedImport = Iterables.find(importSection.getPatternImport(), new Predicate<PatternImport>() { @Override public boolean apply(PatternImport decl) { return targetPattern.equals(decl.getPattern()) || targetPattern.getName().equals(decl.getPattern().getName()); } }, null); if (relatedImport == null) { return ImportState.NONE; } // Checking whether found pattern definition equals to different pattern if (targetPattern.equals(relatedImport.getPattern())) { return ImportState.FOUND; } else { return ImportState.CONFLICTING; } } }); String replacementString = getActualReplacementString(proposal) + "();"; ReplaceEdit edit = new ReplaceEdit(proposal.getReplacementOffset(), proposal.getReplacementLength(), replacementString); edit.apply(document); //+2 is used to put the cursor inside the parentheses int cursorOffset = getActualReplacementString(proposal).length() + 2; if (importStatus == ImportState.NONE) { xtextDocument.modify(new Void<XtextResource>() { @Override public void process(XtextResource state) throws Exception { XImportSection importSection = (XImportSection) Iterators.find(state.getAllContents(), Predicates.instanceOf(XImportSection.class), null); if (importSection.getImportDeclarations().size() + importSection.getPackageImport().size() + importSection.getPatternImport().size() == 0) { //Empty import sections need to be replaced to generate white space after the package declaration XImportSection newSection = EMFPatternLanguageFactory.eINSTANCE.createXImportSection(); ((PatternModel) importSection.eContainer()).setImportPackages(newSection); importSection = newSection; } PatternImport newImport = EMFPatternLanguageFactory.eINSTANCE.createPatternImport(); newImport.setPattern(targetPattern); importSection.getPatternImport().add(newImport); } }); //Two new lines + "import " + pattern fqn cursorOffset += 2 + 7 + CorePatternLanguageHelper.getFullyQualifiedName(targetPattern).length(); } proposal.setCursorPosition(cursorOffset); } }