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:org.eclipse.sirius.diagram.ui.tools.internal.outline.QuickOutlineControl.java

/**
 * Creates the outline's tree viewer./*  w  ww. j  a v  a 2  s .c o m*/
 * 
 * @param parent
 *            parent composite.
 */
protected void createTreeViewer(Composite parent) {
    filteredTree = new FilteredTree(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL, new PatternFilter(),
            true);
    treeViewer = filteredTree.getViewer();
    final Tree tree = treeViewer.getTree();

    tree.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent event) {
            if (event.character == SWT.ESC) {
                dispose();
            }
            if (event.keyCode == 0x0D) {
                gotoSelectedElement();
            }
            if (event.keyCode == SWT.ARROW_DOWN) {
                tree.setFocus();
            }
            if (event.keyCode == SWT.ARROW_UP) {
                tree.setFocus();
            }
            if (event.character == 0x1B) {
                dispose();
            }
        }
    });

    tree.addSelectionListener(new SelectionListener() {
        public void widgetSelected(SelectionEvent e) {
            // do nothing
        }

        public void widgetDefaultSelected(SelectionEvent e) {
            gotoSelectedElement();
        }
    });

    treeViewer.setContentProvider(new FilteredTreeContentProvider(getAdapterFactory(),
            Predicates.or(Predicates.instanceOf(DDiagramElement.class),
                    Predicates.instanceOf(AbstractDDiagramElementLabelItemProvider.class))));
    treeViewer.setLabelProvider(new OutlineLabelProvider());

    // We want to remove everything that's not "top level elements" from the
    // outline view
    treeViewer.addFilter(new ViewerFilter() {

        /**
         * {@inheritDoc}
         * 
         * @see org.eclipse.jface.viewers.ViewerFilter#select(org.eclipse.jface.viewers.Viewer,
         *      java.lang.Object, java.lang.Object)
         */
        @Override
        public boolean select(Viewer viewer, Object parentElement, Object element) {
            return element instanceof DDiagramElement;
        }
    });
}

From source file:org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer.EMFCompareStructureMergeViewerContentProvider.java

/**
 * {@inheritDoc}/*  w w  w .  ja  v  a 2  s .c o  m*/
 * 
 * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider#getChildren(java.lang.Object)
 */
@Override
public final Object[] getChildren(Object element) {
    Object[] children;
    if (element instanceof CompareInputAdapter) {
        children = getCompareInputAdapterChildren((CompareInputAdapter) element);
    } else if (element instanceof ICompareInput) {
        children = new Object[] {};
    } else {
        children = super.getChildren(element);
    }

    final Object[] compareInputChildren;
    // Avoid NPE.
    if (children == null) {
        children = new Object[] {};
    }
    // Do not adapt if it's a pending updater
    if (!Iterables.all(Arrays.asList(children), Predicates.instanceOf(PendingUpdateAdapter.class))) {
        Iterable<?> compareInputs = adapt(children, getAdapterFactory(), ICompareInput.class);
        compareInputChildren = toArray(compareInputs, Object.class);
    } else {
        compareInputChildren = children;
    }
    return compareInputChildren;
}

From source file:org.sosy_lab.cpachecker.cpa.value.refiner.ValueAnalysisRefiner.java

protected final PredicatePrecision extractPredicatePrecision(final ARGReachedSet pReached, ARGState state) {
    return (PredicatePrecision) Precisions.asIterable(pReached.asReachedSet().getPrecision(state))
            .filter(Predicates.instanceOf(PredicatePrecision.class)).get(0);
}

From source file:com.eucalyptus.util.Exceptions.java

@SuppressWarnings("unchecked")
public static <T extends Throwable> T findCause(Throwable ex, final Class<T> class1) {
    try {/*from  w  w w . ja v  a 2  s.co  m*/
        return (T) Iterables.find(Exceptions.causes(ex), Predicates.instanceOf(class1));
    } catch (NoSuchElementException ex1) {
        return null;
    }
}

From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java

@Override
protected void preStart() {
    final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER);
    final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR);
    final Integer groupId = getConfig(GROUP_ID);
    final Integer templateId = getConfig(TEMPLATE_ID);
    final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS);

    log.info("starting zabbix feed for {}", entity);

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    // TODO for https should we really trust all?
    final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll()
            .clientConnectionManager(new ThreadSafeClientConnManager())
            .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build();

    // Registration job, calls Zabbix host.create API
    final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() {
        @Override//w w w . j a v  a 2s  .c o  m
        public HttpToolResponse call() throws Exception {
            if (!registered.get()) {
                // Find the first machine, if available
                Optional<Location> location = Iterables.tryFind(entity.getLocations(),
                        Predicates.instanceOf(MachineLocation.class));
                if (!location.isPresent()) {
                    return null; // Do nothing until location is present
                }
                MachineLocation machine = (MachineLocation) location.get();

                String host = uniqueHostnameGenerator.apply(entity);

                // Select address and port using port-forwarding if available
                String address = entity.getAttribute(Attributes.ADDRESS);
                Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT);
                if (machine instanceof SupportsPortForwarding) {
                    Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR);
                    HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management,
                            port);
                    address = forwarded.getHostText();
                    port = forwarded.getPort();
                }

                // Fill in the JSON template and POST it
                byte[] body = JSON_HOST_CREATE
                        .replace("{{token}}",
                                entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                        .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                        .replace("{{host}}", host).replace("{{ip}}", address)
                        .replace("{{port}}", Integer.toString(port))
                        .replace("{{groupId}}", Integer.toString(groupId))
                        .replace("{{templateId}}", Integer.toString(templateId))
                        .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                        ImmutableMap.of("Content-Type", "application/json"), body);
            }
            return null;
        }
    };

    // The handler for the registration job
    PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() {
        @Override
        public void onSuccess(HttpToolResponse val) {
            if (registered.get() || val == null) {
                return; // Skip if we are registered already or no data from job
            }
            JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject();
            if (response.has("error")) {
                // Parse the JSON error object and log the message
                JsonObject error = response.get("error").getAsJsonObject();
                String message = error.get("message").getAsString();
                String data = error.get("data").getAsString();
                log.warn("zabbix failed registering host - {}: {}", message, data);
            } else if (response.has("result")) {
                // Parse the JSON result object and save the hostId
                JsonObject result = response.get("result").getAsJsonObject();
                String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString();
                // Update the registered status if not set
                if (registered.compareAndSet(false, true)) {
                    entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId);
                    log.info("zabbix registered host as id {}", hostId);
                }
            } else {
                throw new IllegalStateException(String
                        .format("zabbix host registration returned invalid result: %s", response.toString()));
            }
        }

        @Override
        public boolean checkSuccess(HttpToolResponse val) {
            return (val.getResponseCode() == 200);
        }

        @Override
        public void onFailure(HttpToolResponse val) {
            log.warn("zabbix sever returned failure code: {}", val.getResponseCode());
        }

        @Override
        public void onException(Exception exception) {
            log.warn("zabbix exception registering host", exception);
        }

        @Override
        public String toString() {
            return super.toString() + "[" + getDescription() + "]";
        }

        @Override
        public String getDescription() {
            return "Zabbix rest poll";
        }
    };

    // Schedule registration attempt once per second
    getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable

    // Create a polling job for each Zabbix metric
    for (final ZabbixPollConfig<?> config : polls) {
        Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() {
            @Override
            public HttpToolResponse call() throws Exception {
                if (registered.get()) {
                    if (log.isTraceEnabled())
                        log.trace("zabbix polling {} for {}", entity, config);
                    byte[] body = JSON_ITEM_GET
                            .replace("{{token}}",
                                    entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                            .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                            .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID))
                            .replace("{{itemKey}}", config.getItemKey())
                            .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                    return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                            ImmutableMap.of("Content-Type", "application/json"), body);
                } else {
                    throw new IllegalStateException("zabbix agent not yet registered");
                }
            }
        };

        // Schedule the Zabbix polling job
        AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>(
                config, entity, this);
        long minPeriod = Integer.MAX_VALUE; // TODO make configurable
        if (config.getPeriod() > 0)
            minPeriod = Math.min(minPeriod, config.getPeriod());
        getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod);
    }

}

From source file:org.eclipse.sirius.diagram.business.api.query.DDiagramElementQuery.java

/**
 * Tests whether the dDiagramElement is explicitly folded, i.e. it is a
 * folding point.//  w  w  w.jav  a  2s.  com
 * 
 * @return <code>true</code> if the dDiagramElement is explicitly folded.
 */
public boolean isExplicitlyFolded() {
    return Iterables.any(element.getGraphicalFilters(), Predicates.instanceOf(FoldingPointFilter.class));
}

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

private Map<ISequenceEvent, Range> computePunctualEventsGraphicalRanges(Map<EventEnd, Integer> endLocations,
        boolean pack) {
    final Map<ISequenceEvent, Range> sequenceEventsToRange = new LinkedHashMap<ISequenceEvent, Range>();
    if (pack) {//from w  w  w . ja  v  a  2  s .co  m
        for (EventEnd cee : Iterables.filter(semanticOrdering, EventEndHelper.PUNCTUAL_COMPOUND_EVENT_END)) {
            if (endLocations.containsKey(cee) && endToISequencEvents.containsKey(cee)) {
                int loc = endLocations.get(cee);
                Collection<ISequenceEvent> ises = endToISequencEvents.get(cee);

                if (Iterables.any(ises, Predicates.instanceOf(State.class)) && ises.size() == 1) {
                    State ise = (State) ises.iterator().next();
                    int midSize = getAbstractNodeEventVerticalSize(cee, ise, ises, pack) / 2;
                    sequenceEventsToRange.put(ise, new Range(loc - midSize, loc + midSize));
                }
            }
        }
    }
    return sequenceEventsToRange;
}

From source file:org.apache.brooklyn.entity.monitoring.zabbix.ZabbixFeed.java

@Override
protected void preStart() {
    final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER);
    final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR);
    final Integer groupId = getConfig(GROUP_ID);
    final Integer templateId = getConfig(TEMPLATE_ID);
    final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS);

    log.info("starting zabbix feed for {}", entity);

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    // TODO for https should we really trust all?
    final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll()
            .clientConnectionManager(new ThreadSafeClientConnManager())
            .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build();

    // Registration job, calls Zabbix host.create API
    final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() {
        @Override/*w w  w.  ja v  a  2 s.  co  m*/
        public HttpToolResponse call() throws Exception {
            if (!registered.get()) {
                // Find the first machine, if available
                Optional<Location> location = Iterables.tryFind(entity.getLocations(),
                        Predicates.instanceOf(MachineLocation.class));
                if (!location.isPresent()) {
                    return null; // Do nothing until location is present
                }
                MachineLocation machine = (MachineLocation) location.get();

                String host = uniqueHostnameGenerator.apply(entity);

                // Select address and port using port-forwarding if available
                String address = entity.getAttribute(Attributes.ADDRESS);
                Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT);
                if (machine instanceof SupportsPortForwarding) {
                    Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR);
                    HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management,
                            port);
                    address = forwarded.getHostText();
                    port = forwarded.getPort();
                }

                // Fill in the JSON template and POST it
                byte[] body = JSON_HOST_CREATE
                        .replace("{{token}}",
                                entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                        .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                        .replace("{{host}}", host).replace("{{ip}}", address)
                        .replace("{{port}}", Integer.toString(port))
                        .replace("{{groupId}}", Integer.toString(groupId))
                        .replace("{{templateId}}", Integer.toString(templateId))
                        .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                        ImmutableMap.of("Content-Type", "application/json"), body);
            }
            return null;
        }
    };

    // The handler for the registration job
    PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() {
        @Override
        public void onSuccess(HttpToolResponse val) {
            if (registered.get() || val == null) {
                return; // Skip if we are registered already or no data from job
            }
            JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject();
            if (response.has("error")) {
                // Parse the JSON error object and log the message
                JsonObject error = response.get("error").getAsJsonObject();
                String message = error.get("message").getAsString();
                String data = error.get("data").getAsString();
                log.warn("zabbix failed registering host - {}: {}", message, data);
            } else if (response.has("result")) {
                // Parse the JSON result object and save the hostId
                JsonObject result = response.get("result").getAsJsonObject();
                String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString();
                // Update the registered status if not set
                if (registered.compareAndSet(false, true)) {
                    entity.sensors().set(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId);
                    log.info("zabbix registered host as id {}", hostId);
                }
            } else {
                throw new IllegalStateException(String
                        .format("zabbix host registration returned invalid result: %s", response.toString()));
            }
        }

        @Override
        public boolean checkSuccess(HttpToolResponse val) {
            return (val.getResponseCode() == 200);
        }

        @Override
        public void onFailure(HttpToolResponse val) {
            log.warn("zabbix sever returned failure code: {}", val.getResponseCode());
        }

        @Override
        public void onException(Exception exception) {
            log.warn("zabbix exception registering host", exception);
        }

        @Override
        public String toString() {
            return super.toString() + "[" + getDescription() + "]";
        }

        @Override
        public String getDescription() {
            return "Zabbix rest poll";
        }
    };

    // Schedule registration attempt once per second
    getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable

    // Create a polling job for each Zabbix metric
    for (final ZabbixPollConfig<?> config : polls) {
        Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() {
            @Override
            public HttpToolResponse call() throws Exception {
                if (registered.get()) {
                    if (log.isTraceEnabled())
                        log.trace("zabbix polling {} for {}", entity, config);
                    byte[] body = JSON_ITEM_GET
                            .replace("{{token}}",
                                    entity.getConfig(ZabbixMonitored.ZABBIX_SERVER)
                                            .getAttribute(ZabbixServer.ZABBIX_TOKEN))
                            .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID))
                            .replace("{{itemKey}}", config.getItemKey())
                            .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes();

                    return HttpTool.httpPost(httpClient, baseUriProvider.get(),
                            ImmutableMap.of("Content-Type", "application/json"), body);
                } else {
                    throw new IllegalStateException("zabbix agent not yet registered");
                }
            }
        };

        // Schedule the Zabbix polling job
        AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>(
                config, entity, this);
        long minPeriod = Integer.MAX_VALUE; // TODO make configurable
        if (config.getPeriod() > 0)
            minPeriod = Math.min(minPeriod, config.getPeriod());
        getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod);
    }

}

From source file:info.magnolia.ui.form.field.MultiField.java

/**
 * Takes care of moving a field up or down. Tries hard not to assume much about the layout, so we're iterating over parents
 * and component types to make sure we're dealing with Fields.
 *///from   w w w  .  ja va 2 s.c om
private void onMove(Component layout, Property<?> propertyReference, boolean moveUp) {
    int currentPosition = root.getComponentIndex(layout);
    int switchPosition = currentPosition + (moveUp ? -1 : 1);

    Field[] fields = Iterators
            .toArray(Iterators.filter(Iterators.transform(root.iterator(), new Function<Component, Field>() {
                @Nullable
                @Override
                public Field apply(Component input) {
                    if (input instanceof HasComponents) {
                        Optional<Component> field = Iterators.tryFind(((HasComponents) input).iterator(),
                                Predicates.instanceOf(Field.class));
                        if (field.isPresent()) {
                            return (Field) field.get();
                        }
                    }
                    return null;
                }
            }), Predicates.notNull()), Field.class);

    if (moveUp && currentPosition != 0 || (!moveUp && currentPosition != fields.length - 1)) {

        Field switchField = fields[switchPosition];
        Object currentPropertyId = MultiField.this.findPropertyId(getValue(), propertyReference);
        Object switchPropertyId = MultiField.this.findPropertyId(getValue(),
                switchField.getPropertyDataSource());

        root.replaceComponent(root.getComponent(currentPosition), root.getComponent(switchPosition));
        switchItemProperties(currentPropertyId, switchPropertyId);
    }
}

From source file:org.eclipse.sirius.diagram.business.api.query.DDiagramElementQuery.java

/**
 * Tests whether the dDiagramElement is indirectly folded because it is
 * accessible from another edge which was explicitly folded.
 * //from w  ww  .j  a va2  s .co m
 * @return <code>true</code> if the dDiagramElement is explicitly folded.
 */
public boolean isIndirectlyFolded() {
    return Iterables.any(element.getGraphicalFilters(), Predicates.instanceOf(FoldingFilter.class));
}