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

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

Introduction

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

Prototype

public static <T> Predicate<T> not(Predicate<T> predicate) 

Source Link

Document

Returns a predicate that evaluates to true if the given predicate evaluates to false .

Usage

From source file:co.cask.tigon.internal.app.runtime.distributed.AbstractProgramTwillRunnable.java

/**
 * Creates program arguments. It includes all configurations from the specification, excluding hConf and cConf.
 *//* w w  w .ja v  a  2 s.c o  m*/
private Arguments createProgramArguments(TwillContext context, Map<String, String> configs) {
    Map<String, String> args = ImmutableMap.<String, String>builder()
            .put(ProgramOptionConstants.INSTANCE_ID, Integer.toString(context.getInstanceId()))
            .put(ProgramOptionConstants.INSTANCES, Integer.toString(context.getInstanceCount()))
            .put(ProgramOptionConstants.RUN_ID, context.getApplicationRunId().getId())
            .putAll(Maps.filterKeys(configs, Predicates.not(Predicates.in(ImmutableSet.of("hConf", "cConf")))))
            .build();

    return new BasicArguments(args);
}

From source file:org.eclipse.sirius.diagram.sequence.ui.tool.internal.edit.policy.ISEComplexMoveCommandBuilder.java

private void computeReparents(Collection<ISequenceNode> sequenceNodesToMove,
        Map<AbstractNodeEvent, ISequenceEvent> reparents) {
    // reparent directly moved execution
    Collection<AbstractNodeEvent> movedExecutions = Lists
            .newArrayList(Iterables.filter(sequenceNodesToMove, AbstractNodeEvent.class));

    // reparent unmoved executions
    Collection<AbstractNodeEvent> unmovedExecutions = Lists
            .newArrayList(Iterables.filter(validator.getDiagram().getAllAbstractNodeEvents(),
                    Predicates.not(Predicates.in(validator.getMovedElements()))));

    for (AbstractNodeEvent execToReparent : Iterables.concat(movedExecutions, unmovedExecutions)) {
        ISequenceEvent potentialParent = getNewParent(execToReparent, reparents);
        if (potentialParent instanceof ISequenceNode
                && !potentialParent.equals(execToReparent.getHierarchicalParentEvent())) {
            reparents.put(execToReparent, potentialParent);
            sequenceNodesToMove.remove(execToReparent);
        }/*www  .j a  v  a 2  s.c o m*/
    }
}

From source file:org.codeseed.common.config.PropertySources.java

/**
 * Returns a source which returns the first non-{@code null} value from a
 * series of sources./* w  w w  . jav a  2 s.  c o m*/
 *
 * @param sources
 *            the ordered sources to combine
 * @return property source that considers multiple sources
 */
public static PropertySource compose(Iterable<PropertySource> sources) {
    FluentIterable<PropertySource> s = FluentIterable.from(sources)
            .filter(Predicates.not(Predicates.equalTo(empty())));
    if (s.isEmpty()) {
        return empty();
    } else if (s.size() == 1) {
        return s.first().get();
    } else {
        return new CompositionSource(s.toList());
    }
}

From source file:edu.udo.scaffoldhunter.gui.dialogs.ConnectionDialog.java

private void setConnection(ConnectionData connection) {
    if (connection == null) {
        ((CardLayout) profilePanel.getLayout()).show(profilePanel, NO_CONNECTION);
        nameText.setEnabled(false);/*from  w  w w  . ja v a2 s.  c  o  m*/
        typeDBCombo.setEnabled(false);
        return;
    } else {
        ((CardLayout) profilePanel.getLayout()).show(profilePanel, connection.getDbType().name());
        nameText.setEnabled(true);
        typeDBCombo.setEnabled(true);
    }
    connectionList.setSelectedValue(connection, true);
    nameText.setText(connection.getConnectionName());
    typeDBCombo.setSelectedItem(connection.getDbType());
    ProfilePanel panel = profilePanels.get(connection.getDbType());
    panel.setData(connection);
    Predicate<ConnectionType> other = Predicates.not(Predicates.equalTo(connection.getDbType()));
    for (ProfilePanel p : Maps.filterKeys(profilePanels, other).values()) {
        p.clearData();
    }
    validateListener.validate();
    if (dataManager.getConnections().contains(connection)) {
        needsSaving = null;
    } else {
        needsSaving = connection;
    }
}

From source file:com.sri.ai.grinder.library.Equality.java

/**
 * Assumes that first argument is an equality (with possibly more than two arguments) and returns a pair,
 * the first member of which is a collection of the variables in the equality,
 * and the second member of which is the first constant present.
 * Returns null if there are no constants in the equality arguments.
 *//*from w w w  .j a v a 2 s  . co  m*/
public static Pair<List<Expression>, Expression> getVariablesListAndConstantOrNullIfNoConstant(
        Expression equality, RewritingProcess process) {
    Pair<List<Expression>, Expression> result;
    List<Expression> variables = new LinkedList<Expression>();
    List<Expression> constants = new LinkedList<Expression>();
    Predicate<Expression> notIsConstant = Predicates.not(process.getIsUniquelyNamedConstantPredicate());
    Util.collectOrReturnFalseIfElementDoesNotFitEither(equality.getArguments(), variables, notIsConstant,
            constants, process.getIsUniquelyNamedConstantPredicate());
    if (constants.isEmpty()) {
        result = null;
    } else {
        result = Pair.make(variables, Util.getFirst(constants));
    }
    return result;
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.operation.VerticalSpaceExpansion.java

private void shiftSequenceNodes() {

    for (ISequenceNode nodes : Iterables.filter(eventsToShift,
            Predicates.not(Predicates.instanceOf(AbstractNodeEvent.class)))) {
        shift(nodes, expansionSize);/*from  www . j  ava2 s  .  c om*/
    }

    for (AbstractNodeEvent execution : Iterables.filter(eventsToShift, AbstractNodeEvent.class)) {
        Lifeline lep = execution.getLifeline().get();
        Option<Message> cm = lep.getCreationMessage();
        if (cm.some() && isStrictlyBelowInsertionPoint(cm.get())) {
            continue;
        }
        /*
         * Only actually shift the "top-level" executions. The rest will be
         * moved along with their shifted ancestor, as execution position is
         * relative to its parent.
         */

        if (!containsAncestors(eventsToShift, execution)) {
            shift(execution, expansionSize);
        }
    }

    for (AbstractNodeEvent execution : Iterables.filter(eventsToIgnore, AbstractNodeEvent.class)) {
        /*
         * Unshift events to ignore...
         */
        if (eventsToShift.contains(execution.getHierarchicalParentEvent())) {
            shift(execution, -expansionSize);
        }
    }
}

From source file:io.crate.test.integration.CrateTestCluster.java

/**
 * Ensures that at most <code>n</code> are up and running.
 * If less nodes that <code>n</code> are running this method
 * will not start any additional nodes.//from   ww w  .ja  v  a 2  s.  c o  m
 */
public synchronized void ensureAtMostNumNodes(int n) {
    if (nodes.size() <= n) {
        return;
    }
    // prevent killing the master if possible
    final Iterator<NodeAndClient> values = n == 0 ? nodes.values().iterator()
            : Iterators.filter(nodes.values().iterator(),
                    Predicates.not(new MasterNodePredicate(getMasterName())));
    final Iterator<NodeAndClient> limit = Iterators.limit(values, nodes.size() - n);
    logger.info("reducing cluster size from {} to {}", nodes.size() - n, n);
    Set<NodeAndClient> nodesToRemove = new HashSet<NodeAndClient>();
    while (limit.hasNext()) {
        NodeAndClient next = limit.next();
        nodesToRemove.add(next);
        next.close();
    }
    for (NodeAndClient toRemove : nodesToRemove) {
        nodes.remove(toRemove.name);
    }
}

From source file:brooklyn.networking.sdn.SdnProviderImpl.java

@Override
public void provisionNetwork(VirtualNetwork network) {
    // Call provisionNetwork on one of the agents to create it
    SdnAgent agent = (SdnAgent) (getAgents().getMembers().iterator().next());
    String networkId = agent.provisionNetwork(network);

    // Create a DynamicGroup with all attached entities
    EntitySpec<DynamicGroup> networkSpec = EntitySpec.create(DynamicGroup.class)
            .configure(DynamicGroup.ENTITY_FILTER, Predicates.and(
                    Predicates.not(Predicates.or(Predicates.instanceOf(DockerContainer.class),
                            Predicates.instanceOf(DelegateEntity.class))),
                    EntityPredicates.attributeEqualTo(DockerContainer.DOCKER_INFRASTRUCTURE,
                            getAttribute(DOCKER_INFRASTRUCTURE)),
                    SdnAttributes.attachedToNetwork(networkId)))
            .configure(DynamicGroup.MEMBER_DELEGATE_CHILDREN, true).displayName(network.getDisplayName());
    DynamicGroup subnet = getAttribute(SDN_APPLICATIONS).addMemberChild(networkSpec);
    Entities.manage(subnet);/*from  w ww .ja v a2 s. c  om*/
    ((EntityLocal) subnet).setAttribute(VirtualNetwork.NETWORK_ID, networkId);
    ((EntityLocal) network).setAttribute(VirtualNetwork.NETWORKED_APPLICATIONS, subnet);

    getAttribute(SDN_NETWORKS).addMember(network);
}

From source file:org.eclipse.sirius.diagram.sequence.business.internal.query.ISequenceEventQuery.java

private void populateMovedElements(ISequenceEvent inspectedElement, Collection<ISequenceEvent> moved) {
    moved.add(inspectedElement);/*from   w  ww . j  a v  a  2  s.  com*/
    for (ISequenceEvent subEvent : Iterables.filter(inspectedElement.getEventsToMoveWith(),
            Predicates.not(Predicates.in(moved)))) {
        populateMovedElements(subEvent, moved);
    }

}

From source file:brooklyn.networking.cloudstack.legacy.LegacyJcloudsCloudstackSubnetLocation.java

@Override
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(ComputeService computeService,
        NodeMetadata node, String vmHostname1, Optional<HostAndPort> sshHostAndPort, ConfigBag setup)
        throws IOException {
    String subnetSpecificHostname = null;
    String vmHostname = vmHostname1;
    String sshHost = vmHostname;/*from   w  w w  .  j a  v a  2 s. com*/
    Integer sshPort = null;
    PortForwardManager pfw = null;
    String publicIpId = null;

    final String serviceNetworkId = getConfig(CLOUDSTACK_SERVICE_NETWORK_ID);
    boolean portForwardingMode = Strings.isBlank(serviceNetworkId);
    LOG.debug("creating subnet JcloudsSshMachineLocation -- port forwarding={}, node={}",
            new Object[] { node, portForwardingMode });
    if (!portForwardingMode) {
        LOG.debug(
                "Using service network for Brooklyn access - service network ID is {} - searching for NIC connected to this network",
                serviceNetworkId);

        CloudStackApi cloudStackApi = getComputeService().getContext().unwrapApi(CloudStackApi.class);
        VirtualMachineApi vmClient = cloudStackApi.getVirtualMachineApi();
        VirtualMachine vm = vmClient.getVirtualMachine(node.getProviderId());

        Iterable<NIC> allNics = vm.getNICs();
        Predicate<NIC> isServiceNetwork = new Predicate<NIC>() {
            @Override
            public boolean apply(@Nullable NIC input) {
                return input != null && serviceNetworkId.equals(input.getNetworkId());
            }
        };
        Optional<NIC> serviceNic = Iterables.tryFind(allNics, isServiceNetwork);
        Iterable<NIC> otherNics = Iterables.filter(allNics, Predicates.not(isServiceNetwork));

        checkState(serviceNic.isPresent(),
                "unable to identify NIC connected to service network " + serviceNetworkId);
        String ipAddress = serviceNic.get().getIPAddress();
        checkState(Strings.isNonBlank(ipAddress),
                "no IP address on the NIC connected to service network " + serviceNetworkId);

        checkState(!Iterables.isEmpty(otherNics), "VM needs another NIC, in addition to the service network");
        // NIC anotherNic = Iterables.get(otherNics, 0);

        sshHost = ipAddress;
        sshPort = 22;
    } else {
        pfw = getRequiredConfig(PORT_FORWARDING_MANAGER);
        publicIpId = getRequiredConfig(CLOUDSTACK_TIER_PUBLIC_IP_ID);
        Cidr cidr = getConfig(MANAGEMENT_ACCESS_CIDR);

        // others, besides 22!
        int privatePort = 22;
        int publicPort = pfw.acquirePublicPort(publicIpId);

        systemCreatePortForwarding(cidr, publicPort, node, privatePort);

        sshPort = publicPort;
        sshHost = checkNotNull(pfw.getPublicIpHostname(publicIpId), "No ip recorded for id %s", publicIpId);
    }
    LOG.info("Created VM in " + this + " in subnet at " + node + ", ssh accessible via " + sshHost + ":"
            + sshPort);

    // and wait for it to be reachable

    LOG.debug("  waiting for new VM " + node + " in " + this + " to be port reachable on " + sshHost + ":"
            + sshPort);
    boolean isReachable = NetworkMultiAddressUtils2.isAccessible(sshHost, sshPort,
            TimeUnit.MINUTES.toMillis(15));
    if (!isReachable) {
        throw new IllegalStateException("Unable to contact forwarded SSH port for new VM " + node + " in "
                + this + " on " + sshHost + ":" + sshPort);
    }

    if (!NetworkMultiAddressUtils2.isResolveable(vmHostname)) {
        String oldHostname = vmHostname;
        vmHostname = Iterables.getFirst(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()),
                null);
        LOG.info("Renaming unresolvable hostname " + oldHostname + " to " + vmHostname);
    }

    // "public hostname" might be different
    // - sometimes it is not pingable from brooklyn (making sensors hard)
    // - sometimes furthest is the public one, we might want it
    //   (eg if we are in different 10.x subnet - closest not always accessible)
    //   or we might want nearest (if public is not accessible);
    //   and also consider we are on /16 subnet with host, host has another 10.x/8 address, but no public address;
    //   ie furthest might be inaccessible for other reasons
    // TODO i think the "right" way to do this is to have a pluggable "address chooser" ?

    LOG.debug("  vmHostname: " + vmHostname);

    // supply forwarded host and port
    Map<String, Object> sshConfig = extractSshConfig(setup, node);
    sshConfig.put(SshMachineLocation.SSH_HOST.getName(), sshHost);
    if (sshPort != null)
        sshConfig.put(SshMachineLocation.SSH_PORT.getName(), sshPort);

    if (LOG.isDebugEnabled()) {
        LOG.debug(
                "creating JcloudsSshMachineLocation in subnet {}, service network {}, for {}@{} for {} with {}",
                new Object[] { getRequiredConfig(CLOUDSTACK_SUBNET_NETWORK_ID),
                        getConfig(CLOUDSTACK_SERVICE_NETWORK_ID), getUser(setup), vmHostname,
                        setup.getDescription(), Entities.sanitize(sshConfig) });
    }

    final JcloudsSshMachineLocation l = new AbstractJcloudsSubnetSshMachineLocation(
            MutableMap.builder().put("address", Networking.getInetAddressWithFixedName(vmHostname))
                    .put("displayName", vmHostname).put("user", getUser(setup))
                    // don't think "config" does anything
                    .putAll(sshConfig).put("config", sshConfig).put("jcloudsParent", this).put("node", node)
                    .put("port", sshPort).put(CALLER_CONTEXT, setup.get(CALLER_CONTEXT)).build(),
            this, node) {
        @Override
        public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) {
            return getPortForwardingTo(accessor, this, privatePort);
        }
    };
    l.init();
    getManagementContext().getLocationManager().manage(l);

    l.setConfig(SUBNET_HOSTNAME_CONFIG, subnetSpecificHostname);
    l.setConfig(VM_IDENTIFIER, node.getId());

    if (portForwardingMode) {
        // record port 22 forwarding
        pfw.associate(publicIpId, sshPort, l, 22);
    }

    LOG.debug("  waiting for new VM {} in {} to be SSH reachable on {}:{}",
            new Object[] { node, this, sshHost, sshPort });
    final AtomicBoolean isActive = new AtomicBoolean(false);
    Repeater.create().repeat(new Runnable() {
        @Override
        public void run() {
            try {
                int rc = l.execCommands("test accessibility", ImmutableList.of("hostname"));
                isActive.set(rc == 0);
            } catch (Throwable t) {
                isActive.set(false);
            }
        }
    }).every(Duration.FIVE_SECONDS).until(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return isActive.get();
        }
    }).limitTimeTo(Duration.FIVE_MINUTES).run();
    LOG.debug("  waited  for new VM {} in {} to be SSH reachable on {}:{}, result={}",
            new Object[] { node, this, sshHost, sshPort, isActive.get() });

    OperatingSystem operatingSystem = l.getNode().getOperatingSystem();
    if (operatingSystem != null) {
        OsFamily family = operatingSystem.getFamily();
        LOG.info("VM {}: OS family is {}", new Object[] { node, family });
        if (family != OsFamily.WINDOWS && family != OsFamily.UNRECOGNIZED) {
            LOG.warn("VM {}: disabling iptables", new Object[] { node });
            l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                    Arrays.asList(BashCommands.dontRequireTtyForSudo()));
            l.execScript("disabling iptables",
                    Arrays.asList("sudo /etc/init.d/iptables stop", "sudo chkconfig iptables off"));
        } else {
            LOG.warn("VM {}: NOT disabling iptables because OS family is {}", new Object[] { node, family });
        }
    } else {
        LOG.warn("VM {}: NOT disabling iptables because OS is not detected", new Object[] { node });
    }

    String setupScript = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_URL);
    if (Strings.isNonBlank(setupScript)) {
        String setupVarsString = setup.get(JcloudsLocationConfig.CUSTOM_MACHINE_SETUP_SCRIPT_VARS);
        Map<String, String> substitutions = (setupVarsString != null)
                ? Splitter.on(",").withKeyValueSeparator(":").split(setupVarsString)
                : ImmutableMap.<String, String>of();
        String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScript);
        String script = TemplateProcessor.processTemplateContents(scriptContent, substitutions);
        l.execScript(MutableMap.of(SshTool.PROP_ALLOCATE_PTY.getName(), true), "disabling requiretty",
                Arrays.asList(BashCommands.dontRequireTtyForSudo()));
        l.execCommands("Customizing node " + this, ImmutableList.of(script));
    }

    return l;
}