Example usage for java.lang Class cast

List of usage examples for java.lang Class cast

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@HotSpotIntrinsicCandidate
public T cast(Object obj) 

Source Link

Document

Casts an object to the class or interface represented by this Class object.

Usage

From source file:hudson.model.User.java

/**
 * Gets the specific property, or null.// ww  w .  ja va 2s.  com
 */
public <T extends UserProperty> T getProperty(Class<T> clazz) {
    for (UserProperty p : properties) {
        if (clazz.isInstance(p))
            return clazz.cast(p);
    }
    return null;
}

From source file:ddf.security.samlp.impl.LogoutMessageImpl.java

private <T extends SAMLObject> T extract(String samlObject, Class<T> clazz)
        throws WSSecurityException, XMLStreamException {
    Document responseDoc = StaxUtils
            .read(new ByteArrayInputStream(samlObject.getBytes(StandardCharsets.UTF_8)));
    XMLObject responseXmlObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    if (clazz.isAssignableFrom(responseXmlObject.getClass())) {
        return clazz.cast(responseXmlObject);
    }/*ww w .  j ava  2 s  . c om*/
    return null;
}

From source file:com.oneops.cassandra.ClusterBootstrap.java

/**
 * Return the property value associated with the given key, or
 * {@code defaultValue} if the key cannot be resolved. The property
 * resolution flow is//  w  w w  .  j  av  a 2  s . co m
 * <p/>
 * <ol>
 * <li>Get from {@code Environment} if it's running in spring container.
 * It uses property file config and system property as fallback
 * mechanisms</li>
 * <li>Get the value from System Property (-Dprop=value) in non spring env</li>
 * <li>If it can't find anywhere, returns the  {@code defaultValue} </li>
 * <p/>
 * </ol>
 *
 * @param prop         the property name to resolve
 * @param T            the expected type of the property value
 * @param defaultValue the default value to return if no value is found
 */
private <T> T getProp(String prop, Class<T> targetType, T defaultValue) {

    T val = defaultValue;
    // Fully qualified property name
    final String fqProp = CPP + "." + prop;

    if (env != null) {
        val = env.getProperty(fqProp, targetType, defaultValue);
    } else {
        String spVal = System.getProperty(fqProp);
        if (spVal != null) {
            if (targetType.isAssignableFrom(Boolean.class)) {
                val = targetType.cast(getBoolean(spVal));
            } else if (targetType.isAssignableFrom(Integer.class)) {
                val = targetType.cast(parseInt(spVal));
            } else if (targetType.isAssignableFrom(Double.class)) {
                val = targetType.cast(parseDouble(spVal));
            } else if (targetType.isAssignableFrom(String.class)) {
                val = targetType.cast(spVal);
            }
        }
    }
    return val;
}

From source file:com.slytechs.capture.StreamFactory.java

public <T extends InputCapture<? extends FilePacket>> T newInput(final Class<T> t, final ReadableByteChannel in,
        final Filter<ProtocolFilterTarget> filter) throws IOException {
    if (t == PcapInput.class) {
        final BufferedReadableByteChannel b = new BufferedReadableByteChannel(in);
        b.mark(4);/*from w w  w  .  j  av  a2s. c  o m*/

        ByteOrder order = PcapInputCapture.checkFormat(b);

        b.reset();
        return t.cast(new PcapInputCapture(b, order, filter));

    } else if (t == SnoopInput.class) {
        return t.cast(new SnoopInputCapture(in, filter));
    }

    throw new IllegalArgumentException("Unknown input stream format type [" + t.getName() + "]");
}

From source file:com.univocity.articles.kairosdb.custom.KairosDataEntity.java

@Override
public WritingProcess prepareToWrite(String[] fieldNames) {

    final Map<String, Integer> fieldPositions = new HashMap<String, Integer>();
    for (int i = 0; i < fieldNames.length; i++) {
        fieldPositions.put(fieldNames[i], i);
    }/*w ww.  ja va  2s  .  com*/

    return new WritingProcess() {

        MetricBuilder builder = MetricBuilder.getInstance();

        @Override
        public void close() {
            // will push the metrics at the end of each batch instead of at the end of the transaction.
            // otherwise the generated JSON content can be excessively big.
            dataStore.pushMetrics(KairosDataEntity.this, builder);
        }

        @Override
        public void writeNext(Object[] data) {
            String name = get("name", String.class, data, true);
            Metric metric = builder.addMetric(name);

            Long timestamp = get("timestamp", Long.class, data, false);
            Object value = get("value", Object.class, data, true);

            if (timestamp == null) {
                metric.addDataPoint(System.currentTimeMillis(), value);
            } else {
                metric.addDataPoint(timestamp, value);
            }

            for (String tag : tags) {
                String tagValue = get(tag, String.class, data, false);
                metric.addTag(tag, tagValue);
            }
        }

        private <T> T get(String field, Class<T> type, Object[] data, boolean mandatory) {
            Integer position = fieldPositions.get(field);
            if (position == null) {
                if (mandatory) {
                    throw new IllegalStateException("Mandatory field '" + field + "' not mapped.");
                } else {
                    return null;
                }
            }
            Object value = data[position.intValue()];
            return type.cast(value);
        }

        @Override
        public ReadingProcess retrieveGeneratedKeys() {
            return null;
        }
    };
}

From source file:com.rodaxsoft.junit.mailgun.MemberDetailsConverter.java

@Override
public <T> T convert(Class<T> type, Object value) {

    MemberDetails details = null;/*from w ww  .j  a va 2  s  .c  o  m*/

    if (value instanceof JSONObject) {

        JSONObject obj = (JSONObject) value;

        details = new MemberDetails();

        try {
            BeanUtils.populate(details, obj);
        } catch (IllegalAccessException | InvocationTargetException e) {
            ContextedRuntimeException cre;
            cre = new ContextedRuntimeException("Bean population error", e);
            cre.addContextValue("value", obj);
            throw cre;
        }

    }

    return type.cast(details);
}

From source file:org.apache.taverna.scufl2.translator.t2flow.defaultactivities.AbstractActivityParser.java

public <ConfigType> ConfigType unmarshallConfig(T2FlowParser t2FlowParser, ConfigBean configBean,
        String encoding, Class<ConfigType> configType) throws ReaderException {
    Object config = configBean.getAny();
    if (config instanceof JAXBElement) {
        JAXBElement<?> jaxbElement = (JAXBElement<?>) config;
        if (!configType.isInstance((jaxbElement.getValue())))
            throw new ReaderException("Unexpected config type: " + jaxbElement.getValue().getClass()
                    + ", expected " + configType);
        return configType.cast(jaxbElement.getValue());
    }//from   w  w w  .  ja  v  a 2s  . co m
    if (!(config instanceof Element) || !configBean.getEncoding().equals(encoding))
        throw new ReaderException("Unsupported config bean " + configBean);
    return unmarshallElement(t2FlowParser, (Element) config, configType);
}

From source file:edu.harvard.i2b2.fhir.FhirUtil.java

public static Object getChildThruChain(Resource r, String pathStr, List<Resource> s)
        // is dot separated path
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {
    Class c = FhirUtil.getResourceClass(r);

    String suffix = null;//from   w w  w .j  a v  a  2 s .c o  m
    String prefix = pathStr;
    logger.trace("pathStr:" + pathStr);

    if (pathStr.indexOf('.') > -1) {
        suffix = pathStr.substring(pathStr.indexOf('.') + 1);
        prefix = pathStr.substring(0, pathStr.indexOf('.'));
    }

    String methodName = prefix.substring(0, 1).toUpperCase() + prefix.subSequence(1, prefix.length());
    Method method = c.getMethod("get" + methodName, null);
    Object o = method.invoke(c.cast(r));

    if (suffix == null) {
        return o;

    } else {
        if (Reference.class.isInstance(o)) {
            Reference rr = Reference.class.cast(o);
            logger.trace("gotc:" + o.getClass());

            /*
             * try { logger.trace("seek:" + JAXBUtil.toXml(rr));
             * logger.trace("seek:" + rr.getReference().getValue()); } catch
             * (JAXBException e) { // TODO Auto-generated catch block
             * e.printStackTrace(); }
             */

            Resource r1 = FhirUtil.findResourceById(rr.getReference().getValue(), s);
            return getChildThruChain(r1, suffix, s);
        } else {
            return getChildThruChain(r, suffix, s);
        }
    }
}

From source file:org.exoplatform.container.spring.SpringContainer.java

/**
 * {@inheritDoc}/*from   w  w  w  .  j  av a2  s  .c  om*/
 */
@Override
public <T> T getComponentInstance(Object componentKey, Class<T> bindType, boolean autoRegistration) {
    T result = super.getComponentInstance(componentKey, bindType, autoRegistration);
    if (ctx != null && result == null) {
        if (componentKey instanceof Class<?> && !((Class<?>) componentKey).isAnnotation()) {
            return bindType.cast(getInstanceOfType((Class<?>) componentKey));
        } else if (!(componentKey instanceof String) && !(componentKey instanceof Class<?>)) {
            return null;
        }
        String beanName = keyToBeanName(componentKey);
        if (ctx.containsBean(beanName) && bindType.isAssignableFrom(ctx.getType(beanName))) {
            return bindType.cast(ctx.getBean(beanName));
        }
        String[] names = ctx.getBeanNamesForType(bindType);
        if (names != null && names.length > 0) {
            for (int i = 0, length = names.length; i < length; i++) {
                String name = names[i];
                if (componentKey instanceof String) {
                    Named n = ctx.findAnnotationOnBean(name, Named.class);
                    if (n != null && componentKey.equals(n.value())) {
                        return bindType.cast(ctx.getBean(name));
                    }
                } else {
                    @SuppressWarnings("unchecked")
                    Annotation a = ctx.findAnnotationOnBean(name, (Class<? extends Annotation>) componentKey);
                    if (a != null) {
                        return bindType.cast(ctx.getBean(name));
                    }
                }
            }
        }
    }
    return result;
}

From source file:io.fabric8.spring.cloud.kubernetes.reload.ConfigurationChangeDetector.java

/**
 * Finds all registered property sources of the given type.
 *//*from  w w w  .  j a v a2  s.  c om*/
protected <S extends PropertySource<?>> List<S> findPropertySources(Class<S> sourceClass) {
    List<S> managedSources = new LinkedList<>();

    LinkedList<PropertySource<?>> sources = toLinkedList(environment.getPropertySources());
    while (!sources.isEmpty()) {
        PropertySource<?> source = sources.pop();
        if (source instanceof CompositePropertySource) {
            CompositePropertySource comp = (CompositePropertySource) source;
            sources.addAll(comp.getPropertySources());
        } else if (sourceClass.isInstance(source)) {
            managedSources.add(sourceClass.cast(source));
        }
    }

    return managedSources;
}