List of usage examples for com.google.common.base Predicates and
public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second)
From source file:org.dasein.cloud.jclouds.vcloud.director.compute.VmSupport.java
private VirtualMachine toVirtualMachine( RestContext<VCloudDirectorAdminClient, VCloudDirectorAdminAsyncClient> ctx, VApp app, Vm vcloudVm) throws CloudException, InternalException { if (vcloudVm == null) { return null; }//from ww w .j a v a 2s . c om VirtualMachine vm = new VirtualMachine(); String vmId = provider.toId(ctx, vcloudVm.getHref()); URI vdcURI = Iterables.find(app.getLinks(), Predicates.and(LinkPredicates.relEquals(Link.Rel.UP), LinkPredicates.typeEquals(VCloudDirectorMediaType.VDC))).getHref(); vm.setProviderVirtualMachineId(vmId); vm.setName(vcloudVm.getName()); vm.setDescription(vcloudVm.getDescription()); vm.setProviderOwnerId(provider.getOrg().getName()); vm.setProviderRegionId(provider.getContext().getRegionId()); vm.setProviderAssignedIpAddressId(null); vm.setProviderDataCenterId(provider.toId(ctx, vdcURI)); vm.setPlatform(Platform.guess(vm.getName() + " " + vm.getDescription())); vm.setArchitecture(Architecture.I64); vm.setClonable(true); vm.setImagable(true); vm.setPausable(true); vm.setPersistent(true); vm.setRebootable(true); if (vm.getName() == null) { vm.setName(app.getName()); if (vm.getName() == null) { vm.setName(vmId); } } if (vm.getDescription() == null) { vm.setDescription(app.getDescription()); if (vm.getDescription() == null) { vm.setDescription(vm.getName()); } } VirtualHardwareSection hardware = getSection(vcloudVm, VirtualHardwareSection.class); long ram = 256, cpus = 1; for (ResourceAllocationSettingData allocation : hardware.getItems()) { if (allocation.getResourceType().equals(ResourceType.MEMORY)) { ram = allocation.getVirtualQuantity().intValue(); } else if (allocation.getResourceType().equals(ResourceType.PROCESSOR)) { cpus = allocation.getVirtualQuantity().intValue(); } } VirtualMachineProduct product = getProduct(ram + ":" + cpus); if (product == null) { product = new VirtualMachineProduct(); product.setCpuCount((int) cpus); product.setRamInMb((int) ram); product.setProductId(ram + ":" + cpus); product.setDescription(ram + ":" + cpus); product.setName(product.getDescription()); product.setDiskSizeInGb(4); } vm.setProduct(product); ArrayList<String> publicIpAddresses = new ArrayList<String>(); ArrayList<String> privateIpAddresses = new ArrayList<String>(); String externalIp = null, providerNetworkId = null; System.out.println("Checking network connections: " + getSection(vcloudVm, NetworkConnectionSection.class).getNetworkConnections()); for (NetworkConnection c : getSection(vcloudVm, NetworkConnectionSection.class).getNetworkConnections()) { System.out.println("EXT=" + c.getExternalIpAddress()); System.out.println("Assigned=" + c.getIpAddress()); System.out.println("Model=" + c.getIpAddressAllocationMode()); System.out.println("Network=" + c.getNetwork()); if (c.getNetworkConnectionIndex() == getSection(vcloudVm, NetworkConnectionSection.class) .getPrimaryNetworkConnectionIndex()) { Iterable<VLAN> vlans = provider.getNetworkServices().getVlanSupport().listVlans(); for (VLAN vlan : vlans) { if (vlan.getName().equalsIgnoreCase(c.getNetwork())) { providerNetworkId = vlan.getProviderVlanId(); } } if (c.getExternalIpAddress() != null) { externalIp = c.getExternalIpAddress(); } if (c.getIpAddress() != null) { String addr = c.getIpAddress(); if (isPublicIp(addr)) { publicIpAddresses.add(addr); } else { privateIpAddresses.add(addr); } } } } String imageId = app.getDescription(); if (imageId != null) { VAppTemplate template; try { template = ctx.getApi().getVAppTemplateClient().getVAppTemplate(provider.toHref(ctx, imageId)); } catch (RuntimeException e) { template = null; } if (template != null) { VAppTemplateSupport support = provider.getComputeServices().getImageSupport(); vm.setProviderMachineImageId(imageId); vm.setArchitecture(support.getArchitecture(template)); vm.setPlatform(support.getPlatform(template)); } else if (imageId.startsWith("/vAppTemplate")) { vm.setProviderMachineImageId(imageId); } else { vm.setProviderMachineImageId( "/vAppTemplate/" + provider.getContext().getAccountNumber() + "-unknown"); } } else { vm.setProviderMachineImageId("/vAppTemplate/" + provider.getContext().getAccountNumber() + "-unknown"); } vm.setPrivateIpAddresses(privateIpAddresses.toArray(new String[0])); if (externalIp != null) { vm.setPublicIpAddresses(new String[] { externalIp }); } else { vm.setPublicIpAddresses(publicIpAddresses.toArray(new String[0])); } vm.setProviderVlanId(providerNetworkId); vm.setRootPassword(getSection(vcloudVm, GuestCustomizationSection.class).getAdminPassword()); vm.setRootUser(vm.getPlatform().isWindows() ? "administrator" : "root"); vm.setTags(new HashMap<String, String>()); switch (vcloudVm.getStatus()) { case POWERED_ON: vm.setCurrentState(VmState.RUNNING); break; case POWERED_OFF: case SUSPENDED: vm.setCurrentState(VmState.PAUSED); break; case FAILED_CREATION: vm.setCurrentState(VmState.TERMINATED); break; default: logger.warn("Unknown VM status: " + app.getStatus() + " for " + app.getHref().toASCIIString()); vm.setCurrentState(VmState.PENDING); break; } long created = System.currentTimeMillis(); long deployed = -1L, paused = -1L; for (Task task : vcloudVm.getTasks()) { if (task == null) { continue; } Date d = task.getStartTime(); if (d != null) { String txt = (task.getName() + " " + task.getType()).toLowerCase(); long when = d.getTime(); if (txt.contains("deploy")) { if (when > deployed) { deployed = when; } } if (txt.contains("poweroff")) { if (when > paused) { paused = when; } } if (when < created) { created = d.getTime(); } } } vm.setLastPauseTimestamp(paused); vm.setLastBootTimestamp(deployed); vm.setCreationTimestamp(created); vm.setTerminationTimestamp(0L); return vm; }
From source file:org.opensaml.xmlsec.impl.BasicEncryptionParametersResolver.java
/** * Get the effective list of key transport algorithm URIs to consider, including application of * whitelist/blacklist policy.//from w ww . jav a 2 s .com * * @param criteria the input criteria being evaluated * @param whitelistBlacklistPredicate the whitelist/blacklist predicate to use * * @return the list of effective algorithm URIs */ @Nonnull protected List<String> getEffectiveKeyTransportAlgorithms(@Nonnull final CriteriaSet criteria, @Nonnull final Predicate<String> whitelistBlacklistPredicate) { ArrayList<String> accumulator = new ArrayList<>(); for (EncryptionConfiguration config : criteria.get(EncryptionConfigurationCriterion.class) .getConfigurations()) { accumulator.addAll(Collections2.filter(config.getKeyTransportEncryptionAlgorithms(), Predicates.and(getAlgorithmRuntimeSupportedPredicate(), whitelistBlacklistPredicate))); } return accumulator; }
From source file:org.elasticsearch.test.hamcrest.ElasticsearchAssertions.java
public static void assertNodeContainsPlugins(NodesInfoResponse response, String nodeId, List<String> expectedJvmPluginNames, List<String> expectedJvmPluginDescriptions, List<String> expectedJvmVersions, List<String> expectedSitePluginNames, List<String> expectedSitePluginDescriptions, List<String> expectedSiteVersions) { Assert.assertThat(response.getNodesMap().get(nodeId), notNullValue()); PluginsInfo plugins = response.getNodesMap().get(nodeId).getPlugins(); Assert.assertThat(plugins, notNullValue()); List<String> pluginNames = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate) .transform(nameFunction).toList(); for (String expectedJvmPluginName : expectedJvmPluginNames) { Assert.assertThat(pluginNames, hasItem(expectedJvmPluginName)); }//w ww . j av a2 s. c o m List<String> pluginDescriptions = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate) .transform(descriptionFunction).toList(); for (String expectedJvmPluginDescription : expectedJvmPluginDescriptions) { Assert.assertThat(pluginDescriptions, hasItem(expectedJvmPluginDescription)); } List<String> jvmPluginVersions = FluentIterable.from(plugins.getInfos()).filter(jvmPluginPredicate) .transform(versionFunction).toList(); for (String pluginVersion : expectedJvmVersions) { Assert.assertThat(jvmPluginVersions, hasItem(pluginVersion)); } FluentIterable<String> jvmUrls = FluentIterable.from(plugins.getInfos()) .filter(Predicates.and(jvmPluginPredicate, Predicates.not(sitePluginPredicate))).filter(isNull()) .transform(urlFunction); Assert.assertThat(Iterables.size(jvmUrls), is(0)); List<String> sitePluginNames = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate) .transform(nameFunction).toList(); Assert.assertThat(sitePluginNames.isEmpty(), is(expectedSitePluginNames.isEmpty())); for (String expectedSitePluginName : expectedSitePluginNames) { Assert.assertThat(sitePluginNames, hasItem(expectedSitePluginName)); } List<String> sitePluginDescriptions = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate) .transform(descriptionFunction).toList(); Assert.assertThat(sitePluginDescriptions.isEmpty(), is(expectedSitePluginDescriptions.isEmpty())); for (String sitePluginDescription : expectedSitePluginDescriptions) { Assert.assertThat(sitePluginDescriptions, hasItem(sitePluginDescription)); } List<String> sitePluginUrls = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate) .transform(urlFunction).toList(); Assert.assertThat(sitePluginUrls, not(contains(nullValue()))); List<String> sitePluginVersions = FluentIterable.from(plugins.getInfos()).filter(sitePluginPredicate) .transform(versionFunction).toList(); Assert.assertThat(sitePluginVersions.isEmpty(), is(expectedSiteVersions.isEmpty())); for (String pluginVersion : expectedSiteVersions) { Assert.assertThat(sitePluginVersions, hasItem(pluginVersion)); } }
From source file:com.cloudera.impala.analysis.SelectStmt.java
/** * Create a map from COUNT([ALL]) -> zeroifnull(COUNT([ALL])) if * i) There is no GROUP-BY, and// w w w . j av a 2 s.c om * ii) There are other distinct aggregates to be evaluated. * This transformation is necessary for COUNT to correctly return 0 for empty * input relations. */ private ExprSubstitutionMap createCountAllMap(List<FunctionCallExpr> aggExprs, Analyzer analyzer) throws AnalysisException { ExprSubstitutionMap scalarCountAllMap = new ExprSubstitutionMap(); if (groupingExprs_ != null && !groupingExprs_.isEmpty()) { // There are grouping expressions, so no substitution needs to be done. return scalarCountAllMap; } com.google.common.base.Predicate<FunctionCallExpr> isNotDistinctPred = new com.google.common.base.Predicate<FunctionCallExpr>() { public boolean apply(FunctionCallExpr expr) { return !expr.isDistinct(); } }; if (Iterables.all(aggExprs, isNotDistinctPred)) { // Only [ALL] aggs, so no substitution needs to be done. return scalarCountAllMap; } com.google.common.base.Predicate<FunctionCallExpr> isCountPred = new com.google.common.base.Predicate<FunctionCallExpr>() { public boolean apply(FunctionCallExpr expr) { return expr.getFnName().getFunction().equals("count"); } }; Iterable<FunctionCallExpr> countAllAggs = Iterables.filter(aggExprs, Predicates.and(isCountPred, isNotDistinctPred)); for (FunctionCallExpr countAllAgg : countAllAggs) { // Replace COUNT(ALL) with zeroifnull(COUNT(ALL)) ArrayList<Expr> zeroIfNullParam = Lists.newArrayList(countAllAgg.clone()); FunctionCallExpr zeroIfNull = new FunctionCallExpr("zeroifnull", zeroIfNullParam); zeroIfNull.analyze(analyzer); scalarCountAllMap.put(countAllAgg, zeroIfNull); } return scalarCountAllMap; }
From source file:org.eclipse.sirius.diagram.ui.tools.internal.dialogs.DiagramElementsSelectionDialog.java
/** * Return all selected elements of the diagram that are display in the tree. * //from w ww.j av a 2 s. c o m * @return All selected elements of the diagram that are display in the * tree. */ protected Set<Object> getAllSelectedElements() { Set<Object> treeElements = getAllChildren(diagram); return Sets.newHashSet( Iterators.filter(treeElements.iterator(), Predicates.and(isSelected, Predicates.not(isGrayed)))); }
From source file:com.eucalyptus.vm.VmControl.java
public DescribeBundleTasksResponseType describeBundleTasks(final DescribeBundleTasksType request) throws EucalyptusCloudException { final DescribeBundleTasksResponseType reply = request.getReply(); final Filter filter = Filters.generate(request.getFilterSet(), VmBundleTask.class); final EntityTransaction db = Entities.get(VmInstance.class); try {//from www . j ava 2 s . co m // Get all from cache that match filters...... final Predicate<? super VmBundleTask> filteredAndBundling = Predicates.and(filter.asPredicate(), VmBundleTask.Filters.BUNDLING); Collection<VmBundleTask> cachedValues = Bundles.getPreviousBundleTasks().values(); final Map<String, VmBundleTask> cachedBundles = buildMap( Collections2.filter(cachedValues, filteredAndBundling)); final Predicate<? super VmInstance> requestedAndAccessible = CloudMetadatas .filteringFor(VmInstance.class).byId(toInstanceIds(request.getBundleIds())).byPrivileges() .buildPredicate(); // Get all from the db that are owned final Predicate<? super VmInstance> filteredInstances = Predicates.compose(filter.asPredicate(), VmInstances.bundleTask()); final Filter noFilters = Filters.generate(new ArrayList<edu.ucsb.eucalyptus.msgs.Filter>(), VmBundleTask.class); final Collection<VmInstance> dbBundles = VmInstances.list(null, noFilters.asCriterion(), noFilters.getAliases(), requestedAndAccessible); for (final VmInstance v : dbBundles) { if (filteredInstances.apply(v) && VmInstance.Filters.BUNDLING.apply(v)) { LOG.debug("Getting current bundle for " + v.getInstanceId()); reply.getBundleTasks().add(Bundles.transform(v.getRuntimeState().getBundleTask())); } else { if (!VmInstance.Filters.BUNDLING.apply(v) && cachedBundles.containsKey(v.getInstanceId())) { LOG.debug("Getting previous bundle for " + v.getInstanceId()); reply.getBundleTasks().add(Bundles.transform(cachedBundles.get(v.getInstanceId()))); } } } } catch (Exception ex) { Logs.exhaust().error(ex, ex); throw new EucalyptusCloudException(ex); } finally { db.rollback(); } return reply; }
From source file:org.apache.flex.compiler.internal.scopes.ASScope.java
/** * Find a property in an IDefinition, using the open namespaces & packages * of this scope, and any additional constraints that are passed in as a {@link Predicate}. * * @param project {@link ICompilerProject} whose symbol table is used to * resolve namespace references in the "use namespace" set this scope. * @param def The definition to resolve the property in * @param name The name of the definition to find * @param additional A {@link Predicate} that will perform additional filtering of the results. * This {@link Predicate} will run before any namespace set checking. * @param isSuperRef whether this lookup is through a 'super' reference - if * it is then the namespace set will be adjusted to use the base classes * protected namespace instead of the containing classes protected namespace * @return The IDefinition for the property, or null if one is not found *//* w ww. j a v a 2 s .co m*/ public IDefinition getPropertyFromDef(ICompilerProject project, IDefinition def, String name, Predicate<IDefinition> additional, boolean isSuperRef) { NamespaceSetPredicate nsPred = new NamespaceSetPredicate(project, getNamespaceSetForMemberAccess(project, def, isSuperRef)); Predicate<IDefinition> combinedPred = Predicates.and(additional, nsPred); return getPropertyFromDef((CompilerProject) project, def, name, combinedPred, nsPred, isSuperRef); }
From source file:org.obeonetwork.dsl.uml2.core.api.wizards.ModelElementsSelectionDialog.java
/** * Sets the predicate to use to detect which elements of the diagram are * selected, in the sense of the criterion to be edited. * * @param isGrayedPredicate// w ww.ja v a 2 s. c o m * the predicate to used to detect selected elements of the * diagram. */ @SuppressWarnings("unchecked") public void setGrayedPredicate(Predicate<EObject> isGrayedPredicate) { isGrayed = Predicates.and( (Predicate<? super Object>) (isGrayedPredicate != null ? isGrayedPredicate : Predicates.alwaysFalse()), AddElementToDiagramServices.INSTANCE.isValidForDiagram(diagram, eObject)); }
From source file:com.eucalyptus.simpleworkflow.SimpleWorkflowService.java
public Run startWorkflowExecution(final StartWorkflowExecutionRequest request) throws SimpleWorkflowException { final Context ctx = Contexts.lookup(); final UserFullName userFullName = ctx.getUserFullName(); final AccountFullName accountFullName = userFullName.asAccountFullName(); final Predicate<? super WorkflowType> accessible = SimpleWorkflowMetadatas.filteringFor(WorkflowType.class) .byPrivileges().buildPredicate(); final WorkflowExecution workflowExecution = allocate(new Supplier<WorkflowExecution>() { @Override/*from w ww .j a v a2 s . co m*/ public WorkflowExecution get() { try { if (!workflowExecutions.listByExample(WorkflowExecution.exampleForOpenWorkflow(accountFullName, request.getDomain(), request.getWorkflowId()), Predicates.alwaysTrue(), Functions.identity()).isEmpty()) { throw new SimpleWorkflowClientException("WorkflowExecutionAlreadyStartedFault", "Workflow open with ID " + request.getWorkflowId()); } final Domain domain; try { domain = domains.lookupByName(accountFullName, request.getDomain(), Registered, Functions.<Domain>identity()); } catch (SwfMetadataNotFoundException e) { throw upClient("UnknownResourceFault", "Unknown domain: " + request.getDomain()); } if (workflowExecutions.countOpenByDomain(accountFullName, domain.getDisplayName()) >= SimpleWorkflowProperties .getOpenWorkflowExecutionsPerDomain()) { throw upClient("LimitExceededFault", "Request would exceed limit for open workflow executions"); } final WorkflowType workflowType; try { workflowType = workflowTypes.lookupByExample( WorkflowType.exampleWithUniqueName(accountFullName, request.getDomain(), request.getWorkflowType().getName(), request.getWorkflowType().getVersion()), accountFullName, request.getWorkflowType().getName(), Predicates.and(accessible, WorkflowType.Status.Registered), Functions.<WorkflowType>identity()); } catch (SwfMetadataNotFoundException e) { throw upClient("UnknownResourceFault", "Unknown workflow type: " + request.getWorkflowType().getName()); } if (request.getChildPolicy() == null && workflowType.getDefaultChildPolicy() == null) { throw upClient("DefaultUndefinedFault", "Default child policy undefined"); } if (request.getTaskList() == null && workflowType.getDefaultTaskList() == null) { throw upClient("DefaultUndefinedFault", "Default task list undefined"); } final String childPolicy = Objects.firstNonNull(request.getChildPolicy(), workflowType.getDefaultChildPolicy()); final String taskList = request.getTaskList() == null ? workflowType.getDefaultTaskList() : request.getTaskList().getName(); final Integer executionStartToCloseTimeout = requireDefault( parsePeriod(request.getExecutionStartToCloseTimeout(), -1), workflowType.getDefaultExecutionStartToCloseTimeout(), "ExecutionStartToCloseTimeout"); final Integer taskStartToCloseTimeout = requireDefault( parsePeriod(request.getTaskStartToCloseTimeout(), -1), workflowType.getDefaultTaskStartToCloseTimeout(), "TaskStartToCloseTimeout"); final String taskStartToCloseTimeoutStr = taskStartToCloseTimeout < 0 ? "NONE" : String.valueOf(taskStartToCloseTimeout); final WorkflowExecution workflowExecution = WorkflowExecution.create(userFullName, UUID.randomUUID().toString(), domain, workflowType, request.getWorkflowId(), childPolicy, taskList, executionStartToCloseTimeout, taskStartToCloseTimeout < 0 ? null : taskStartToCloseTimeout, request.getTagList(), Lists.newArrayList( new WorkflowExecutionStartedEventAttributes().withChildPolicy(childPolicy) .withExecutionStartToCloseTimeout( String.valueOf(executionStartToCloseTimeout)) .withInput(request.getInput()).withParentInitiatedEventId(0L) .withTaskList(new TaskList().withName(taskList)) .withTagList(request.getTagList()) .withTaskStartToCloseTimeout(taskStartToCloseTimeoutStr) .withWorkflowType(request.getWorkflowType()), new DecisionTaskScheduledEventAttributes() .withStartToCloseTimeout(taskStartToCloseTimeoutStr) .withTaskList(request.getTaskList()))); return workflowExecutions.save(workflowExecution); } catch (Exception ex) { throw new RuntimeException(ex); } } }, WorkflowExecution.class, request.getWorkflowId()); notifyTaskList(accountFullName, workflowExecution.getDomainName(), "decision", workflowExecution.getTaskList()); final Run run = new Run(); run.setRunId(workflowExecution.getDisplayName()); return request.reply(run); }
From source file:org.obeonetwork.dsl.uml2.design.api.wizards.ModelElementsSelectionDialog.java
/** * Sets the predicate to use to detect which elements of the diagram are selected, in the sense of the * criterion to be edited.//from ww w . ja v a2s . co m * * @param isGrayedPredicate * the predicate to used to detect selected elements of the diagram. */ @SuppressWarnings("unchecked") public void setGrayedPredicate(Predicate<EObject> isGrayedPredicate) { isGrayed = Predicates.and((Predicate<? super Object>) (isGrayedPredicate != null ? isGrayedPredicate : Predicates.alwaysFalse()), isValidForDiagram()); }