Example usage for java.lang Class getPackage

List of usage examples for java.lang Class getPackage

Introduction

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

Prototype

public Package getPackage() 

Source Link

Document

Gets the package of this class.

Usage

From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java

/**
 * Generates and returns source code for importing packages that are
 * required by the persister helper this class is generating.
 * /*  w  w w .j  a  v a2 s . c  om*/
 * @param visitedClass
 *            The {@link SPObject} class that is being visited by the
 *            annotation processor.
 * @param constructorImports
 *            The {@link Set} of packages that visitedClass uses in its
 *            {@link Constructor} annotated constructor and need to be
 *            imported.
 * @param mutatorImports
 *            The {@link Multimap} of setter methods to packages that
 *            visitedClass uses in its {@link Mutator} annotated methods and
 *            needs to be imported.
 * @return The source code for the generated imports.
 */
private String generateImports(Class<? extends SPObject> visitedClass, Set<String> constructorImports,
        Multimap<String, String> mutatorImports) {
    final String helperPackage = visitedClass.getPackage().getName() + "."
            + PersisterHelperFinder.GENERATED_PACKAGE_NAME;

    // Using a TreeSet here to sort imports alphabetically.
    Set<String> allImports = new TreeSet<String>();
    if (!Modifier.isAbstract(visitedClass.getModifiers())) {
        allImports.addAll(constructorImports);
    }
    allImports.addAll(mutatorImports.values());

    StringBuilder sb = new StringBuilder();

    // XXX Need to import any additional classes this generated persister helper
    // class requires, aside from those needed in visitedClass.
    allImports.add(List.class.getName());
    allImports.add(visitedClass.getName());
    allImports.add(SPPersistenceException.class.getName());
    allImports.add(SPPersister.class.getName());
    allImports.add(SessionPersisterSuperConverter.class.getName());
    allImports.add(SPObject.class.getName());
    allImports.add(DataType.class.getName());
    allImports.addAll(importedClassNames);

    for (String pkg : allImports) {
        // No need to import java.lang as it is automatically imported.
        // No need to import package if the persister helper is already
        // in the package.
        // Also want to keep array classes out
        if (!pkg.startsWith("java.lang") && !pkg.startsWith("[L")) {
            // Nested classes, enums, etc. will be separated by the "$"
            // character but we need to change them to "." so it can be
            // imported correctly.
            String pkgName = pkg.replaceAll("\\$", ".");

            // Only import the package if it is not the same one
            // that the persister helper exists in.
            int index = pkgName.lastIndexOf(".");
            if (index == -1) {
                index = pkgName.length();
            }
            if (!pkgName.substring(0, index).equals(helperPackage)) {
                niprintln(sb, "import " + pkgName + ";");
            }
        }
    }

    return sb.toString();
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * /* w w w  .  j a  va  2 s .  c  om*/
 * 
 * @param sqlId
 *            SQLID
 * @param bindParams
 *            sql parameter
 * @param bean
 *            bean class of result
 * 
 * @return List<Map<String, Object>> result
 * @throws NoSuchMethodException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws SecurityException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T executeForBean(String sqlId, Map<String, Object> bindParams, Class bean)
        throws SecurityException, IllegalAccessException, InstantiationException, NoSuchMethodException {
    getDbObject();
    int pointer = context.getResources().getIdentifier(sqlId, "string", context.getPackageName());
    if (pointer == 0) {
        Log.e(TAG, "undefined sql id : " + sqlId);
        return null;
    }
    String sql = context.getResources().getString(pointer);
    if (bindParams != null) {
        Iterator<String> mapIterator = bindParams.keySet().iterator();
        while (mapIterator.hasNext()) {
            String key = mapIterator.next();
            Object value = bindParams.get(key);
            sql = getFinalSql(sql, key.toLowerCase(), value.toString());
        }
    }
    if (sql.indexOf('#') != -1) {
        Log.e(TAG, "undefined parameter sql : " + sql);
        return null;
    }
    Cursor cursor = dbObj.rawQuery(sql, null);
    Log.d(TAG, "Run sql : " + sql);
    List<T> objectList = new ArrayList<T>();
    if (cursor == null) {
        return null;
    }

    T beanObj = null;
    // get bean class package
    Package beanPackage = bean.getPackage();
    while (cursor.moveToNext()) {
        int i = 0;

        beanObj = (T) parseToObject(bean, cursor);
        // objectList.add(beanObj) cursor.getString(i));
        i++;

        /*
         * JSONObject json = new JSONObject(map); try { beanObj =
         * (T)parse(json.toString(), bean, beanPackage.getName()); } catch
         * (Exception e) { Log.d(TAG, e.toString()); return null; }
         */
        objectList.add(beanObj);
    }
    if (objectList.size() <= 0) {
        return null;
    }
    cursor.close();
    dbObj.close();
    return objectList.get(0);
}

From source file:com.espertech.esper.event.EventAdapterServiceImpl.java

/**
 * Add an event type for the given Java class name.
 * @param eventTypeName is the name/*from   www . j a v  a  2  s.  c  o  m*/
 * @param fullyQualClassName is the Java class name
 * @return event type
 * @throws EventAdapterException if the Class name cannot resolve or other error occured
 */
public synchronized EventType addBeanType(String eventTypeName, String fullyQualClassName,
        boolean considerAutoName, boolean isPreconfiguredStatic, boolean isPreconfigured, boolean isConfigured)
        throws EventAdapterException {
    if (log.isDebugEnabled()) {
        log.debug(".addBeanType Adding " + eventTypeName + " for type " + fullyQualClassName);
    }

    EventType existingType = nameToTypeMap.get(eventTypeName);
    if (existingType != null) {
        if ((existingType.getUnderlyingType().getName().equals(fullyQualClassName))
                || (existingType.getUnderlyingType().getSimpleName().equals(fullyQualClassName))) {
            if (log.isDebugEnabled()) {
                log.debug(".addBeanType Returning existing type for " + eventTypeName);
            }
            return existingType;
        }

        throw new EventAdapterException("Event type named '" + eventTypeName
                + "' has already been declared with differing underlying type information: Class "
                + existingType.getUnderlyingType().getName() + " versus " + fullyQualClassName);
    }

    // Try to resolve as a fully-qualified class name first
    Class clazz = null;
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        clazz = Class.forName(fullyQualClassName, true, cl);
    } catch (ClassNotFoundException ex) {
        if (!considerAutoName) {
            throw new EventAdapterException(
                    "Event type or class named '" + fullyQualClassName + "' was not found", ex);
        }

        // Attempt to resolve from auto-name packages
        for (String javaPackageName : javaPackageNames) {
            String generatedClassName = javaPackageName + "." + fullyQualClassName;
            try {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                Class resolvedClass = Class.forName(generatedClassName, true, cl);
                if (clazz != null) {
                    throw new EventAdapterException("Failed to resolve name '" + eventTypeName
                            + "', the class was ambigously found both in " + "package '"
                            + clazz.getPackage().getName() + "' and in " + "package '"
                            + resolvedClass.getPackage().getName() + "'", ex);
                }
                clazz = resolvedClass;
            } catch (ClassNotFoundException ex1) {
                // expected, class may not exists in all packages
            }
        }
        if (clazz == null) {
            throw new EventAdapterException(
                    "Event type or class named '" + fullyQualClassName + "' was not found", ex);
        }
    }

    EventType eventType = beanEventAdapter.createBeanType(eventTypeName, clazz, isPreconfiguredStatic,
            isPreconfigured, isConfigured);
    nameToTypeMap.put(eventTypeName, eventType);

    return eventType;
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanFactory.java

protected Object __wrapProxy(IProxyFactory proxyFactory, Object targetObject) {
    final Class<?> _targetClass = targetObject.getClass();
    ////from www . ja v a 2 s .  c o  m
    List<IProxy> _targetProxies = proxyFactory.getProxies(new IProxyFilter() {

        private boolean __doCheckAnnotation(Proxy targetProxyAnno) {
            // targetClass???true
            if (targetProxyAnno.annotation().length > 0) {
                for (Class<? extends Annotation> _annoClass : targetProxyAnno.annotation()) {
                    if (_targetClass.isAnnotationPresent(_annoClass)) {
                        return true;
                    }
                }
                return false;
            }
            return true;
        }

        public boolean filter(IProxy targetProxy) {
            CleanProxy _cleanProxy = _targetClass.getAnnotation(CleanProxy.class);
            if (_cleanProxy != null) {
                if (_cleanProxy.value().length > 0) {
                    for (Class<? extends IProxy> _proxyClass : _cleanProxy.value()) {
                        if (_proxyClass.equals(targetProxy.getClass())) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            }
            Proxy _targetProxyAnno = targetProxy.getClass().getAnnotation(Proxy.class);
            // 
            if (StringUtils.isNotBlank(_targetProxyAnno.packageScope())) {
                // ??
                if (!StringUtils.startsWith(_targetClass.getPackage().getName(),
                        _targetProxyAnno.packageScope())) {
                    return false;
                }
            }
            return __doCheckAnnotation(_targetProxyAnno);
        }
    });
    if (!_targetProxies.isEmpty()) {
        // ????????
        return ClassUtils.wrapper(targetObject)
                .duplicate(proxyFactory.createProxy(_targetClass, _targetProxies));
    }
    return targetObject;
}

From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.java

@SuppressWarnings("unchecked")
protected void buildConfiguration(Set<Class> classes) {
    Map<String, PackageConfig.Builder> packageConfigs = new HashMap<String, PackageConfig.Builder>();

    for (Class<?> actionClass : classes) {
        Actions actionsAnnotation = actionClass.getAnnotation(Actions.class);
        Action actionAnnotation = actionClass.getAnnotation(Action.class);

        // Skip classes that can't be instantiated
        if (cannotInstantiate(actionClass)) {
            if (LOG.isTraceEnabled())
                LOG.trace("Class [#0] did not pass the instantiation test and will be ignored",
                        actionClass.getName());
            continue;
        }// w ww .  ja va 2 s . c o m

        // Tell the ObjectFactory about this class
        try {
            objectFactory.getClassInstance(actionClass.getName());
        } catch (ClassNotFoundException e) {
            if (LOG.isErrorEnabled())
                LOG.error("Object Factory was unable to load class [#0]", e, actionClass.getName());
            throw new StrutsException("Object Factory was unable to load class " + actionClass.getName(), e);
        }

        // Determine the action package
        String actionPackage = actionClass.getPackage().getName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing class [#0] in package [#1]", actionClass.getName(), actionPackage);
        }

        // Determine the default namespace and action name
        List<String> namespaces = determineActionNamespace(actionClass);
        for (String namespace : namespaces) {
            String defaultActionName = determineActionName(actionClass);
            PackageConfig.Builder defaultPackageConfig = getPackageConfig(packageConfigs, namespace,
                    actionPackage, actionClass, null);

            // Verify that the annotations have no errors and also determine if the default action
            // configuration should still be built or not.
            Map<String, List<Action>> map = getActionAnnotations(actionClass);
            Set<String> actionNames = new HashSet<String>();
            boolean hasDefaultMethod = ReflectionTools.containsMethod(actionClass, DEFAULT_METHOD);
            if (!map.containsKey(DEFAULT_METHOD) && hasDefaultMethod && actionAnnotation == null
                    && actionsAnnotation == null && (alwaysMapExecute || map.isEmpty())) {
                boolean found = false;
                for (String method : map.keySet()) {
                    List<Action> actions = map.get(method);
                    for (Action action : actions) {

                        // Check if there are duplicate action names in the annotations.
                        String actionName = action.value().equals(Action.DEFAULT_VALUE) ? defaultActionName
                                : action.value();
                        if (actionNames.contains(actionName)) {
                            throw new ConfigurationException("The action class [" + actionClass
                                    + "] contains two methods with an action name annotation whose value "
                                    + "is the same (they both might be empty as well).");
                        } else {
                            actionNames.add(actionName);
                        }

                        // Check this annotation is the default action
                        if (action.value().equals(Action.DEFAULT_VALUE)) {
                            found = true;
                        }
                    }
                }

                // Build the default
                if (!found) {
                    createActionConfig(defaultPackageConfig, actionClass, defaultActionName, DEFAULT_METHOD,
                            null);
                }
            }

            // Build the actions for the annotations
            for (String method : map.keySet()) {
                List<Action> actions = map.get(method);
                for (Action action : actions) {
                    PackageConfig.Builder pkgCfg = defaultPackageConfig;
                    if (action.value().contains("/")) {
                        pkgCfg = getPackageConfig(packageConfigs, namespace, actionPackage, actionClass,
                                action);
                    }

                    createActionConfig(pkgCfg, actionClass, defaultActionName, method, action);
                }
            }

            // some actions will not have any @Action or a default method, like the rest actions
            // where the action mapper is the one that finds the right method at runtime
            if (map.isEmpty() && mapAllMatches && actionAnnotation == null && actionsAnnotation == null) {
                createActionConfig(defaultPackageConfig, actionClass, defaultActionName, null,
                        actionAnnotation);
            }

            //if there are @Actions or @Action at the class level, create the mappings for them
            String methodName = hasDefaultMethod ? DEFAULT_METHOD : null;
            if (actionsAnnotation != null) {
                List<Action> actionAnnotations = checkActionsAnnotation(actionsAnnotation);
                for (Action actionAnnotation2 : actionAnnotations)
                    createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName,
                            actionAnnotation2);
            } else if (actionAnnotation != null)
                createActionConfig(defaultPackageConfig, actionClass, defaultActionName, methodName,
                        actionAnnotation);
        }
    }

    buildIndexActions(packageConfigs);

    // Add the new actions to the configuration
    Set<String> packageNames = packageConfigs.keySet();
    for (String packageName : packageNames) {
        configuration.addPackageConfig(packageName, packageConfigs.get(packageName).build());
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

private static void application_activityStatusSwitch(Context context, Class appClass, int status) {
    ComponentName component = new ComponentName(appClass.getPackage().getName(), appClass.getName());

    if (status == PackageManager.COMPONENT_ENABLED_STATE_DISABLED && (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            || context.getPackageManager()
                    .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)) {
        context.getPackageManager().setComponentEnabledSetting(component,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

    } else if (status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED && (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            || context.getPackageManager()
                    .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)) {
        context.getPackageManager().setComponentEnabledSetting(component,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }/*  w  ww.j a v  a  2s .c  om*/
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Switches the component status of an Activity Alias. Use this to enable or disable it. If the
 * activity alias points to an Activity with android.intent.category.LAUNCHER intent, it will
 * remove/add the launcher icon in the applications menu.
 *
 * @param context           The application context
 * @param appClass          Class of the activity alias
 * @param appLaunchAlias    The android:name of the activity-alias entry in the manifest.
 *//*from w  w w  .  jav  a2  s  .com*/
public static void application_activityAliasSwitchStatus(Context context, Class appClass,
        String appLaunchAlias) {
    ComponentName component = new ComponentName(appClass.getPackage().getName(),
            appClass.getPackage().getName() + "." + appLaunchAlias);
    if (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
        application_activityAliasStatusSwitch(context, appClass, appLaunchAlias,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
    } else if (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
        application_activityAliasStatusSwitch(context, appClass, appLaunchAlias,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

private static void application_activityAliasStatusSwitch(Context context, Class appClass,
        String appLaunchAlias, int status) {
    ComponentName component = new ComponentName(appClass.getPackage().getName(),
            appClass.getPackage().getName() + "." + appLaunchAlias);

    if (status == PackageManager.COMPONENT_ENABLED_STATE_DISABLED && (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
            || context.getPackageManager()
                    .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)) {
        context.getPackageManager().setComponentEnabledSetting(component,
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

    } else if (status == PackageManager.COMPONENT_ENABLED_STATE_ENABLED && (context.getPackageManager()
            .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
            || context.getPackageManager()
                    .getComponentEnabledSetting(component) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)) {
        context.getPackageManager().setComponentEnabledSetting(component,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }/*from   w w w.  jav  a 2  s  . c  o m*/
}

From source file:de.innovationgate.utils.WGUtils.java

/**
 * Return the path of the given classes package, that must be used when loading resources from it
 * This returns the name of the package of the given class, converted to a resource path. You can use
 * the returned path to load non-class resources from the package folder.
 * @param clazz The class whose package is used
 *///from   w  w  w. jav a  2 s  .  c o  m
public static String getPackagePath(Class<? extends Object> clazz) {
    return WGUtils.strReplace(clazz.getPackage().getName(), ".", "/", true);
}

From source file:org.cloudgraph.store.mapping.StoreMapping.java

private CloudGraphStoreMapping deriveMapping() throws NoSuchFieldException, SecurityException {
    if (log.isDebugEnabled())
        log.debug("deriving mapping");
    CloudGraphStoreMapping result = new CloudGraphStoreMapping();
    for (Class<?> c : this.annotatedClasses) {
        org.cloudgraph.store.mapping.annotation.Table tableAnnot = c
                .getAnnotation(org.cloudgraph.store.mapping.annotation.Table.class);
        if (log.isDebugEnabled())
            log.debug("discovered " + tableAnnot.name() + " table mapping");
        Table table = new Table();
        result.getTables().add(table);/*w w  w  . j a va 2s  .c o m*/
        table.setName(tableAnnot.name());
        table.setDataColumnFamilyName(tableAnnot.dataColumnFamilyName());
        table.setTombstoneRows(tableAnnot.tombstoneRows());
        table.setTombstoneRowsOverwriteable(tableAnnot.tombstoneRowsOverwriteable());
        table.setUniqueChecks(tableAnnot.uniqueChecks());
        if (tableAnnot.hashAlgorithm().ordinal() != HashAlgorithmName.NONE.ordinal()) {
            HashAlgorithm hash = new HashAlgorithm();
            hash.setName(tableAnnot.hashAlgorithm());
            table.setHashAlgorithm(hash);
        }
        // add properties

        DataGraph dataGraph = new DataGraph();
        table.getDataGraphs().add(dataGraph);
        org.plasma.sdo.annotation.Type typeAnnot = c.getAnnotation(org.plasma.sdo.annotation.Type.class);

        String typeName = typeAnnot.name();
        if (typeName == null || typeName.trim().length() == 0)
            typeName = c.getSimpleName(); // use the enumeration class name
        dataGraph.setType(typeName);
        org.plasma.sdo.annotation.Namespace namespaceAnnot = c.getPackage()
                .getAnnotation(org.plasma.sdo.annotation.Namespace.class);
        dataGraph.setUri(namespaceAnnot.uri());
        if (log.isDebugEnabled())
            log.debug("added data graph for type: " + dataGraph.getUri() + "#" + dataGraph.getType());

        ColumnKeyModel columnModel = new ColumnKeyModel();
        columnModel.setFieldDelimiter("|");
        columnModel.setReferenceMetadataDelimiter("#");
        columnModel.setSequenceDelimiter("@");
        dataGraph.setColumnKeyModel(columnModel);
        ColumnKeyField pkgColKeyField = new ColumnKeyField();
        pkgColKeyField.setName(MetaFieldName.PKG);
        columnModel.getColumnKeyFields().add(pkgColKeyField);
        ColumnKeyField typeColKeyField = new ColumnKeyField();
        typeColKeyField.setName(MetaFieldName.TYPE);
        columnModel.getColumnKeyFields().add(typeColKeyField);
        ColumnKeyField propColKeyField = new ColumnKeyField();
        propColKeyField.setName(MetaFieldName.PROPERTY);
        columnModel.getColumnKeyFields().add(propColKeyField);

        RowKeyModel rowKeyModel = new RowKeyModel();
        dataGraph.setRowKeyModel(rowKeyModel);
        rowKeyModel.setFieldDelimiter(tableAnnot.rowKeyFieldDelimiter());

        for (Object o : c.getEnumConstants()) {
            Enum<?> enm = (Enum<?>) o;
            Field field = c.getField(enm.name());
            org.cloudgraph.store.mapping.annotation.RowKeyField rowKeyFieldAnnot = field
                    .getAnnotation(org.cloudgraph.store.mapping.annotation.RowKeyField.class);
            if (rowKeyFieldAnnot != null) {
                RowKeyField rowKeyField = new RowKeyField();
                rowKeyModel.getRowKeyFields().add(rowKeyField);
                DataField userDefinedField = new DataField();
                rowKeyField.setDataField(userDefinedField);
                userDefinedField.setPath(field.getName());

                userDefinedField.setCodecType(rowKeyFieldAnnot.codecType());
            }
        }

    }

    return result;
}