Example usage for java.lang Class isInstance

List of usage examples for java.lang Class isInstance

Introduction

In this page you can find the example usage for java.lang Class isInstance.

Prototype

@HotSpotIntrinsicCandidate
public native boolean isInstance(Object obj);

Source Link

Document

Determines if the specified Object is assignment-compatible with the object represented by this Class .

Usage

From source file:com.mgmtp.jfunk.web.util.WebElementFinder.java

/**
 * Finds all elements.//from  w w w . j  av a  2 s  .c o  m
 * 
 * @return the list of elements
 */
public List<WebElement> findAll() {
    checkState(webDriver != null, "No WebDriver specified.");
    checkState(by != null, "No By instance for locating elements specified.");

    log.info(toString());

    final List<WebElement> result = newArrayList();

    try {
        if (timeoutSeconds > 0L) {
            WebDriverWait wait = createWebDriverWait();
            wait.until(new Function<WebDriver, List<WebElement>>() {
                @Override
                public List<WebElement> apply(final WebDriver input) {
                    doFindElements(result, input);
                    if (result.isEmpty()) {
                        // this means, we try again until the timeout occurs
                        throw new WebElementException("No matching element found.");
                    }
                    return result;
                }

                @Override
                public String toString() {
                    return WebElementFinder.this.toString();
                }
            });
        } else {
            doFindElements(result, webDriver);
        }
        return result;
    } catch (TimeoutException ex) {
        Throwable cause = ex.getCause();
        for (Class<? extends Throwable> thClass : IGNORED_EXCEPTIONS) {
            if (thClass.isInstance(cause)) {
                return ImmutableList.of();
            }
        }
        throw new WebElementException(ex);
    }
}

From source file:com.processpuzzle.artifact.domain.Artifact.java

public <V extends ArtifactView> V findViewByClass(Class<V> viewClass) {
    for (Iterator<String> iter = availableViews.keySet().iterator(); iter.hasNext();) {
        String viewName = iter.next();

        if (viewClass.isInstance(availableViews.get(viewName)))
            return (V) availableViews.get(viewName);
    }// w w  w  . j  a v a 2s.  c  o m
    return null;
}

From source file:de.julielab.jcore.utility.JCoReAnnotationTools.java

/**
 * Returns the nearest annotation of class <tt>cls</tt> to <tt>focusAnnotation</tt>, i.e. the one (or just one, if
 * multiple exist) with the highest start-offset that completely overlaps <tt>focusAnnotation</tt>.
 * <p>/*from  www.  j  a  v a 2 s .c o m*/
 * This method has nice performance properties when it is known that the annotation looked for is near, e.g. finding
 * the nearest token or sentence.
 * </p>
 * 
 * @param aJCas
 * @param focusAnnotation
 * @param cls
 * @return the leftmost annotation of type <tt>cls</tt> that completely includes <tt>focusAnnotation</tt>.
 */
@SuppressWarnings("unchecked")
public static <T extends Annotation> T getNearestIncludingAnnotation(JCas aJCas, Annotation focusAnnotation,
        Class<T> cls) {
    FSIterator<Annotation> cursor = aJCas.getAnnotationIndex().iterator();

    if (!cursor.isValid())
        throw new IllegalArgumentException(
                "Given FocusAnnotation was not found in the JCas' annotation index: " + focusAnnotation);

    // The annotations are sorted by begin offset. So go to the first annotation with a larger begin offset compared
    // to the focusAnnotation. Afterwards we we search for an including annotation to the left.
    cursor.moveTo(focusAnnotation);
    while (cursor.isValid() && cursor.get().getBegin() <= focusAnnotation.getBegin()) {
        cursor.moveToNext();
    }
    if (!cursor.isValid())
        cursor.moveTo(focusAnnotation);
    else
        cursor.moveToPrevious();

    // Now that we have our starting point, we go to the left until we find the first annotation of correct type
    // completely overlapping the focus annotation.
    while (cursor.isValid()) {
        Annotation currentAnnotation = cursor.get();
        if (!cls.isInstance(currentAnnotation)) {
            cursor.moveToPrevious();
            continue;
        }
        Range<Integer> currentRange = Range.between(currentAnnotation.getBegin(), currentAnnotation.getEnd());
        Range<Integer> focusRange = Range.between(focusAnnotation.getBegin(), focusAnnotation.getEnd());
        if (cursor.isValid() && cls.isInstance(currentAnnotation) && currentRange.containsRange(focusRange))
            return (T) currentAnnotation;
        cursor.moveToPrevious();
    }
    return null;
}

From source file:com.amalto.workbench.service.GlobalServiceRegister.java

/**
 * DOC qian Comment method "findService".Finds the specific service from the list.
 * //  w  ww .  ja va 2 s  . c o m
 * @param klass the interface type want to find.
 * @return IService
 */
private IService findService(Class klass) {
    String key = klass.getName();
    for (int i = 0; i < configurationElements.length; i++) {
        IConfigurationElement element = configurationElements[i];
        String id = element.getAttribute("serviceId"); //$NON-NLS-1$
        element.getAttribute("class");//$NON-NLS-1$
        if (!key.endsWith(id)) {
            continue;
        }
        try {
            Object service = element.createExecutableExtension("class"); //$NON-NLS-1$
            if (klass.isInstance(service)) {
                return (IService) service;
            }
        } catch (CoreException e) {
            log.error(e.getMessage(), e);
        }
    }
    return null;
}

From source file:hudson.PluginManager.java

/**
 * Get the plugin instances that extend a specific class, use to find similar plugins.
 * Note: beware the classloader fun.//from   ww w.  j av  a2s.c om
 * @param pluginSuperclass The class that your plugin is derived from.
 * @return The list of plugins implementing the specified class.
 */
public List<PluginWrapper> getPlugins(Class<? extends Plugin> pluginSuperclass) {
    List<PluginWrapper> result = new ArrayList<PluginWrapper>();
    for (PluginWrapper p : plugins) {
        if (pluginSuperclass.isInstance(p.getPlugin()))
            result.add(p);
    }
    return Collections.unmodifiableList(result);
}

From source file:com.nextep.datadesigner.vcs.impl.Merger.java

protected boolean isClass(Class<?> clazz, Object src, Object tgt) {
    return ((src == null || (clazz.isInstance(src))) && (tgt == null || (clazz.isInstance(tgt))));
}

From source file:com.bstek.dorado.data.JsonUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object internalToJavaEntity(ObjectNode objectNode, EntityDataType dataType, Class<?> targetType,
        boolean proxy, JsonConvertContext context) throws Exception {
    if (objectNode == null || objectNode.isNull()) {
        return null;
    }/*ww w  .j a  v  a 2  s . c  o  m*/

    Class<?> creationType = null;
    if (dataType != null && !(dataType instanceof CustomEntityDataType)) {
        creationType = dataType.getCreationType();
        if (creationType == null) {
            creationType = dataType.getMatchType();
        }
    }
    if (creationType == null) {
        creationType = Record.class;
    }

    Object result;
    if (EnhanceableEntity.class.isAssignableFrom(creationType)) {
        EnhanceableEntity ee = (EnhanceableEntity) creationType.newInstance();
        ee.setEntityEnhancer(new EnhanceableMapEntityEnhancer(dataType));
        result = ee;
    } else {
        MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(dataType, creationType,
                null);
        result = ProxyBeanUtils.createBean(creationType, mis);
    }

    EntityWrapper entity = EntityWrapper.create(result);
    if (proxy) {
        entity.setStateLocked(true);
    }

    Iterator<Entry<String, JsonNode>> fields = objectNode.getFields();
    while (fields.hasNext()) {
        Entry<String, JsonNode> field = fields.next();
        String property = field.getKey();
        if (property.charAt(0) == SYSTEM_PROPERTY_PREFIX) {
            continue;
        }

        Object value = null;
        JsonNode jsonNode = field.getValue();
        if (jsonNode != null && !jsonNode.isNull()) {
            Class<?> type = null;
            PropertyDef propertyDef = null;
            DataType propertyDataType = null;
            type = entity.getPropertyType(property);
            if (dataType != null) {
                propertyDef = dataType.getPropertyDef(property);
                if (propertyDef != null) {
                    propertyDataType = propertyDef.getDataType();
                }
            }

            if (jsonNode instanceof ContainerNode) {
                value = toJavaObject(jsonNode, propertyDataType, type, proxy, context);
            } else if (jsonNode instanceof ValueNode) {
                value = toJavaValue((ValueNode) jsonNode, propertyDataType, null);
            } else {
                throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
            }

            if (type != null) {
                if (!type.isInstance(value)) {
                    if (value instanceof String && type.isEnum()) {
                        if (StringUtils.isNotBlank((String) value)) {
                            value = Enum.valueOf((Class<? extends Enum>) type, (String) value);
                        }
                    } else {
                        propertyDataType = getDataTypeManager().getDataType(type);
                        if (propertyDataType != null) {
                            value = propertyDataType.fromObject(value);
                        }
                    }
                }
            } else {
                if (value instanceof String) { // ?
                    String str = (String) value;
                    if (str.length() == DEFAULT_DATE_PATTERN_LEN
                            && DEFAULT_DATE_PATTERN.matcher(str).matches()) {
                        value = DateUtils.parse(com.bstek.dorado.core.Constants.ISO_DATETIME_FORMAT1, str);
                    }
                }
            }
        }
        entity.set(property, value);
    }

    if (proxy) {
        entity.setStateLocked(false);
        int state = JsonUtils.getInt(objectNode, STATE_PROPERTY);
        if (state > 0) {
            entity.setState(EntityState.fromInt(state));
        }

        int entityId = JsonUtils.getInt(objectNode, ENTITY_ID_PROPERTY);
        if (entityId > 0) {
            entity.setEntityId(entityId);
        }

        ObjectNode jsonOldValues = (ObjectNode) objectNode.get(OLD_DATA_PROPERTY);
        if (jsonOldValues != null) {
            Map<String, Object> oldValues = entity.getOldValues(true);
            Iterator<Entry<String, JsonNode>> oldFields = jsonOldValues.getFields();
            while (oldFields.hasNext()) {
                Entry<String, JsonNode> entry = oldFields.next();
                String property = entry.getKey();
                PropertyDef propertyDef = null;
                DataType propertyDataType = null;
                Object value;

                if (dataType != null) {
                    propertyDef = dataType.getPropertyDef(property);
                    if (propertyDef != null) {
                        propertyDataType = propertyDef.getDataType();
                    }
                }

                if (dataType != null) {
                    propertyDef = dataType.getPropertyDef(property);
                    if (propertyDef != null) {
                        propertyDataType = propertyDef.getDataType();
                    }
                }

                JsonNode jsonNode = entry.getValue();
                if (jsonNode instanceof ContainerNode) {
                    Class<?> type = entity.getPropertyType(property);
                    value = toJavaObject(jsonNode, propertyDataType, type, proxy, context);
                } else if (jsonNode instanceof ValueNode) {
                    value = toJavaValue((ValueNode) jsonNode, propertyDataType, null);
                } else {
                    throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
                }

                oldValues.put(property, value);
            }
        }
    }

    if (targetType != null && !targetType.isInstance(result)) {
        throw new IllegalArgumentException("Java type mismatch. expect [" + targetType + "].");
    }
    if (context != null && context.getEntityCollection() != null) {
        context.getEntityCollection().add(result);
    }
    return result;
}

From source file:net.sf.ehcache.constructs.asynchronous.AsynchronousCommandExecutor.java

private boolean checkIfRetryOnThrowable(Throwable throwable, InstrumentedCommand instrumentedCommand) {
    Command command = instrumentedCommand.command;
    Class[] retryThrowables = command.getThrowablesToRetryOn();
    if (retryThrowables == null) {
        return false;
    }//from   www  .  j av a 2s.  c  om
    boolean match = false;
    for (int i = 0; i < retryThrowables.length; i++) {
        Class retryThrowable = retryThrowables[i];
        if (retryThrowable.isInstance(throwable)) {
            match = true;
        }

    }
    return match;
}

From source file:net.java.sip.communicator.impl.protocol.jabber.InfoRetreiver.java

/**
 * returns the user details from the specified class or its descendants
 * the class is one from the/* w  w  w.  j a  v a2 s .co m*/
 * net.java.sip.communicator.service.protocol.ServerStoredDetails
 * or implemented one in the operation set for the user info
 *
 * @param uin String
 * @param detailClass Class
 * @return Iterator
 */
<T extends GenericDetail> Iterator<T> getDetailsAndDescendants(String uin, Class<T> detailClass) {
    List<GenericDetail> details = getContactDetails(uin);
    List<T> result = new LinkedList<T>();

    for (GenericDetail item : details)
        if (detailClass.isInstance(item)) {
            @SuppressWarnings("unchecked")
            T t = (T) item;

            result.add(t);
        }

    return result.iterator();
}

From source file:com.thinkbiganalytics.metadata.core.dataset.InMemoryDatasourceProvider.java

@Override
public <D extends Datasource> D ensureDatasource(String name, String descr, Class<D> type) {
    synchronized (this.datasets) {
        try {//from   www  .j  ava  2 s .  c om
            D ds = null;
            BaseDatasource existing = getExistingDataset(name);

            if (existing == null) {
                ds = (D) ConstructorUtils.invokeConstructor(type, name, descr);
                this.datasets.put(ds.getId(), ds);
            } else if (type.isInstance(ds)) {
                ds = (D) existing;
            } else {
                throw new MetadataException("A datasource already exists of type: " + ds.getClass()
                        + " but expected one of type: " + type);
            }

            return ds;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException
                | InstantiationException e) {
            throw new MetadataException("Failed to create a datasource to type: " + type, e);
        }
    }
}