Example usage for java.lang Class getCanonicalName

List of usage examples for java.lang Class getCanonicalName

Introduction

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

Prototype

public String getCanonicalName() 

Source Link

Document

Returns the canonical name of the underlying class as defined by the Java Language Specification.

Usage

From source file:com.vertica.hivestoragehandler.VerticaOutputFormat.java

/**
 * Given a class, initializes it and returns it. If the class is a subclass of
 * @{link AbstractVerticaOutputCommitter}, then the constructor that takes a
 * @{link VerticaOutputFormat} object will be used. Alternatively, the class can implement
 * @{link OutputCommitter} directly./*from  ww w . j  av  a 2s  .  c  om*/
 * @param outputCommitterClass
 * @param configuration
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private OutputCommitter initializeOutputCommitter(Class outputCommitterClass, Configuration configuration)
        throws IOException {
    // If class extends AbstractVerticaOutputCommitter, create one of those
    // else it needs to be an instance of OutputCommitter
    // else throw exception
    if (VerticaTaskOutputCommitter.class.isAssignableFrom(outputCommitterClass)) {

        // iterate through the constructors to find the one we're looking for
        for (Constructor constructor : outputCommitterClass.getDeclaredConstructors()) {
            if (constructor.getGenericParameterTypes().length == 1
                    && constructor.getGenericParameterTypes()[0].equals(VerticaOutputFormat.class)) {
                try {
                    return (OutputCommitter) constructor.newInstance(this);
                } catch (Exception e) {
                    throw new IOException("Could not initialize OutputCommitter class "
                            + outputCommitterClass.getCanonicalName(), e);
                }
            }
        }

        throw new IOException("Implementation of AbstractVerticaOutputCommitter must "
                + "have a constructor that takes a VerticaOutputFormat object");
    } else if (OutputCommitter.class.isAssignableFrom(outputCommitterClass)) {
        return (OutputCommitter) ReflectionUtils.newInstance(outputCommitterClass, configuration);
    }

    throw new IOException(String.format("Configured output committer class %s must implement %s",
            outputCommitterClass.getCanonicalName(), OutputCommitter.class.getCanonicalName()));
}

From source file:ca.uhn.fhir.context.ModelScanner.java

private void scan(Class<? extends IBase> theClass) throws ConfigurationException {
    BaseRuntimeElementDefinition<?> existingDef = myClassToElementDefinitions.get(theClass);
    if (existingDef != null) {
        return;// ww  w  .  ja v a2s .  c  o  m
    }

    ResourceDef resourceDefinition = pullAnnotation(theClass, ResourceDef.class);
    if (resourceDefinition != null) {
        if (!IBaseResource.class.isAssignableFrom(theClass)) {
            throw new ConfigurationException("Resource type contains a @" + ResourceDef.class.getSimpleName()
                    + " annotation but does not implement " + IResource.class.getCanonicalName() + ": "
                    + theClass.getCanonicalName());
        }
        @SuppressWarnings("unchecked")
        Class<? extends IBaseResource> resClass = (Class<? extends IBaseResource>) theClass;
        scanResource(resClass, resourceDefinition);
        return;
    }

    DatatypeDef datatypeDefinition = pullAnnotation(theClass, DatatypeDef.class);
    if (datatypeDefinition != null) {
        if (ICompositeType.class.isAssignableFrom(theClass)) {
            @SuppressWarnings("unchecked")
            Class<? extends ICompositeType> resClass = (Class<? extends ICompositeType>) theClass;
            scanCompositeDatatype(resClass, datatypeDefinition);
        } else if (IPrimitiveType.class.isAssignableFrom(theClass)) {
            @SuppressWarnings({ "unchecked" })
            Class<? extends IPrimitiveType<?>> resClass = (Class<? extends IPrimitiveType<?>>) theClass;
            scanPrimitiveDatatype(resClass, datatypeDefinition);
        }

        return;
    }

    Block blockDefinition = pullAnnotation(theClass, Block.class);

    if (blockDefinition != null) {
        if (IResourceBlock.class.isAssignableFrom(theClass)
                || IBaseBackboneElement.class.isAssignableFrom(theClass)
                || IBaseDatatypeElement.class.isAssignableFrom(theClass)) {
            scanBlock(theClass);
        } else {
            throw new ConfigurationException(
                    "Type contains a @" + Block.class.getSimpleName() + " annotation but does not implement "
                            + IResourceBlock.class.getCanonicalName() + ": " + theClass.getCanonicalName());
        }
    }

    if (blockDefinition == null && datatypeDefinition == null && resourceDefinition == null) {
        throw new ConfigurationException(
                "Resource class[" + theClass.getName() + "] does not contain any valid HAPI-FHIR annotations");
    }
}

From source file:com.strandls.alchemy.rest.client.stubgenerator.RestProxyGenerator.java

/**
 * @return the rest webservice classes to process.
 * @throws MalformedURLException//  ww w.j a  v a2s  .  co  m
 */
private Set<Class<?>> findServiceClasses() {
    final List<Object> params = new ArrayList<Object>();
    final ClassLoader loader = getClass().getClassLoader();
    if (loader instanceof AntClassLoader) {
        final String[] path = ((AntClassLoader) loader).getClasspath()
                .split(System.getProperty("path.separator"));
        for (final String string : path) {
            try {
                params.add(new URL(string));
            } catch (final MalformedURLException e) {
                try {
                    params.add(new URL("file://" + string));
                } catch (final MalformedURLException e1) {
                    throw new RuntimeException(e1);
                }
            }
        }

    }

    final Reflections reflections = new Reflections(params.toArray(new Object[0]));
    final Set<Class<?>> allRestServices = reflections.getTypesAnnotatedWith(Path.class);
    log("Locating service classes", Project.MSG_ERR);

    final Set<Class<?>> filtered = Sets.filter(allRestServices, new Predicate<Class<?>>() {
        @Override
        public boolean apply(final Class<?> input) {
            return doesMatch(input, includes) && !doesMatch(input, excludes);
        }

        /**
         * Indicates if the input class matches any one of the comma
         * separated regex patterns.
         *
         * <code>null</code> or empty pattern implies no match.
         *
         * @param input
         *            the input class.
         * @param patterns
         *            comma separated list of patterns.
         *
         * @return <code>true</code> if any one of the pattern matches the
         *         canonical name of the class.
         */
        private boolean doesMatch(final Class<?> input, final String patterns) {
            boolean matches = false;
            if (patterns != null) {
                for (final String include : patterns.split("\\s*,\\s*")) {
                    matches |= Pattern.matches(include, input.getCanonicalName());
                }
            }
            return matches;
        }
    });

    for (final Class<?> klass : filtered) {
        log("Will process class: " + klass.getCanonicalName(), Project.MSG_ERR);
    }

    return filtered;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> T findFirst(Class<T> clazz) throws Exception {
    T res = null;// ww  w . j  a  v a  2  s .c o  m
    List<T> list = null;

    testClazz(clazz);

    String query = "SELECT o FROM " + clazz.getCanonicalName() + " o";
    res = findFirst(clazz, query);

    return res;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> List<T> findAll(Class<T> clazz, String orderBy) throws Exception {
    List<T> res = new ArrayList<T>();

    testClazz(clazz);//from   w  w w .j  a  va  2s .c om

    String query = "SELECT o FROM " + clazz.getCanonicalName() + " o";
    if (StringUtils.isNotEmpty(orderBy)) {
        query = query + " ORDER BY " + orderBy;
    }

    res = findBy(clazz, query);

    return res;
}

From source file:edu.ku.brc.specify.tasks.subpane.security.SecurityAdminPane.java

/**
 * Creates an info sub panel for a given object type and adds it to the card layout panel.
 *   /*from  www  .  j a v a  2s.c o m*/
 * @param clazz used to get the class name which is the key into the infoSubPanels map.
 */
private void createBlankInfoSubPanel(final Class<?> clazz, final JPanel panel) {
    AdminInfoSubPanelWrapper panelWrapper = new AdminInfoSubPanelWrapper(panel);
    infoCards.add(panel, clazz.getCanonicalName());
    infoSubPanels.put(clazz.getCanonicalName(), panelWrapper);
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

private MongoClient client() {
    mutex.lock();/*from   w w  w  .j  a  va 2 s.  c o m*/
    try {
        if (__client == null) {
            final MongoClientOptions options = MongoClientOptions.builder()
                    .readPreference(ReadPreference.nearest()).writeConcern(WriteConcern.ACKNOWLEDGED).build();
            final Splitter splitter = on(':').trimResults().omitEmptyStrings().limit(2);
            final List<ServerAddress> seeds = from(CONFIG_MANAGER.getDbHosts())
                    .transform(new Function<String, ServerAddress>() {
                        @Override
                        public ServerAddress apply(final String entry) {
                            ServerAddress seed = null;
                            try {
                                final List<String> tokens = splitter.splitToList(entry);
                                switch (tokens.size()) {
                                case 1:
                                    seed = new ServerAddress(tokens.get(0), 27017);
                                    break;
                                case 2:
                                    int port = parseInt(tokens.get(1));
                                    seed = new ServerAddress(tokens.get(0), port);
                                    break;
                                default:
                                    break;
                                }
                            } catch (Exception e) {
                                LOGGER.error("Invalid host", e);
                            }
                            return seed;
                        }
                    }).filter(notNull()).toList();
            // enable/disable authentication (requires MongoDB server to be configured to support authentication)
            final List<MongoCredential> credentials = newArrayList();
            if (!CONFIG_MANAGER.isAnonymousDbAccess()) {
                credentials.add(createMongoCRCredential(CONFIG_MANAGER.getDbUsername(),
                        CONFIG_MANAGER.getDbName(), CONFIG_MANAGER.getDbPassword().toCharArray()));
            }
            __client = new MongoClient(seeds, credentials, options);
            // check class attributes accessed by reflection
            try {
                final Field metadataField = BaseFile.class.getDeclaredField(METADATA_ATTR);
                checkNotNull(metadataField, "Metadata property (" + METADATA_ATTR + ") not found in file base: "
                        + BaseFile.class.getCanonicalName());
                final Class<?> metadataType = metadataField.getType();
                checkState(Versionable.class.isAssignableFrom(metadataType),
                        "Metadata does not implements versionable: " + metadataType.getCanonicalName());
                checkNotNull(Versionable.class.getDeclaredField(IS_LATEST_VERSION_ATTR),
                        "Version property (" + IS_LATEST_VERSION_ATTR + ") not found in versionable: "
                                + Versionable.class.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_LINK_ATTR),
                        "Open access link property (" + OPEN_ACCESS_LINK_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
                checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_DATE_ATTR),
                        "Open access date property (" + OPEN_ACCESS_DATE_ATTR + ") not found in metadata: "
                                + metadataType.getCanonicalName());
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Object versioning needs a compatible version of the LVL core library, but none is available",
                        e);
            }
        }
        return __client;
    } finally {
        mutex.unlock();
    }
}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Find a single value based on the given model, from arbitrary SQL, and
 * use the cache./* w ww  . j  a  v  a 2 s . c  om*/
 *
 * @param model
 * @param sql
 * @param params
 * @param <T>
 * @return
 */
public <T> T cachedScalar(Class model, String sql, Object... params) {
    String cacheKey = buildCacheKey(model, sql, params);
    T result = (T) SmartQueryCache.getSmart(model.getCanonicalName(), cacheKey);
    if (result != null) {
        return result;
    }
    QueryRunner runner = new QueryRunner(dataSource);
    try {
        result = runner.query(sql, new ScalarHandler<T>(), params);
        SmartQueryCache.set(model.getCanonicalName(), cacheKey, result);
        return result;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Find a list of objects via arbitrary SQL, checking the cache first, and storing to the
 * cache if retrieved fromt he database.
 *
 * @param model/*from  w w w  .j  a  v a 2s . c o m*/
 * @param sql
 * @param args
 * @param <T>
 * @return
 */
public <T extends Model> List<T> cachedQuery(Class<T> model, String sql, Object... args) {
    String cacheKey = buildCacheKey(model, sql, args);
    Object result = SmartQueryCache.getSmart(model.getCanonicalName(), cacheKey);
    if (result != null) {
        return (List<T>) result;
    }
    QueryRunner runner = new QueryRunner(dataSource);
    List<T> items = list();
    try {
        Schema schema = getSchemaForModelClass(model);
        if (!emptyInstance(schema)) {
            ModelListHandler<T> handler = new ModelListHandler<T>(schema);
            items = runner.query(sql, handler, args);
        } else {
            BeanListHandler<T> handler = new BeanListHandler(model);
            items = runner.query(sql, handler, args);
        }
        SmartQueryCache.set(model.getCanonicalName(), cacheKey, items);
        return items;
    } catch (SQLException e) {
        SmartQueryCache.set(model.getCanonicalName(), cacheKey, items);
        throw new RuntimeException(e);
    }
}