Example usage for java.lang Class asSubclass

List of usage examples for java.lang Class asSubclass

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <U> Class<? extends U> asSubclass(Class<U> clazz) 

Source Link

Document

Casts this Class object to represent a subclass of the class represented by the specified class object.

Usage

From source file:org.apache.hadoop.hive.accumulo.predicate.PrimitiveComparisonFilter.java

@Override
public void init(SortedKeyValueIterator<Key, Value> source, Map<String, String> options,
        IteratorEnvironment env) throws IOException {
    super.init(source, options, env);
    String serializedColumnMapping = options.get(COLUMN);
    Entry<String, String> pair = ColumnMappingFactory.parseMapping(serializedColumnMapping);

    // The ColumnEncoding, column name and type are all irrelevant at this point, just need the
    // cf:[cq]/*w w w  .ja  v a  2 s.co m*/
    columnMapping = new HiveAccumuloColumnMapping(pair.getKey(), pair.getValue(), ColumnEncoding.STRING,
            "column", "string");
    columnMappingFamily = new Text(columnMapping.getColumnFamily());
    columnMappingQualifier = new Text(columnMapping.getColumnQualifier());
    cfHolder = new Text();
    cqHolder = new Text();

    try {
        Class<?> pClass = JavaUtils.loadClass(options.get(P_COMPARE_CLASS));
        Class<?> cClazz = JavaUtils.loadClass(options.get(COMPARE_OPT_CLASS));
        PrimitiveComparison pCompare = pClass.asSubclass(PrimitiveComparison.class).newInstance();
        compOpt = cClazz.asSubclass(CompareOp.class).newInstance();
        byte[] constant = getConstant(options);
        pCompare.init(constant);
        compOpt.setPrimitiveCompare(pCompare);
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    } catch (InstantiationException e) {
        throw new IOException(e);
    } catch (IllegalAccessException e) {
        throw new IOException(e);
    }
}

From source file:com.asakusafw.runtime.directio.hadoop.SequenceFileFormat.java

/**
 * Returns a compression codec for output sequence files.
 * Clients can override this method in subclasses, and return the suitable {@link CompressionCodec} object.
 * @param path target path/*from  www.  ja v  a 2s. c o m*/
 * @return a compression codec used to output, or {@code null} if output will not be compressed
 * @throws IOException if failed to create a compression codec
 * @throws InterruptedException if interrupted
 */
public CompressionCodec getCompressionCodec(Path path) throws IOException, InterruptedException {
    String codecClassName = getConf().get(KEY_COMPRESSION_CODEC);
    if (codecClassName != null && codecClassName.isEmpty() == false) {
        try {
            Class<?> codecClass = getConf().getClassByName(codecClassName);
            return ReflectionUtils.newInstance(codecClass.asSubclass(CompressionCodec.class), getConf());
        } catch (Exception e) {
            LOG.warn(MessageFormat.format("Failed to load compression codec ({0}={1})", KEY_COMPRESSION_CODEC,
                    codecClassName), e);
            return null;
        }
    }
    return null;
}

From source file:com.antonjohansson.geolocation.config.Configuration.java

private <T> T getInstance(Properties properties, Class<T> target) {
    String type = target.getSimpleName().toLowerCase();
    String className = properties.getProperty(type);
    Class<?> clazz = getClass(className);
    if (!target.isAssignableFrom(clazz)) {
        throw new RuntimeException("'" + clazz.getName() + "' is not a valid " + type);
    }//  w ww.  j  a  v a 2  s  . c  o  m
    T instance = newInstance(clazz.asSubclass(target));

    List<String> keys = properties.keySet().stream().filter(key -> key instanceof String)
            .map(key -> (String) key).filter(key -> key.startsWith(type))
            .filter(key -> key.length() > type.length()).map(key -> key.substring(type.length() + 1))
            .filter(key -> isWriteable(instance, key)).collect(toList());

    for (String key : keys) {
        Object value = properties.get(type + "." + key);
        try {
            setProperty(instance, key, value);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return instance;
}

From source file:org.seedstack.seed.rest.internal.RestPlugin.java

@Override
public InitState init(InitContext initContext) {
    if (servletContext == null) {
        LOGGER.info("No servlet context detected, REST support disabled");
        return InitState.INITIALIZED;
    }//from  w  ww .ja v a 2  s  .c  om

    Configuration restConfiguration = null;
    WebPlugin webPlugin = null;
    for (Plugin plugin : initContext.pluginsRequired()) {
        if (plugin instanceof ApplicationPlugin) {
            restConfiguration = ((ApplicationPlugin) plugin).getApplication().getConfiguration()
                    .subset(RestPlugin.REST_PLUGIN_CONFIGURATION_PREFIX);
        } else if (plugin instanceof WebPlugin) {
            webPlugin = (WebPlugin) plugin;
        }
    }

    if (restConfiguration == null) {
        throw new PluginException("Unable to find SEED application plugin");
    }
    if (webPlugin == null) {
        throw new PluginException("Unable to find SEED Web plugin");
    }

    String restPath = restConfiguration.getString("path", "/rest");
    String jspPath = restConfiguration.getString("jsp-path", "/WEB-INF/jsp");

    Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext
            .scannedClassesByAnnotationClass();
    Map<Specification, Collection<Class<?>>> scannedClassesBySpecification = initContext
            .scannedTypesBySpecification();

    Collection<Class<?>> resourceFilterFactoryClasses = scannedClassesByAnnotationClass
            .get(ResourceFiltering.class);
    Set<Class<? extends ResourceFilterFactory>> resourceFilterFactories = new HashSet<Class<? extends ResourceFilterFactory>>();
    if (resourceFilterFactoryClasses != null) {
        for (Class<?> candidate : resourceFilterFactoryClasses) {
            if (ResourceFilterFactory.class.isAssignableFrom(candidate)) {
                resourceFilterFactories.add(candidate.asSubclass(ResourceFilterFactory.class));
            }
        }
    }

    Map<String, String> jerseyParameters = new HashMap<String, String>();
    Properties jerseyProperties = SeedConfigurationUtils.buildPropertiesFromConfiguration(restConfiguration,
            "jersey.property");
    for (Object key : jerseyProperties.keySet()) {
        jerseyParameters.put(key.toString(), jerseyProperties.getProperty(key.toString()));
    }

    String baseRel = restConfiguration.getString("baseRel", "");
    String baseParam = restConfiguration.getString("baseParam", "");

    jsonHome = new JsonHome(baseRel, baseParam, scannedClassesBySpecification.get(resourcesSpecification));

    webPlugin.registerAdditionalModule(new RestModule(scannedClassesBySpecification.get(resourcesSpecification),
            scannedClassesBySpecification.get(providersSpecification), jerseyParameters,
            resourceFilterFactories, restPath, jspPath, jsonHome));

    return InitState.INITIALIZED;
}

From source file:com.nike.cerberus.server.config.guice.CmsGuiceModule.java

@Override
protected void configure() {
    loadEnvProperties();//from ww  w .j a v  a2  s .  co  m

    bind(UrlResolver.class).to(CmsVaultUrlResolver.class);
    bind(VaultCredentialsProvider.class).to(CmsVaultCredentialsProvider.class);
    bind(ObjectMapper.class).toInstance(objectMapper);

    String className = this.appConfig.getString(AUTH_CONNECTOR_IMPL_KEY);
    try {
        Class<?> clazz = Class.forName(className);
        bind(AuthConnector.class).to(clazz.asSubclass(AuthConnector.class)).asEagerSingleton();
    } catch (ClassNotFoundException nfe) {
        throw new IllegalArgumentException("invalid class: " + className, nfe);
    } catch (ClassCastException cce) {
        throw new IllegalArgumentException("class: " + className + " is the wrong type", cce);
    }
}

From source file:com.ctriposs.rest4j.internal.server.model.ResourceModelEncoder.java

private static String buildDataSchemaType(final Class<?> type, final DataSchema dataSchema) {
    final DataSchema schemaToEncode;
    if (dataSchema instanceof TyperefDataSchema) {
        return ((TyperefDataSchema) dataSchema).getFullName();
    } else if (dataSchema instanceof PrimitiveDataSchema || dataSchema instanceof NamedDataSchema) {
        return dataSchema.getUnionMemberKey();
    } else if (dataSchema instanceof UnionDataSchema && HasTyperefInfo.class.isAssignableFrom(type)) {
        final TyperefInfo unionRef = DataTemplateUtil.getTyperefInfo(type.asSubclass(DataTemplate.class));
        schemaToEncode = unionRef.getSchema();
    } else {/* w w  w  .ja  v  a2 s  .com*/
        schemaToEncode = dataSchema;
    }

    JsonBuilder builder = null;
    try {
        builder = new JsonBuilder(JsonBuilder.Pretty.SPACES);
        final SchemaToJsonEncoder encoder = new NamedSchemaReferencingJsonEncoder(builder);
        encoder.encode(schemaToEncode);
        return builder.result();
    } catch (IOException e) {
        throw new Rest4JInternalException("could not encode schema for '" + type.getName() + "'", e);
    } finally {
        if (builder != null) {
            builder.closeQuietly();
        }
    }
}

From source file:com.mindquarry.persistence.mock.SessionMock.java

private Class<? extends EntityBase> validateEntityClass(Class<?> clazz) {
    assert isConfiguredEntityClazz(clazz) : clazz + " is not "
            + "configured as entity class within mindquarry-persistence.xml";
    return clazz.asSubclass(EntityBase.class);
}

From source file:org.apache.hadoop.hbase.regionserver.AssistantStore.java

private <U> Class<? extends U> getClass(String name, Class<U> xface) {
    try {/*  w w w  .ja  v a2  s  .co  m*/
        Class<?> theClass = Class.forName(name);
        if (theClass != null && !xface.isAssignableFrom(theClass))
            throw new RuntimeException(theClass + " not " + xface.getName());
        else if (theClass != null)
            return theClass.asSubclass(xface);
        else
            return null;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.nullschool.grains.jackson.datatype.GrainsAnnotationIntrospector.java

@Override
public Object findSerializer(Annotated annotated) {
    Class<?> clazz = annotated.getRawType();

    if (Grain.class.isAssignableFrom(clazz)) {
        JsonSerializer serializer = serializerMemos.get(clazz);
        if (serializer == null) {
            // No serializer found, so try finding one using the "public interface" of the grain.
            Class<?> grainClass = TypeTools.publicInterfaceOf(clazz);
            serializer = serializerMemos.get(grainClass);
            if (serializer == null) {
                // No serializer found for public interface either, so make a new one.
                serializer = new GrainSerializer(grainClass.asSubclass(Grain.class));
            }//from   www .  j  a  v  a2 s.  c  o  m
            synchronized (this) {
                // It's okay to have a race condition where two threads create the same serializer twice. We
                // simply want to avoid serializer construction upon every invocation of findSerializer.
                serializerMemos = new HashMap<>(serializerMemos);
                serializerMemos.put(grainClass, serializer);
                serializerMemos.put(clazz, serializer);
            }
        }
        return serializer;
    }

    return null;
}

From source file:com.google.walkaround.util.server.flags.JsonFlags.java

@VisibleForTesting
@SuppressWarnings("unchecked")
static Object parseOneFlag(FlagDeclaration decl, JSONObject json) throws FlagFormatException {
    String key = decl.getName();/*from w  w w .j a va 2 s  . co m*/
    Class<?> type = decl.getType();
    try {
        if (!json.has(key)) {
            throw new FlagFormatException("Missing flag: " + key);
        }
        // Explicit check, otherwise null would be interpreted as "null" (the
        // string) for string and enum values.
        if (json.isNull(key)) {
            throw new FlagFormatException("Null value for key " + key);
        }

        if (type == String.class) {
            return json.getString(key);
        } else if (type == Boolean.class) {
            return Boolean.valueOf(json.getBoolean(key));
        } else if (type == Integer.class) {
            int val = json.getInt(key);
            if (val != json.getDouble(key)) {
                throw new FlagFormatException(
                        "Loss of precision for type int, key=" + key + ", value=" + json.getDouble(key));
            }
            return Integer.valueOf(val);
        } else if (type == Double.class) {
            return Double.valueOf(json.getDouble(key));
        } else if (type.isEnum()) {
            // TODO(ohler): Avoid unchecked warning here, the rest of the method should be clean.
            return parseEnumValue(type.asSubclass(Enum.class), key, json.getString(key).toUpperCase());
        } else {
            throw new IllegalArgumentException("Unknown flag type " + type.getName());
        }
    } catch (JSONException e) {
        throw new FlagFormatException(
                "Invalid flag JSON for key " + key + " (possibly a bad type); map=" + json, e);
    }
}