Example usage for com.google.common.base Predicates and

List of usage examples for com.google.common.base Predicates and

Introduction

In this page you can find the example usage for com.google.common.base Predicates and.

Prototype

public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) 

Source Link

Document

Returns a predicate that evaluates to true if both of its components evaluate to true .

Usage

From source file:com.github.jsdossier.Config.java

/**
 * Loads a new runtime configuration from the provided input stream.
 *///from ww w . j  a  v a2 s.c o m
static Config load(InputStream stream, FileSystem fileSystem) {
    ConfigSpec spec = ConfigSpec.load(stream, fileSystem);
    checkArgument(spec.output != null, "Output not specified");
    Path output = spec.output;
    boolean isZip = isZipFile(output);
    if (exists(output)) {
        checkArgument(isDirectory(output) || isZipFile(output),
                "Output path must be a directory or zip file: %s", output);
    }

    if (isZip) {
        FileSystem fs;
        try {
            if (output.getFileSystem() == FileSystems.getDefault()) {
                URI uri = URI.create("jar:file:" + output.toAbsolutePath());
                fs = FileSystems.newFileSystem(uri,
                        ImmutableMap.of("create", "true", "encoding", UTF_8.displayName()));
            } else {
                fs = output.getFileSystem().provider().newFileSystem(output,
                        ImmutableMap.of("create", "true", "encoding", UTF_8.displayName()));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        output = fs.getPath("/");
    }

    ImmutableSet<Path> excludes = resolve(spec.excludes);

    @SuppressWarnings("unchecked")
    Predicate<Path> filter = Predicates.and(notExcluded(excludes), notHidden());

    Iterable<Path> filteredSources = from(resolve(spec.sources)).filter(filter);
    Iterable<Path> filteredModules = from(resolve(spec.modules)).filter(filter);

    if (spec.closureLibraryDir.isPresent()) {
        ImmutableSet<Path> depsFiles = ImmutableSet.<Path>builder()
                .add(spec.closureLibraryDir.get().resolve("deps.js")).addAll(spec.closureDepsFile).build();

        try {
            filteredSources = processClosureSources(filteredSources, depsFiles, spec.closureLibraryDir.get());
        } catch (IOException | SortedDependencies.CircularDependencyException e) {
            throw new RuntimeException(e);
        }
    }

    return new Config(ImmutableSet.copyOf(filteredSources), ImmutableSet.copyOf(filteredModules),
            ImmutableSet.copyOf(resolve(spec.externs)), excludes, ImmutableSet.copyOf(spec.typeFilters), isZip,
            output, spec.readme, spec.customPages, spec.stripModulePrefix, spec.strict, spec.useMarkdown,
            spec.language, System.out, System.err, fileSystem);
}

From source file:org.apache.brooklyn.rest.resources.CatalogResource.java

@Override
public List<CatalogPolicySummary> listPolicies(String regex, String fragment, boolean allVersions) {
    Predicate<CatalogItem<Policy, PolicySpec<?>>> filter = Predicates.and(CatalogPredicates.IS_POLICY,
            CatalogPredicates.<Policy, PolicySpec<?>>disabled(false));
    List<CatalogItemSummary> result = getCatalogItemSummariesMatchingRegexFragment(filter, regex, fragment,
            allVersions);/*from   w  w w .  ja v  a2s .c  o  m*/
    return castList(result, CatalogPolicySummary.class);
}

From source file:com.eucalyptus.cluster.Migrations.java

private void rollbackInstanceEvacuations(final String sourceHost) {
    Predicate<VmInstance> filterHost = new Predicate<VmInstance>() {

        @Override/*from  w w  w .  j a  va 2  s . c  o m*/
        public boolean apply(@Nullable VmInstance input) {
            String vmHost = URI.create(input.getServiceTag()).getHost();
            return Strings.nullToEmpty(vmHost).equals(sourceHost);
        }
    };
    Predicate<VmInstance> rollbackMigration = new Predicate<VmInstance>() {

        @Override
        public boolean apply(@Nullable VmInstance input) {
            VmInstances.abortMigration(input);
            return true;
        }
    };
    Predicate<VmInstance> filterAndAbort = Predicates.and(this.filterPartition, rollbackMigration);
    Predicate<VmInstance> rollbackMigrationTx = Entities.asTransaction(VmInstance.class, filterAndAbort);
    VmInstances.list(rollbackMigrationTx);
}

From source file:org.artifactory.schedule.TaskServiceImpl.java

@Override
public void stopRelatedTasks(Class<? extends TaskCallback> typeToRun, List<String> tokenStopped,
        Object... keyValues) {//ww  w  .j ava 2 s  . co m
    // Extract task filters for each stop strategy
    EnumMap<StopStrategy, Predicate<Task>> predicatePerStrategy = getPredicatePerStrategy(typeToRun, keyValues);

    // Each predicates should not count myself :)
    Predicate<Task> notMyself = getNotMySelfPredicate();

    // Stop early if impossible to run
    Predicate<Task> impossibleFilter = predicatePerStrategy.get(StopStrategy.IMPOSSIBLE);
    if (impossibleFilter != null) {
        for (TaskBase activeTask : getActiveTasks(Predicates.and(notMyself, impossibleFilter))) {
            if (activeTask.processActive()) {
                throw new TaskImpossibleToStartException("Job " + typeToRun.getName()
                        + " cannot stop related job " + activeTask + " while it's running!");
            }
            // Immediate stop fails if task in running mode
            activeTask.stop(false);
            // Single execution task that are stopped don't need to be resumed because they'll die.
            // So, don't add the token to the list for stopped single exec tasks
            if (!activeTask.isSingleExecution()) {
                tokenStopped.add(activeTask.getToken());
            }
        }
    }

    // Then stop what's needed
    Predicate<Task> stopFilter = predicatePerStrategy.get(StopStrategy.STOP);
    if (stopFilter != null) {
        for (TaskBase activeTask : getActiveTasks(Predicates.and(notMyself, stopFilter))) {
            // Just stop and keep for resume
            activeTask.stop(true);
            // Single execution task that are stopped don't need to be resumed because they'll die.
            // So, don't add the token to the list for stopped single exec tasks
            if (!activeTask.isSingleExecution()) {
                tokenStopped.add(activeTask.getToken());
            }
        }
    }

    // Then pause what's needed
    Predicate<Task> pauseFilter = predicatePerStrategy.get(StopStrategy.PAUSE);
    if (pauseFilter != null) {
        for (TaskBase activeTask : getActiveTasks(Predicates.and(notMyself, pauseFilter))) {
            // Just stop and always keep for resume, since even single execution paused should be resumed
            activeTask.pause(true);
            tokenStopped.add(activeTask.getToken());
        }
    }
}

From source file:edu.udo.scaffoldhunter.model.dataimport.Importer.java

private List<PropertyDefinition> saveDatasetAndPropertyDefinitions(Dataset dataset,
        Map<String, PropertyDefinition> propDefs) {
    for (ImportJob j : importProcess.getJobs()) {
        for (Map.Entry<String, SourcePropertyMapping> e : j.getPropertyMappings().entrySet()) {
            if (e.getValue().getPropertyDefiniton() != null) {
                PropertyDefinition propDef = e.getValue().getPropertyDefiniton();
                // find unique key if key is not set
                if (propDef.getKey() == null || propDef.getKey().isEmpty()) {
                    String newKey;
                    for (int i = 0;; i++) {
                        newKey = propDef.getTitle().toUpperCase() + i;

                        /*
                         * prevents key collision with scaffold properties
                         * and calculated properties
                         *///from w ww  . j ava2  s. co  m
                        if (newKey.startsWith(ScaffoldTreeGenerator.SCAFFOLD_PROPERTY_KEY_PREFIX)
                                || newKey.startsWith(Calculator.CALC_PLUGINS_PROPERTY_KEY_PREFIX)) {
                            newKey = "_" + newKey;
                        }

                        if (!propDefs.containsKey(newKey))
                            break;
                    }
                    propDef.setKey(newKey);
                } else {
                    /*
                     * prevents key collision with scaffold properties and
                     * calculated properties
                     */
                    if (propDef.getKey().startsWith(ScaffoldTreeGenerator.SCAFFOLD_PROPERTY_KEY_PREFIX)
                            || propDef.getKey().startsWith(Calculator.CALC_PLUGINS_PROPERTY_KEY_PREFIX)) {
                        propDef.setKey("_" + propDef.getKey());
                    }
                }
                propDef.setDataset(dataset);
                propDefs.put(propDef.getKey(), propDef);
            }
        }
    }

    if (importProcess.getDataset() != null) {
        Predicate<PropertyDefinition> notOld = Predicates.and(Predicates.notNull(),
                Predicates.not(Predicates.in(importProcess.getDataset().getPropertyDefinitions().values())));
        newPropDefs = Lists.newArrayList(Iterables.filter(propDefs.values(), notOld));
    } else {
        newPropDefs = Lists.newArrayList(propDefs.values());
    }

    dataset.setPropertyDefinitions(propDefs);
    DBExceptionHandler.callDBManager(db, new VoidUnaryDBFunction<Dataset>(dataset) {
        @Override
        public void call(Dataset arg) throws DatabaseException {
            db.saveOrUpdate(newDataset);
            db.saveAllAsNew(newPropDefs);
        }
    });
    return newPropDefs;
}

From source file:org.jclouds.vcloud.director.v1_5.compute.strategy.VCloudDirectorComputeServiceAdapter.java

@Override
public NodeAndInitialCredentials<Vm> createNodeWithGroupEncodedIntoName(String group, String name,
        Template template) {//from  w w  w .  jav a 2  s . c  o m
    checkNotNull(template, "template was null");
    checkNotNull(template.getOptions(), "template options was null");

    String imageId = checkNotNull(template.getImage().getId(), "template image id must not be null");
    String locationId = checkNotNull(template.getLocation().getId(), "template location id must not be null");
    final String hardwareId = checkNotNull(template.getHardware().getId(),
            "template image id must not be null");

    VCloudDirectorTemplateOptions templateOptions = VCloudDirectorTemplateOptions.class
            .cast(template.getOptions());

    Vdc vdc = getVdc(locationId);

    final Reference networkReference;

    if (template.getOptions().getNetworks().isEmpty()) {
        Org org = getOrgForSession();
        Network.FenceMode fenceMode = Network.FenceMode.NAT_ROUTED;
        Optional<Network> optionalNetwork = tryFindNetworkInVDCWithFenceMode(api, vdc, fenceMode);
        if (!optionalNetwork.isPresent()) {
            throw new IllegalStateException(
                    "Can't find a network with fence mode: " + fenceMode + "in org " + org.getFullName());
        }
        networkReference = Reference.builder().href(optionalNetwork.get().getHref())
                .name(optionalNetwork.get().getName()).build();
    } else {
        String networkName = Iterables.getOnlyElement(template.getOptions().getNetworks());
        networkReference = tryFindNetworkInVDC(vdc, networkName);
    }

    VAppTemplate vAppTemplate = api.getVAppTemplateApi().get(imageId);
    Set<Vm> vms = getAvailableVMsFromVAppTemplate(vAppTemplate);
    // TODO now get the first vm to be added to vApp, what if more?
    Vm toAddVm = Iterables.get(vms, 0);

    // customize toAddVm
    GuestCustomizationSection guestCustomizationSection = api.getVmApi()
            .getGuestCustomizationSection(toAddVm.getHref());
    guestCustomizationSection = guestCustomizationSection.toBuilder().resetPasswordRequired(false).build();

    Statement guestCustomizationScript = ((VCloudDirectorTemplateOptions) (template.getOptions()))
            .getGuestCustomizationScript();
    if (guestCustomizationScript != null) {
        guestCustomizationSection = guestCustomizationSection.toBuilder()
                // TODO differentiate on guestOS
                .customizationScript(guestCustomizationScript.render(OsFamily.WINDOWS)).build();
    }

    SourcedCompositionItemParam vmItem = createVmItem(toAddVm, networkReference.getName(),
            guestCustomizationSection);
    ComposeVAppParams compositionParams = ComposeVAppParams.builder().name(name)
            .instantiationParams(instantiationParams(vdc, networkReference))
            .sourcedItems(ImmutableList.of(vmItem)).build();
    VApp vApp = api.getVdcApi().composeVApp(vdc.getId(), compositionParams);
    Task compositionTask = Iterables.getFirst(vApp.getTasks(), null);

    logger.debug(">> awaiting vApp(%s) deployment", vApp.getId());
    boolean vAppDeployed = waitForTask(compositionTask, timeouts.nodeRunning);
    logger.trace("<< vApp(%s) deployment completed(%s)", vApp.getId(), vAppDeployed);
    if (!vAppDeployed) {
        // TODO Destroy node? But don't have VM id yet.
        final String message = format("vApp(%s, %s) not composed within %d ms (task %s).", name, vApp.getId(),
                timeouts.nodeRunning, compositionTask.getHref());
        logger.warn(message);
        throw new IllegalStateException(message);
    }

    if (!vApp.getTasks().isEmpty()) {
        for (Task task : vApp.getTasks()) {
            logger.debug(">> awaiting vApp(%s) composition", vApp.getId());
            boolean vAppReady = waitForTask(task, timeouts.nodeRunning);
            logger.trace("<< vApp(%s) composition completed(%s)", vApp.getId(), vAppReady);
            if (!vAppReady) {
                // TODO Destroy node? But don't have VM id yet.
                final String message = format("vApp(%s, %s) post-compose not ready within %d ms (task %s).",
                        name, vApp.getId(), timeouts.nodeRunning, task.getHref());
                logger.warn(message);
                throw new IllegalStateException(message);
            }
        }
    }
    URI vAppHref = checkNotNull(vApp.getHref(), format("vApp %s must not have a null href", vApp.getId()));
    VApp composedVApp = api.getVAppApi().get(vAppHref);
    VAppChildren children = checkNotNull(composedVApp.getChildren(),
            format("composedVApp %s must not have null children", composedVApp.getId()));
    Vm vm = Iterables.getOnlyElement(children.getVms());

    if (!vm.getTasks().isEmpty()) {
        for (Task task : vm.getTasks()) {
            logger.debug(">> awaiting vm(%s) deployment", vApp.getId());
            boolean vmReady = waitForTask(task, timeouts.nodeRunning);
            logger.trace("<< vApp(%s) deployment completed(%s)", vApp.getId(), vmReady);
            if (!vmReady) {
                final String message = format(
                        "vApp(%s, %s) post-compose VM(%s) not ready within %d ms (task %s), so it will be destroyed",
                        name, vApp.getId(), vm.getHref(), timeouts.nodeRunning, task.getHref());
                logger.warn(message);
                destroyNode(vm.getId());
                throw new IllegalStateException(message);
            }
        }
    }

    // Configure VirtualHardware on a VM
    Optional<Hardware> hardwareOptional = Iterables.tryFind(listHardwareProfiles(), new Predicate<Hardware>() {
        @Override
        public boolean apply(Hardware input) {
            return input.getId().equals(hardwareId);
        }
    });

    // virtualCpus and memory templateOptions get the precedence over the default values given by hardwareId
    Integer virtualCpus = templateOptions.getVirtualCpus() == null ? getCoresFromHardware(hardwareOptional)
            : templateOptions.getVirtualCpus();
    Integer ram = templateOptions.getMemory() == null ? getRamFromHardware(hardwareOptional)
            : templateOptions.getMemory();
    Integer disk = templateOptions.getDisk();

    if (virtualCpus == null || ram == null) {
        String msg;
        if (hardwareOptional.isPresent()) {
            msg = format(
                    "vCPUs and RAM stats not available in hardware %s, and not configured in template options",
                    hardwareId);
        } else {
            msg = format(
                    "vCPUs and RAM stats not available - no hardware matching id %s, and not configured in template options; destroying VM",
                    hardwareId);
        }
        logger.error(msg + "; destroying VM and failing");
        destroyNode(vm.getId());
        throw new IllegalStateException(msg);
    }

    VirtualHardwareSection virtualHardwareSection = api.getVmApi().getVirtualHardwareSection(vm.getHref());

    Predicate<ResourceAllocationSettingData> processorPredicate = resourceTypeEquals(
            ResourceAllocationSettingData.ResourceType.PROCESSOR);
    virtualHardwareSection = updateVirtualHardwareSection(virtualHardwareSection, processorPredicate,
            virtualCpus + " virtual CPU(s)", BigInteger.valueOf(virtualCpus.intValue()));
    Predicate<ResourceAllocationSettingData> memoryPredicate = resourceTypeEquals(
            ResourceAllocationSettingData.ResourceType.MEMORY);
    virtualHardwareSection = updateVirtualHardwareSection(virtualHardwareSection, memoryPredicate,
            ram + " MB of memory", BigInteger.valueOf(ram.intValue()));
    if (disk != null) {
        Predicate<ResourceAllocationSettingData> diskPredicate = resourceTypeEquals(
                ResourceAllocationSettingData.ResourceType.DISK_DRIVE);
        Predicate<ResourceAllocationSettingData> elementPredicate = elementNameEquals("Hard disk 1");
        virtualHardwareSection = updateVirtualHardwareSectionDisk(virtualHardwareSection,
                Predicates.and(diskPredicate, elementPredicate), BigInteger.valueOf(disk.intValue()));
    }
    // NOTE this is not efficient but the vCD API v1.5 don't support editing hardware sections during provisioning
    Task editVirtualHardwareSectionTask = api.getVmApi().editVirtualHardwareSection(vm.getHref(),
            virtualHardwareSection);
    logger.debug(">> awaiting vm(%s) to be edited", vm.getId());
    boolean vmEdited = waitForTask(editVirtualHardwareSectionTask, timeouts.nodeRunning);
    logger.trace("<< vApp(%s) to be edited completed(%s)", vm.getId(), vmEdited);
    if (!vmEdited) {
        final String message = format(
                "vApp(%s, %s) VM(%s) edit not completed within %d ms (task %s); destroying VM", name,
                vApp.getId(), vm.getHref(), timeouts.nodeRunning, editVirtualHardwareSectionTask.getHref());
        logger.warn(message);
        destroyNode(vm.getId());
        throw new IllegalStateException(message);
    }

    Task deployTask = api.getVAppApi().deploy(vApp.getHref(), DeployVAppParams.builder().powerOn().build());
    logger.debug(">> awaiting vApp(%s) to be powered on", vApp.getId());
    boolean vAppPoweredOn = waitForTask(deployTask, timeouts.nodeRunning);
    logger.trace("<< vApp(%s) to be powered on completed(%s)", vApp.getId(), vAppPoweredOn);
    if (!vAppPoweredOn) {
        final String message = format(
                "vApp(%s, %s) power-on not completed within %d ms (task %s); destroying VM", name, vApp.getId(),
                timeouts.nodeRunning, deployTask.getHref());
        logger.warn(message);
        destroyNode(vm.getId());
        throw new IllegalStateException(message);
    }

    // Reload the VM; the act of "deploy" can change things like the password in the guest customization
    composedVApp = api.getVAppApi().get(vAppHref);
    children = checkNotNull(composedVApp.getChildren(),
            format("composedVApp %s must not have null children", composedVApp.getId()));
    vm = Iterables.getOnlyElement(children.getVms());

    // Infer the login credentials from the VM, defaulting to "root" user
    LoginCredentials defaultCredentials = VCloudDirectorComputeUtils.getCredentialsFrom(vm);
    LoginCredentials.Builder credsBuilder;
    if (defaultCredentials == null) {
        credsBuilder = LoginCredentials.builder().user("root");
    } else {
        credsBuilder = defaultCredentials.toBuilder();
        if (defaultCredentials.getUser() == null) {
            credsBuilder.user("root");
        }
    }
    // If login overrides are supplied in TemplateOptions, always prefer those.
    String overriddenLoginUser = template.getOptions().getLoginUser();
    String overriddenLoginPassword = template.getOptions().getLoginPassword();
    String overriddenLoginPrivateKey = template.getOptions().getLoginPrivateKey();
    if (overriddenLoginUser != null) {
        credsBuilder.user(overriddenLoginUser);
    }
    if (overriddenLoginPassword != null) {
        credsBuilder.password(overriddenLoginPassword);
    }
    if (overriddenLoginPrivateKey != null) {
        credsBuilder.privateKey(overriddenLoginPrivateKey);
    }
    return new NodeAndInitialCredentials<Vm>(vm, vm.getId(), credsBuilder.build());
}

From source file:com.eucalyptus.cluster.Migrations.java

@SuppressWarnings("unchecked")
private List<String> prepareInstanceEvacuations(final String sourceHost) {
    Predicate<VmInstance> filterHost = new Predicate<VmInstance>() {

        @Override/*from   w  ww .  j a va  2 s  . c  o  m*/
        public boolean apply(@Nullable VmInstance input) {
            String vmHost = URI.create(input.getServiceTag()).getHost();
            return Strings.nullToEmpty(vmHost).equals(sourceHost);
        }
    };
    Predicate<VmInstance> startMigration = new Predicate<VmInstance>() {

        @Override
        public boolean apply(@Nullable VmInstance input) {
            VmInstances.startMigration(input);
            return true;
        }
    };
    Predicate<VmInstance> filterAndAbort = Predicates.and(this.filterPartition, startMigration);
    Predicate<VmInstance> startMigrationTx = Entities.asTransaction(VmInstance.class, filterAndAbort);
    return Lists.transform(VmInstances.list(startMigrationTx), new Function<VmInstance, String>() {
        @Nullable
        @Override
        public String apply(@Nullable VmInstance vmInstance) {
            return vmInstance.getInstanceId();
        }
    });

}

From source file:org.apache.brooklyn.rest.resources.CatalogResource.java

@Override
public List<CatalogLocationSummary> listLocations(String regex, String fragment, boolean allVersions) {
    Predicate<CatalogItem<Location, LocationSpec<?>>> filter = Predicates.and(CatalogPredicates.IS_LOCATION,
            CatalogPredicates.<Location, LocationSpec<?>>disabled(false));
    List<CatalogItemSummary> result = getCatalogItemSummariesMatchingRegexFragment(filter, regex, fragment,
            allVersions);/*  ww w .  j ava2s. c o  m*/
    return castList(result, CatalogLocationSummary.class);
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.vertical.SequenceVerticalLayout.java

private Map<ISequenceEvent, Range> computeBasicRanges(Map<EventEnd, Integer> endLocations) {
    final Map<ISequenceEvent, Range> sequenceEventsToRange = new LinkedHashMap<ISequenceEvent, Range>();
    Predicate<ISequenceEvent> notMoved = Predicates.not(Predicates.in(sequenceEventsToRange.keySet()));

    // CombinedFragments
    for (EventEnd sortedEnd : semanticOrdering) {
        Predicate<ISequenceEvent> frames = Predicates.and(notMoved, Predicates.or(
                Predicates.instanceOf(CombinedFragment.class), Predicates.instanceOf(InteractionUse.class)));
        for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), frames)) {
            computeFinalRange(endLocations, sequenceEventsToRange, ise);
        }//from w w w .ja v  a 2 s.c  o  m
    }

    // Operands
    for (EventEnd sortedEnd : semanticOrdering) {
        Predicate<ISequenceEvent> operands = Predicates.and(notMoved, Predicates.instanceOf(Operand.class));
        for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), operands)) {
            computeFinalRange(endLocations, sequenceEventsToRange, ise);
        }
    }

    // Other sequence events
    for (EventEnd sortedEnd : semanticOrdering) {
        for (ISequenceEvent ise : Iterables.filter(endToISequencEvents.get(sortedEnd), notMoved)) {
            computeFinalRange(endLocations, sequenceEventsToRange, ise);
        }
    }
    return sequenceEventsToRange;
}

From source file:gov.nih.nci.firebird.data.Protocol.java

/**
 * @return active subinvestigator registrations.
 *///from  w  ww  .j  a v  a  2  s . c  om
@Transient
public Set<SubInvestigatorRegistration> getActiveSubinvestigatorRegistrations() {
    return FluentIterable.from(getSubinvestigatorRegistrations())
            .filter(Predicates.and(AbstractProtocolRegistration.IS_INVITED_PREDICATE,
                    SubInvestigatorRegistration.IS_ACTIVE_PREDICATE))
            .toSet();
}