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

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

Introduction

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

Prototype

@GwtIncompatible("Class.isInstance")
public static Predicate<Object> instanceOf(Class<?> clazz) 

Source Link

Document

Returns a predicate that evaluates to true if the object being tested is an instance of the given class.

Usage

From source file:clocker.docker.location.DockerLocation.java

@Override
public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
    // Check context for entity being deployed
    Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName());
    if (context != null && !(context instanceof Entity)) {
        throw new IllegalStateException("Invalid location context: " + context);
    }// ww w.  j a v a2  s.  com
    Entity entity = (Entity) context;

    // Get the available hosts
    List<DockerHostLocation> available = getDockerHostLocations();
    LOG.debug("Placement for: {}", Iterables.toString(Iterables.transform(available, EntityFunctions.id())));

    // Apply placement strategies
    List<DockerAwarePlacementStrategy> entityStrategies = entity.config()
            .get(DockerAttributes.PLACEMENT_STRATEGIES);
    if (entityStrategies == null)
        entityStrategies = ImmutableList.of();
    for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) {
        available = strategy.filterLocations(available, entity);
        LOG.debug("Placement after {}: {}", strategy,
                Iterables.toString(Iterables.transform(available, EntityFunctions.id())));
    }

    // Use the provisioning strategy to add a new host
    DockerHostLocation machine = null;
    DockerHost dockerHost = null;
    if (available.size() > 0) {
        machine = available.get(0);
        dockerHost = machine.getOwner();
    } else {
        // Get permission to create a new Docker host
        if (permit.tryAcquire()) {
            try {
                // Determine if headroom scaling policy is being used and suspend
                Integer headroom = getOwner().config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM);
                Double headroomPercent = getOwner().config()
                        .get(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE);
                boolean headroomSet = (headroom != null && headroom > 0)
                        || (headroomPercent != null && headroomPercent > 0d);
                Optional<Policy> policy = Iterables.tryFind(getOwner().getDockerHostCluster().policies(),
                        Predicates.instanceOf(AutoScalerPolicy.class));
                if (headroomSet && policy.isPresent())
                    policy.get().suspend();

                try {
                    // Resize the host cluster
                    LOG.info("Provisioning new host");
                    Entity added = Iterables.getOnlyElement(getOwner().getDockerHostCluster().resizeByDelta(1));
                    dockerHost = (DockerHost) added;
                    machine = dockerHost.getDynamicLocation();

                    // Update autoscaler policy with new minimum size and resume
                    if (headroomSet && policy.isPresent()) {
                        int currentMin = policy.get().config().get(AutoScalerPolicy.MIN_POOL_SIZE);
                        LOG.info("Updating autoscaler policy ({}) setting {} to {}", new Object[] {
                                policy.get(), AutoScalerPolicy.MIN_POOL_SIZE.getName(), currentMin + 1 });
                        policy.get().config().set(AutoScalerPolicy.MIN_POOL_SIZE, currentMin + 1);
                    }
                } finally {
                    if (policy.isPresent())
                        policy.get().resume();
                }
            } finally {
                permit.release();
            }
        } else {
            // Wait until whoever has the permit releases it, and try again
            try {
                permit.acquire();
            } catch (InterruptedException ie) {
                Exceptions.propagate(ie);
            } finally {
                permit.release();
            }
            return obtain(flags);
        }
    }

    // Now wait until the host has started up
    Entities.waitForServiceUp(dockerHost);

    // Obtain a new Docker container location, save and return it
    try {
        LOG.debug("Obtain a new container from {} for {}", machine, entity);
        Map<?, ?> hostFlags = MutableMap.copyOf(flags);
        DockerContainerLocation container = machine.obtain(hostFlags);
        containers.put(machine, container.getId());
        return container;
    } finally {
        // Release any placement strategy locks
        for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) {
            if (strategy instanceof WithMutexes) {
                ((WithMutexes) strategy).releaseMutex(entity.getApplicationId());
            }
        }
    }
}

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

private List<EventEnd> getCompoundEnds(ISequenceEvent eventToUpdate, List<EventEnd> ends) {
    List<ISequenceEvent> compoundEvents = EventEndHelper.getCompoundEvents(eventToUpdate);
    Predicate<ISequenceEvent> isLogicallyInstantaneousNonReorderedEvent = new Predicate<ISequenceEvent>() {
        @Override/*from   w  w w.ja  va 2  s  .  c  om*/
        public boolean apply(ISequenceEvent input) {
            return input.isLogicallyInstantaneous() && !reordered.contains(input);
        };
    };
    Iterable<ISequenceEvent> compoundEventsToReorder = Iterables.filter(compoundEvents,
            isLogicallyInstantaneousNonReorderedEvent);
    Iterable<EventEnd> nonReorderedEndsOfCompoundEvents = Iterables
            .concat(Iterables.transform(compoundEventsToReorder, EventEndHelper.EVENT_ENDS));
    Predicate<EventEnd> isCompoundEnd = Predicates.and(Predicates.instanceOf(SingleEventEnd.class),
            Predicates.not(Predicates.in(ends)));

    return Lists.newArrayList(Iterables.filter(nonReorderedEndsOfCompoundEvents, isCompoundEnd));
}

From source file:org.eclipse.sirius.diagram.ui.business.api.helper.graphicalfilters.CollapseUpdater.java

/**
 * Remove filter of <code>element</code> and update (if needed) the bounds
 * of the GMF Node.//www  . j av a 2 s .  c om
 * 
 * @param element
 *            The @link {@link DDiagramElement} to synchronized.
 * @param optionalNode
 *            The optional {@link Node} to synchronized. The GMF bounds are
 *            not update if there is no node (it is the case during the
 *            repair process).
 * @param kindOfFilter
 *            the kind of filter to add or remove ( {@link CollapseFilter}
 *            or {@link IndirectlyCollapseFilter}
 */
protected void removeGraphicalFilter(DDiagramElement element, Option<Node> optionalNode,
        Class<? extends CollapseFilter> kindOfFilter) {
    // Compute the expanded Bounds that will be used at the end if the node
    // is no more collapsed. This expanded bounds is computed now because
    // after removing all graphical filters is too late.
    Option<Bounds> optionalExpandedBounds;
    if (optionalNode.some()) {
        optionalExpandedBounds = getExpandedBounds(optionalNode.get(), element);
    } else {
        optionalExpandedBounds = Options.newNone();

    }
    if (kindOfFilter.equals(CollapseFilter.class)) {
        // Iterate on all CollapseFilter that are not
        // IndirectlyCollapseFilter
        for (CollapseFilter collapseApplication : Lists.newArrayList(
                Iterables.filter(Iterables.filter(element.getGraphicalFilters(), CollapseFilter.class),
                        Predicates.not(Predicates.instanceOf(IndirectlyCollapseFilter.class))))) {
            element.getGraphicalFilters().remove(collapseApplication);
        }
        removeFromChildrenIndirectlyCollapsedFilter(element);
    } else if (kindOfFilter.equals(IndirectlyCollapseFilter.class)) {
        for (IndirectlyCollapseFilter collapseApplication : Lists.newArrayList(
                Iterables.filter(element.getGraphicalFilters(), IndirectlyCollapseFilter.class))) {
            element.getGraphicalFilters().remove(collapseApplication);
        }
    }

    if (optionalNode.some()) {
        NodeQuery nodeQuery = new NodeQuery(optionalNode.get());
        // if the node have no more collapse filter after having remove the
        // last one, we expand it (if it's a bordered node only)
        if (!nodeQuery.isCollapsed() && nodeQuery.isBorderedNode()) {
            if (optionalExpandedBounds.some()) {
                optionalNode.get().setLayoutConstraint(optionalExpandedBounds.get());
            }
        }
    }
}

From source file:org.eclipse.sirius.diagram.ui.graphical.edit.policies.MoveEdgeGroupManager.java

/**
 * Determines if the given request is a valid request for this tool.<br/>
 * Each selected edge should respect the following rules:
 * <ul>//  ww w  . j av a2  s  .co  m
 * <li>a border node as source</li>
 * <li>a border node as target</li>
 * <li>source node has only one connection: the moved edge.</li>
 * <li>target node has only one connection: the moved edge.</li>
 * <li>Both border nodes are on the same axe (Horizontal or Vertical)</li>
 * </ul>
 * <br/>
 * Furthermore, every selected edge group should be in the same direction
 * and only edges should be selected.
 * 
 * @return true if the moved edges and border nodes can be activated,
 *         otherwise false.
 */
@SuppressWarnings("unchecked")
private boolean accept() {
    if (request instanceof BendpointRequest) {
        ConnectionEditPart connectionEditPart = ((BendpointRequest) request).getSource();
        // The selected diagram element should only contain edges otherwise
        // the move is not valid
        final Set<Integer> edgeDirections = Sets.newLinkedHashSet();
        boolean result = Iterables.all(connectionEditPart.getViewer().getSelectedEditParts(), Predicates
                .and(Predicates.instanceOf(ConnectionEditPart.class), new Predicate<ConnectionEditPart>() {
                    /**
                     * Determines if the given edge respects the following rules:
                     * <ul>
                     * <li>a border node as source</li>
                     * <li>a border node as target</li>
                     * <li>source node has only one connection: the moved edge.</li>
                     * <li>target node has only one connection: the moved edge.</li>
                     * <li>Both border nodes are on the same axe (Horizontal or
                     * Vertical)</li>
                     * </ul>
                     */
                    @Override
                    public boolean apply(ConnectionEditPart input) {
                        EditPart sourceEditPart = input.getSource();
                        EditPart targetEditPart = input.getTarget();

                        if (sourceEditPart instanceof AbstractDiagramBorderNodeEditPart
                                && targetEditPart instanceof AbstractDiagramBorderNodeEditPart) {
                            if (getAllConnections((AbstractDiagramBorderNodeEditPart) sourceEditPart)
                                    .size() == 1
                                    && getAllConnections((AbstractDiagramBorderNodeEditPart) targetEditPart)
                                            .size() == 1) {
                                int sourceDirection = getBorderNodeDirection(
                                        (AbstractDiagramBorderNodeEditPart) sourceEditPart);
                                int targetDirection = getBorderNodeDirection(
                                        (AbstractDiagramBorderNodeEditPart) targetEditPart);
                                if (sourceDirection == targetDirection) {
                                    direction = sourceDirection;
                                    edgeDirections.add(sourceDirection);
                                    return true;
                                }
                            }
                        }
                        return false;
                    }
                }));
        // There should be only one kind of direction for every edges to
        // authorize the move
        return result && edgeDirections.size() == 1;
    }
    return false;
}

From source file:com.cloudera.impala.analysis.InlineViewRef.java

protected void makeOutputNullableHelper(Analyzer analyzer, ExprSubstitutionMap smap) throws InternalException {
    // Gather all unique rhs SlotRefs into rhsSlotRefs
    List<SlotRef> rhsSlotRefs = Lists.newArrayList();
    TreeNode.collect(smap.getRhs(), Predicates.instanceOf(SlotRef.class), rhsSlotRefs);
    // Map for substituting SlotRefs with NullLiterals.
    ExprSubstitutionMap nullSMap = new ExprSubstitutionMap();
    for (SlotRef rhsSlotRef : rhsSlotRefs) {
        // The rhs null literal should have the same type as the lhs SlotRef to ensure
        // exprs resolve to the same signature after applying this smap.
        nullSMap.put(rhsSlotRef.clone(), NullLiteral.create(rhsSlotRef.getType()));
    }// ww w.ja  v  a 2  s .c  o m

    // Make rhs exprs nullable if necessary.
    for (int i = 0; i < smap.getRhs().size(); ++i) {
        List<Expr> params = Lists.newArrayList();
        if (!requiresNullWrapping(analyzer, smap.getRhs().get(i), nullSMap))
            continue;
        params.add(new TupleIsNullPredicate(materializedTupleIds_));
        params.add(new NullLiteral());
        params.add(smap.getRhs().get(i));
        Expr ifExpr = new FunctionCallExpr("if", params);
        ifExpr.analyzeNoThrow(analyzer);
        smap.getRhs().set(i, ifExpr);
    }
}

From source file:org.obeonetwork.m2doc.ui.dialog.VariableEditDialog.java

/**
 * Create contents of the dialog.//from  w  ww  . java2  s.c om
 * 
 * @param parent
 */
@Override
protected Control createDialogArea(Composite parent) {
    setTitle("Configure Variable");
    setMessage("Configure the variable name and type.");
    Composite area = (Composite) super.createDialogArea(parent);
    Composite container = new Composite(area, SWT.NONE);
    container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
    container.setLayout(new GridLayout(2, false));

    Label lblVariableName = new Label(container, SWT.NONE);
    lblVariableName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblVariableName.setText("TemplateVariable Name:");

    txtName = new Text(container, SWT.BORDER);
    txtName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    Label lblMetamodel = new Label(container, SWT.NONE);
    lblMetamodel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblMetamodel.setText("Meta-Model:");

    Composite composite = new Composite(container, SWT.NONE);
    composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1));
    GridLayout gl_composite = new GridLayout(2, false);
    gl_composite.verticalSpacing = 0;
    gl_composite.marginHeight = 0;
    gl_composite.marginWidth = 0;
    gl_composite.horizontalSpacing = 0;
    composite.setLayout(gl_composite);

    Combo combo = new Combo(composite, SWT.NONE);
    combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
    mmComboViewer = new ComboViewer(combo);
    mmComboViewer.setContentProvider(new IStructuredContentProvider() {
        @Override
        public Object[] getElements(Object inputElement) {
            @SuppressWarnings("unchecked")
            Map<String, EPackageMapping> map = (Map<String, EPackageMapping>) inputElement;
            List<Object> result = new ArrayList<>();
            result.add(config);
            result.addAll(map.values());
            return result.toArray(new Object[result.size()]);
        }

        @Override
        public void dispose() {
            // Nothing
        }

        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            // Nothing
        }
    });
    mmComboViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
    for (EPackageMapping mapping : config.getMappings()) {
        if (mapping.getUri() != null && mapping.getName() != null) {
            mappingsByUri.put(mapping.getUri(), mapping);
        }
    }
    mmComboViewer.setInput(mappingsByUri);

    Button btnAddMetamodel = new Button(composite, SWT.NONE);
    btnAddMetamodel.setText("...");
    btnAddMetamodel.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            RegisteredPackageDialog dialog = new RegisteredPackageDialog(Display.getCurrent().getActiveShell());
            dialog.setMultipleSelection(false);
            dialog.open();
            if (dialog.getReturnCode() == Dialog.OK) {
                Object firstResult = dialog.getFirstResult();
                if (firstResult instanceof String) {
                    String uri = (String) firstResult;
                    if (mappingsByUri.containsKey(uri)) {
                        // Reuse the one that's already registered
                        mmComboViewer.setSelection(new StructuredSelection(mappingsByUri.get(uri)), true);
                    } else {
                        final EPackage ePackage = EPackage.Registry.INSTANCE.getEPackage(uri);
                        if (ePackage != null) {
                            EPackageMapping newMapping = TplconfFactory.eINSTANCE.createEPackageMapping();
                            newMapping.setName(ePackage.getName());
                            newMapping.setUri(ePackage.getNsURI());
                            newMapping.setEPackage(ePackage);
                            mappingsByUri.put(uri, newMapping);
                            mmComboViewer.refresh();
                            mmComboViewer.setSelection(new StructuredSelection(newMapping), true);
                        }
                    }
                }
            }
        }
    });

    Label lblType = new Label(container, SWT.NONE);
    lblType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblType.setText("TemplateType:");

    PatternFilter filter = new PatternFilter();
    filteredTree = new FilteredTree(container, SWT.BORDER | SWT.SINGLE, filter, true);
    classifierTreeViewer = filteredTree.getViewer();

    Label lblTypeName = new Label(container, SWT.NONE);
    lblTypeName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
    lblTypeName.setText("TemplateType Name:");

    txtTypeName = new Text(container, SWT.BORDER);
    txtTypeName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));

    classifierTreeViewer.setContentProvider(new ITreeContentProvider() {

        @Override
        public boolean hasChildren(Object element) {
            return false;
        }

        @Override
        public Object getParent(Object element) {
            return null;
        }

        @Override
        public Object[] getElements(Object inputElement) {
            if (inputElement instanceof EPackageMapping) {
                EPackageMapping mm = ((EPackageMapping) inputElement);
                if (mm.getEPackage() instanceof EPackage) {
                    EList<EClassifier> eClassifiers = ((EPackage) mm.getEPackage()).getEClassifiers();
                    return eClassifiers.toArray(new Object[eClassifiers.size()]);
                }
            } else if (inputElement instanceof TemplateConfig) {
                Collection<TemplateType> allTypes = ((TemplateConfig) inputElement).getTypesByName().values();
                return Collections2.filter(allTypes, Predicates.instanceOf(ScalarType.class)).toArray();
            }
            return new Object[0];
        }

        @Override
        public Object[] getChildren(Object parentElement) {
            return null;
        }

        @Override
        public void dispose() {
            // Nothing
        }

        @Override
        public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            // Nothing
        }
    });
    classifierTreeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));

    // Set initial values
    txtName.setText(variable.getName());
    if (variable.getTypeName() != null) {
        txtTypeName.setText(variable.getTypeName());
    }
    TemplateType type = variable.getType();
    if (type instanceof ScalarType) {
        mmComboViewer.setSelection(new StructuredSelection(config), true);
        classifierTreeViewer.setSelection(new StructuredSelection(variable.getType()), true);
    } else if (type instanceof StructuredType) {
        if (((StructuredType) variable.getType()).getMapping() != null) {
            mmComboViewer.setSelection(
                    new StructuredSelection(((StructuredType) variable.getType()).getMapping()), true);
        }
        if (((StructuredType) variable.getType()).getEClassifier() != null) {
            classifierTreeViewer.setSelection(
                    new StructuredSelection(((StructuredType) variable.getType()).getEClassifier()), true);
        }
    }

    hookListeners();

    return container;
}

From source file:org.obeonetwork.dsl.sysml.design.tests.plugin.manual.ServiceTestsUtils.java

private static List<String> getAllSysmlOperations() {
    // Obtain a new resource set
    ResourceSet resSet = new ResourceSetImpl();

    // Create a resource
    Resource res = resSet.getResource(URI.createURI("http://www.eclipse.org/papyrus/0.7.0/SysML"), true);
    EObject root = res.getContents().get(0);

    // Get all eOperations
    List<EObject> sysmlOperations = Lists.newArrayList();
    Iterators.addAll(sysmlOperations,/* ww  w.  j  ava  2 s  . c o  m*/
            Iterators.filter(root.eAllContents(), Predicates.instanceOf(EOperation.class)));

    // Get eOperation names
    List<String> result = Lists.newArrayList();
    for (EObject sysmlOperation : sysmlOperations) {
        result.add(((EOperation) sysmlOperation).getName());
    }
    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  w ww.  jav  a  2 s .c  o  m
    }

    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:com.cloudera.impala.analysis.Expr.java

protected void computeNumDistinctValues() {
    if (isConstant()) {
        numDistinctValues_ = 1;//from   w  w  w .j  a  va  2 s. c  om
    } else {
        // if this Expr contains slotrefs, we estimate the # of distinct values
        // to be the maximum such number for any of the slotrefs;
        // the subclass analyze() function may well want to override this, if it
        // knows better
        List<SlotRef> slotRefs = Lists.newArrayList();
        this.collect(Predicates.instanceOf(SlotRef.class), slotRefs);
        numDistinctValues_ = -1;
        for (SlotRef slotRef : slotRefs) {
            numDistinctValues_ = Math.max(numDistinctValues_, slotRef.numDistinctValues_);
        }
    }
}

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   ww w  . ja v  a2s . co m*/
    ((EntityLocal) subnet).setAttribute(VirtualNetwork.NETWORK_ID, networkId);
    ((EntityLocal) network).setAttribute(VirtualNetwork.NETWORKED_APPLICATIONS, subnet);

    getAttribute(SDN_NETWORKS).addMember(network);
}