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:me.bayes.vertx.vest.VestApplication.java

public <T> T getSingleton(Class<? extends T> type) {
    for (Object object : singletons) {
        if (type.isInstance(object)) {
            return (T) object;
        }//from  w w w  .j  av  a  2s  .  c  o  m
    }

    return null;
}

From source file:com.ery.ertc.estorm.util.JVM.java

/**
 * Load the implementation of UnixOperatingSystemMXBean for Oracle jvm and runs the desired method.
 * /*from w w  w.  ja va 2 s.c  o m*/
 * @param mBeanMethodName
 *            : method to run from the interface UnixOperatingSystemMXBean
 * @return the method result
 */
private Long runUnixMXBeanMethod(String mBeanMethodName) {
    Object unixos;
    Class<?> classRef;
    Method mBeanMethod;

    try {
        classRef = Class.forName("com.sun.management.UnixOperatingSystemMXBean");
        if (classRef.isInstance(osMbean)) {
            mBeanMethod = classRef.getMethod(mBeanMethodName, new Class[0]);
            unixos = classRef.cast(osMbean);
            return (Long) mBeanMethod.invoke(unixos);
        }
    } catch (Exception e) {
        LOG.warn("Not able to load class or method for" + " com.sun.management.UnixOperatingSystemMXBean.", e);
    }
    return null;
}

From source file:JSONWrapper.java

public <E> List<E> asList(List<E> defaultValue, Class<E> type) {
    if (this.value instanceof List) {
        List<E> values = new ArrayList<>();
        for (Object obj : (List) this.value) {
            if (type.isInstance(obj)) {
                values.add(type.cast(obj));
            }//from   www.  jav a 2s  .co  m
        }

        return values;
    } else if (this.value instanceof JSONArray) {
        return this.asArray().asList(defaultValue, type);
    }
    return defaultValue;
}

From source file:eu.eidas.node.auth.metadata.NODEMetadataProcessor.java

private <T extends RoleDescriptor> T getFirstRoleDescriptor(EntityDescriptor entityDescriptor,
        final Class<T> clazz) {
    for (RoleDescriptor rd : entityDescriptor.getRoleDescriptors()) {
        if (clazz.isInstance(rd)) {
            return (T) rd;
        }/* w  w  w. j av  a2  s .c o m*/
    }
    return null;
}

From source file:com.alibaba.citrus.service.requestcontext.session.valueencoder.AbstractSessionValueEncoder.java

protected final String convertToString(Class<?> type, Object value, TypeConverter converter) {
    if (value instanceof String) {
        return (String) value;
    } else {//from   w w w . j  a  v a2 s  . c om
        if (converter instanceof PropertyEditorRegistry && type != null && type.isInstance(value)) {
            PropertyEditor editor = ((PropertyEditorRegistry) converter).findCustomEditor(type, null);

            if (editor != null) {
                editor.setValue(value);
                return editor.getAsText();
            }
        }

        return (String) getTypeConverter().convertIfNecessary(value, String.class);
    }
}

From source file:org.redisson.spring.cache.RedissonCache.java

public <T> T get(Object key, Class<T> type) {
    Object value = map.get(key);//w  w w  .  j a  va  2  s  .  c o m
    if (value != null) {
        if (value.getClass().getName().equals(NullValue.class.getName())) {
            return null;
        }
        if (type != null && !type.isInstance(value)) {
            throw new IllegalStateException(
                    "Cached value is not of required type [" + type.getName() + "]: " + value);
        }
    }
    return (T) value;
}

From source file:multichain.command.builders.QueryBuilderCommon.java

@SuppressWarnings("rawtypes")
protected boolean verifyInstanceofList(List<Object> obj, Class TheClass) {
    boolean verify = true;

    // Verify only the first Element of the list
    if (obj.size() > 0) {
        Object objElt = obj.get(0);
        if (!LinkedTreeMap.class.isInstance(objElt)) {
            verify = TheClass.isInstance(objElt);
        }//  www. ja  v  a2  s  . c om
    }

    return verify;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Convert a {@link JSONArray} with only non-array children into a {@link Collection}.
 *
 * @param jsonArray The array to convert.
 * @param collection The Collection to populate. The parametrization should match {@code
 * typeClass}.//from  ww  w . jav a 2 s . c  o m
 * @param itemParser The parser to use for items of the array. May be null.
 * @param typeClass The type of items to expect in the array. May not be null, but may be
 * Object.class.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 */
private static <T> void convertFlatJsonArrayToCollection(JSONArray jsonArray, Collection<T> collection,
        JsonObjectParser<T> itemParser, Class<T> typeClass, String key, JsonParserContext context)
        throws IOException {
    Converter<T> converter = null;
    if (Converters.isConvertibleFromString(typeClass)) {
        converter = Converters.getConverter(typeClass);
    }
    for (int i = 0; i < jsonArray.length(); i++) {
        Object o = jsonArray.opt(i);
        T parsedItem = null;
        if (typeClass.isInstance(o)) {
            @SuppressWarnings("unchecked")
            T castItem = (T) o;
            parsedItem = castItem;
        } else if (o instanceof JSONObject) {
            parsedItem = convertJsonObject((JSONObject) o, typeClass, itemParser, context);
        } else if (o instanceof String && converter != null) {
            parsedItem = converter.convert((String) o);
        }

        if (parsedItem != null) {
            collection.add(parsedItem);
        } else {
            throw new IllegalStateException(
                    String.format(Locale.US, "Could not convert value in array at \"%s\" to %s from %s.", key,
                            typeClass.getName(), getClassName(o)));
        }
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(final Collection<HttpClientConfiguration> configurations) {
    return new HttpClientFactory() {
        @Override/*from  ww  w .  j  a  v  a 2s .  c  o  m*/
        public HttpClient createClient(String host, int port) {

            ApacheHttpClient31BackedHttpClient httpClient = createApacheClient();

            HostConfiguration hostConfiguration = new HostConfiguration();
            configureSsl(hostConfiguration, host, port, httpClient);
            configureProxy(hostConfiguration, httpClient);

            httpClient.setHostConfiguration(hostConfiguration);
            configureOAuth(httpClient);
            return httpClient;
        }

        private ApacheHttpClient31BackedHttpClient createApacheClient() {
            HttpClientConfig httpClientConfig = locateConfig(HttpClientConfig.class,
                    HttpClientConfig.newBuilder().build());

            HttpConnectionManager connectionManager = createConnectionManager(httpClientConfig);

            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
                    connectionManager);
            client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
            client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
            client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);
            client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);

            return new ApacheHttpClient31BackedHttpClient(client,
                    httpClientConfig.getCopyOfHeadersForEveryRequest());

        }

        @SuppressWarnings("unchecked")
        private <T> T locateConfig(Class<? extends T> _class, T defaultConfiguration) {
            for (HttpClientConfiguration configuration : configurations) {
                if (_class.isInstance(configuration)) {
                    return (T) configuration;
                }
            }
            return defaultConfiguration;
        }

        private boolean hasValidProxyUsernameAndPasswordSettings(HttpClientProxyConfig httpClientProxyConfig) {
            return StringUtils.isNotBlank(httpClientProxyConfig.getProxyUsername())
                    && StringUtils.isNotBlank(httpClientProxyConfig.getProxyPassword());
        }

        private HttpConnectionManager createConnectionManager(HttpClientConfig config) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            if (config.getMaxConnectionsPerHost() > 0) {
                connectionManager.getParams()
                        .setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost());
            } else {
                connectionManager.getParams().setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE);
            }
            if (config.getMaxConnections() > 0) {
                connectionManager.getParams().setMaxTotalConnections(config.getMaxConnections());
            }
            return connectionManager;
        }

        private void configureOAuth(ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientOAuthConfig httpClientOAuthConfig = locateConfig(HttpClientOAuthConfig.class, null);
            if (httpClientOAuthConfig != null) {
                String serviceName = httpClientOAuthConfig.getServiceName();
                HttpClientConsumerKeyAndSecretProvider consumerKeyAndSecretProvider = httpClientOAuthConfig
                        .getConsumerKeyAndSecretProvider();
                String consumerKey = consumerKeyAndSecretProvider.getConsumerKey(serviceName);
                if (StringUtils.isEmpty(consumerKey)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerKey is null or empty for service:"
                                    + serviceName);
                }
                String consumerSecret = consumerKeyAndSecretProvider.getConsumerSecret(serviceName);
                if (StringUtils.isEmpty(consumerSecret)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerSecret is null or empty for service:"
                                    + serviceName);
                }

                httpClient.setConsumerTokens(consumerKey, consumerSecret);
            }
        }

        private void configureProxy(HostConfiguration hostConfiguration,
                ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientProxyConfig httpClientProxyConfig = locateConfig(HttpClientProxyConfig.class, null);
            if (httpClientProxyConfig != null) {
                hostConfiguration.setProxy(httpClientProxyConfig.getProxyHost(),
                        httpClientProxyConfig.getProxyPort());
                if (hasValidProxyUsernameAndPasswordSettings(httpClientProxyConfig)) {
                    HttpState state = new HttpState();
                    state.setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(httpClientProxyConfig.getProxyUsername(),
                                    httpClientProxyConfig.getProxyPassword()));
                    httpClient.setState(state);
                }
            }
        }

        private void configureSsl(HostConfiguration hostConfiguration, String host, int port,
                ApacheHttpClient31BackedHttpClient httpClient) throws IllegalStateException {
            HttpClientSSLConfig httpClientSSLConfig = locateConfig(HttpClientSSLConfig.class, null);
            if (httpClientSSLConfig != null) {
                Protocol sslProtocol;
                if (httpClientSSLConfig.getCustomSSLSocketFactory() != null) {
                    sslProtocol = new Protocol(HTTPS_PROTOCOL, new CustomSecureProtocolSocketFactory(
                            httpClientSSLConfig.getCustomSSLSocketFactory()), SSL_PORT);
                } else {
                    sslProtocol = Protocol.getProtocol(HTTPS_PROTOCOL);
                }
                hostConfiguration.setHost(host, port, sslProtocol);
                httpClient.setUsingSSL();
            } else {
                hostConfiguration.setHost(host, port);
            }
        }
    };
}

From source file:cgeo.geocaching.connector.AbstractConnector.java

private void addCapability(final List<String> capabilities, final Class<? extends IConnector> clazz,
        @StringRes final int featureResourceId) {
    if (clazz.isInstance(this)) {
        capabilities.add(feature(featureResourceId));
    }/*ww  w. j a va2  s.c  o  m*/
}