Java 类org.apache.commons.lang.ClassUtils 实例源码

项目:sstore-soft    文件:ClassUtil.java   
/**
 * Get a set of all of the interfaces that the element_class implements
 * 
 * @param element_class
 * @return
 */
@SuppressWarnings("unchecked")
public static Collection<Class<?>> getInterfaces(Class<?> element_class) {
    Set<Class<?>> ret = ClassUtil.CACHE_getInterfaceClasses.get(element_class);
    if (ret == null) {
        // ret = new HashSet<Class<?>>();
        // Queue<Class<?>> queue = new LinkedList<Class<?>>();
        // queue.add(element_class);
        // while (!queue.isEmpty()) {
        // Class<?> current = queue.poll();
        // for (Class<?> i : current.getInterfaces()) {
        // ret.add(i);
        // queue.add(i);
        // } // FOR
        // } // WHILE
        ret = new HashSet<Class<?>>(ClassUtils.getAllInterfaces(element_class));
        if (element_class.isInterface())
            ret.add(element_class);
        ret = Collections.unmodifiableSet(ret);
        ClassUtil.CACHE_getInterfaceClasses.put(element_class, ret);
    }
    return (ret);
}
项目:canal-elasticsearch    文件:TotoroBootStrap.java   
public TotoroBootStrap(final Properties conf) throws UnknownHostException {

        CanalConf canalConf = getCanalConf(conf);
        EsConf esConf = getEsConf(conf);
        int transThreadNum = getTransThreadNum(conf);
        //totoroSelector需要提前初始化好
        totoroSelector = new CanalEmbedSelector(canalConf);
        //初始化 Channel
        initChannel();
        //初始化 SelectorTask
        SelectorTask selectorTask = initSelectorTask();
        //初始化 TransFormTask
        TransFormTask transFormTask = initTransFormTask(canalConf, transThreadNum);
        //初始化 ConsumerTask
        ConsumerTask consumerTask = initConsumerTask(esConf);

        taskMap.put(ClassUtils.getShortClassName(SelectorTask.class), selectorTask);
        taskMap.put(ClassUtils.getShortClassName(TransFormTask.class), transFormTask);
        taskMap.put(ClassUtils.getShortClassName(ConsumerTask.class), consumerTask);


        logger.info("Totoro init complete .......");
    }
项目:s-store    文件:ClassUtil.java   
/**
 * Get a set of all of the interfaces that the element_class implements
 * 
 * @param element_class
 * @return
 */
@SuppressWarnings("unchecked")
public static Collection<Class<?>> getInterfaces(Class<?> element_class) {
    Set<Class<?>> ret = ClassUtil.CACHE_getInterfaceClasses.get(element_class);
    if (ret == null) {
        // ret = new HashSet<Class<?>>();
        // Queue<Class<?>> queue = new LinkedList<Class<?>>();
        // queue.add(element_class);
        // while (!queue.isEmpty()) {
        // Class<?> current = queue.poll();
        // for (Class<?> i : current.getInterfaces()) {
        // ret.add(i);
        // queue.add(i);
        // } // FOR
        // } // WHILE
        ret = new HashSet<Class<?>>(ClassUtils.getAllInterfaces(element_class));
        if (element_class.isInterface())
            ret.add(element_class);
        ret = Collections.unmodifiableSet(ret);
        ClassUtil.CACHE_getInterfaceClasses.put(element_class, ret);
    }
    return (ret);
}
项目:lams    文件:MemberUtils.java   
/**
 * Get the number of steps required to promote a primitive number to another
 * type.
 * @param srcClass the (primitive) source class
 * @param destClass the (primitive) destination class
 * @return The cost of promoting the primitive
 */
private static float getPrimitivePromotionCost(final Class srcClass, final Class destClass) {
    float cost = 0.0f;
    Class cls = srcClass;
    if (!cls.isPrimitive()) {
        // slight unwrapping penalty
        cost += 0.1f;
        cls = ClassUtils.wrapperToPrimitive(cls);
    }
    for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
        if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
            cost += 0.1f;
            if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
                cls = ORDERED_PRIMITIVE_TYPES[i + 1];
            }
        }
    }
    return cost;
}
项目:lams    文件:ReflectionToStringBuilder.java   
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Reject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
        && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
项目:otter-G    文件:LogInterceptor.java   
/**
 * 记录请求信息
 * 
 * @param methodInvocation
 * @param take
 */
private void dump(MethodInvocation methodInvocation, Object result, long take) {
    // 取得日志打印对象
    Logger log = getLogger(methodInvocation.getMethod().getDeclaringClass());
    Object[] args = methodInvocation.getArguments();
    StringBuffer buffer = getArgsString(args);

    if (log.isInfoEnabled()) {
        String className = ClassUtils.getShortClassName(methodInvocation.getMethod().getDeclaringClass());
        String methodName = methodInvocation.getMethod().getName();
        String resultStr = getResultString(result);

        String now = new SimpleDateFormat(DATA_FORMAT).format(new Date());
        log.info(MessageFormat.format(MESSAGE, new Object[] { className, methodName, now, take, buffer.toString(),
                resultStr }));
    }
}
项目:otter-G    文件:RpcStageController.java   
/**
 * 将当前的符合条件的processIds和当前的reply queue进行校对,剔除不在processIds里的内容
 */
private synchronized void compareReply(List<Long> processIds, ReplyProcessQueue replyProcessIds) {
    Object[] replyIds = replyProcessIds.toArray();
    for (Object replyId : replyIds) {
        if (processIds.contains((Long) replyId) == false) { // 判断reply id是否在当前processId列表中
            // 因为存在并发问题,如在执行Listener事件的同时,可能触发了process的创建,这时新建的processId会进入到reply队列中
            // 此时接受到的processIds变量为上一个版本的内容,所以会删除新建的process,导致整个通道被挂住
            if (CollectionUtils.isEmpty(processIds) == false) {
                Long processId = processIds.get(0);
                if (processId > (Long) replyId) { // 如果当前最小的processId都大于replyId, processId都是递增创建的
                    logger.info("## {} remove reply id [{}]", ClassUtils.getShortClassName(this.getClass()),
                                (Long) replyId);
                    replyProcessIds.remove((Long) replyId);
                    progress.remove((Long) replyId);
                }
            }
        }
    }
}
项目:otter-G    文件:AbstractProcessListener.java   
/**
 * 将当前的符合条件的processIds和当前的reply queue进行校对,剔除不在processIds里的内容
 */
protected synchronized void compareReply(List<Long> processIds) {
    Object[] replyIds = replyProcessIds.toArray();
    for (Object replyId : replyIds) {
        if (processIds.contains((Long) replyId) == false) { // 判断reply id是否在当前processId列表中
            // 因为存在并发问题,如在执行Listener事件的同时,可能触发了process的创建,这时新建的processId会进入到reply队列中
            // 此时接受到的processIds变量为上一个版本的内容,所以会删除新建的process,导致整个通道被挂住
            if (CollectionUtils.isEmpty(processIds) == false) {
                Long processId = processIds.get(0);
                if (processId > (Long) replyId) { // 如果当前最小的processId都大于replyId, processId都是递增创建的
                    logger.info("## {} remove reply id [{}]", ClassUtils.getShortClassName(this.getClass()),
                                (Long) replyId);
                    replyProcessIds.remove((Long) replyId);
                }
            }
        }
    }
}
项目:HTAPBench    文件:ClassUtil.java   
/**
     * Get a set of all of the interfaces that the element_class implements
     * @param element_class
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Collection<Class<?>> getInterfaces(Class<?> element_class) {
        Set<Class<?>> ret = ClassUtil.CACHE_getInterfaceClasses.get(element_class);
        if (ret == null) {
//            ret = new HashSet<Class<?>>();
//            Queue<Class<?>> queue = new LinkedList<Class<?>>();
//            queue.add(element_class);
//            while (!queue.isEmpty()) {
//                Class<?> current = queue.poll();
//                for (Class<?> i : current.getInterfaces()) {
//                    ret.add(i);
//                    queue.add(i);
//                } // FOR
//            } // WHILE
            ret = new HashSet<Class<?>>(ClassUtils.getAllInterfaces(element_class));
            if (element_class.isInterface()) ret.add(element_class);
            ret = Collections.unmodifiableSet(ret);
            ClassUtil.CACHE_getInterfaceClasses.put(element_class, ret);
        }
        return (ret);
    }
项目:ditb    文件:RegionServerCoprocessorHost.java   
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="BC_UNCONFIRMED_CAST",
    justification="Intentional; FB has trouble detecting isAssignableFrom")
public RegionServerEnvironment(final Class<?> implClass,
    final Coprocessor impl, final int priority, final int seq,
    final Configuration conf, final RegionServerServices services) {
  super(impl, priority, seq, conf);
  this.regionServerServices = services;
  for (Object itf : ClassUtils.getAllInterfaces(implClass)) {
    Class<?> c = (Class<?>) itf;
    if (SingletonCoprocessorService.class.isAssignableFrom(c)) {// FindBugs: BC_UNCONFIRMED_CAST
      this.regionServerServices.registerService(
        ((SingletonCoprocessorService) impl).getService());
      break;
    }
  }
}
项目:Blur    文件:TickMethodsCache.java   
private static TickMethod getTickMethod(Class clazz, Method method) {
    // Order of list is from bottom (subclass) to top (superclass).
    List<Class> superclasses = (List<Class>) ClassUtils.getAllSuperclasses(clazz);
    superclasses.add(0, clazz);
    // Loop over clazz and its superclasses
    for (Class superclass : superclasses) {
        // find and iterate over the current class' tick methods, if it has any.
        for (TickMethod tickMethod : CLASS_TICK_METHODS.get(superclass)) {
            // if the superclass TickMethod has the same method as ours, return it.
            if (ReflectionUtils.sameMethodSignature(method, tickMethod.method)) {
                return tickMethod;
            }
        }
    }
    return null;
}
项目:mycore    文件:MCRFunctionCallJava.java   
@Override
public Object call(Context context, List args) throws FunctionCallException {
    try {
        String clazzName = (String) (args.get(0));
        String methodName = (String) (args.get(1));
        LOGGER.info("XEditor extension function calling {} {}", clazzName, methodName);

        Class[] argTypes = new Class[args.size() - 2];
        Object[] params = new Object[args.size() - 2];
        for (int i = 0; i < argTypes.length; i++) {
            argTypes[i] = args.get(i + 2).getClass();
            params[i] = args.get(i + 2);
        }

        Class clazz = ClassUtils.getClass(clazzName);
        Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes);
        return method.invoke(null, params);
    } catch (Exception ex) {
        LOGGER.warn("Exception in call to external java method", ex);
        return ex.getMessage();
    }
}
项目:mycore    文件:MCRCommand.java   
public MCRCommand(Method cmd) {
    className = cmd.getDeclaringClass().getName();
    methodName = cmd.getName();
    parameterTypes = cmd.getParameterTypes();
    org.mycore.frontend.cli.annotation.MCRCommand cmdAnnotation = cmd
        .getAnnotation(org.mycore.frontend.cli.annotation.MCRCommand.class);
    help = cmdAnnotation.help();
    messageFormat = new MessageFormat(cmdAnnotation.syntax(), Locale.ROOT);
    setMethod(cmd);

    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> paramtype = parameterTypes[i];
        if (ClassUtils.isAssignable(paramtype, Integer.class, true)
            || ClassUtils.isAssignable(paramtype, Long.class, true)) {
            messageFormat.setFormat(i, NumberFormat.getIntegerInstance(Locale.ROOT));
        } else if (!String.class.isAssignableFrom(paramtype)) {
            unsupportedArgException(className + "." + methodName, paramtype.getName());
        }
    }

    int pos = cmdAnnotation.syntax().indexOf("{");
    suffix = pos == -1 ? cmdAnnotation.syntax() : cmdAnnotation.syntax().substring(0, pos);
}
项目:super-csv-declarative    文件:CsvDeclarativeBeanReader.java   
private <T> T populateBean(final T resultBean, List<Object> processedColumns, BeanCells cells) {
    for (int i = 0; i < processedColumns.size(); i++) {
        final Object fieldValue = processedColumns.get(i);

        BeanCell cell = cells.getCell(i);
        if (cell == null || cell.getType() == null) {
            continue;
        }

        // ClassUtils handles boxed types
        if (fieldValue != null && ClassUtils.isAssignable(fieldValue.getClass(), cell.getType(), true)) {
            cell.setValue(resultBean, fieldValue);
        } else {
            Class<?> fieldValueClass = fieldValue == null ? Object.class : fieldValue.getClass();
            TypeConverter<Object, Object> converter
                    = (TypeConverter<Object, Object>) typeConverterRegistry.getConverter(fieldValueClass, cell.getType());
            if (converter == null) {
                throw new SuperCsvException(Form.at("No converter registered from type {} to type {}. Add one or fix your CellProcessor-annotations to return the field's type",
                        fieldValueClass.getName(), cell.getType().getName()));
            }
            cell.setValue(resultBean, converter.convert(fieldValue));
        }
    }

    return resultBean;
}
项目:cuba    文件:KryoSerialization.java   
@Override
public Object read(Kryo kryo, Input input, Class type) {
    try {
        ObjectMap graphContext = kryo.getGraphContext();
        ObjectInputStream objectStream = (ObjectInputStream) graphContext.get(this);
        if (objectStream == null) {
            objectStream = new ObjectInputStream(input) {
                @Override
                protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    return ClassUtils.getClass(KryoSerialization.class.getClassLoader(), desc.getName());
                }
            };
            graphContext.put(this, objectStream);
        }
        return objectStream.readObject();
    } catch (Exception ex) {
        throw new KryoException("Error during Java deserialization.", ex);
    }
}
项目:cuba    文件:MetaModelLoader.java   
private boolean propertyBelongsTo(Field field, MetaProperty metaProperty, List<Class> systemInterfaces) {
    String getterName = "get" + StringUtils.capitalize(metaProperty.getName());

    Class<?> aClass = field.getDeclaringClass();
    //noinspection unchecked
    List<Class> allInterfaces = ClassUtils.getAllInterfaces(aClass);
    for (Class intf : allInterfaces) {
        Method[] methods = intf.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(getterName) && method.getParameterTypes().length == 0) {
                if (systemInterfaces.contains(intf))
                    return true;
            }
        }
    }
    return false;
}
项目:Blur    文件:TickMethodsCache.java   
private static TickMethod getTickMethod(Class clazz, Method method) {
    // Order of list is from bottom (subclass) to top (superclass).
    List<Class> superclasses = (List<Class>) ClassUtils.getAllSuperclasses(clazz);
    superclasses.add(0, clazz);
    // Loop over clazz and its superclasses
    for (Class superclass : superclasses) {
        // find and iterate over the current class' tick methods, if it has any.
        for (TickMethod tickMethod : CLASS_TICK_METHODS.get(superclass)) {
            // if the superclass TickMethod has the same method as ours, return it.
            if (ReflectionUtils.sameMethodSignature(method, tickMethod.method)) {
                return tickMethod;
            }
        }
    }
    return null;
}
项目:metaworks_framework    文件:AdminPermissionDaoImpl.java   
public boolean isUserQualifiedForOperationOnCeilingEntityViaDefaultPermissions(String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_BY_PERMISSION_AND_CEILING_ENTITY");
        query.setParameter("permissionNames", Arrays.asList(AdminSecurityService.DEFAULT_PERMISSIONS));
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:metaworks_framework    文件:AdminPermissionDaoImpl.java   
public boolean doesOperationExistForCeilingEntity(PermissionType permissionType, String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_PERMISSIONS_BY_TYPE_AND_CEILING_ENTITY");
        query.setParameter("type", permissionType.getType());
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:llamafur    文件:ReflectionUtils.java   
/**
 * Set a field of an object with a value, also if the field is of primitive type.
 * 
 * Apart from this, it mimics behavior from java.reflection.Field.set(Object, Object).
 */
public static void setFieldFromObject(Object object, Field field, Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (!field.getType().isPrimitive()) {
        field.set(object, value);
        return;
    }

    Class<?> primitiveClass = value.getClass();

    if (!primitiveClass.isPrimitive()) {
        primitiveClass = ClassUtils.wrapperToPrimitive(primitiveClass);
        if (primitiveClass == null) {
            throw new IllegalArgumentException(field + " is a primitive field but the value is neither primitive nor wrapper.");
        }
    }

    String assignerName = "set" + WordUtils.capitalize(primitiveClass.getSimpleName());

    Method assigner = Field.class.getMethod(assignerName, new Class<?>[] {Object.class, primitiveClass});
    assigner.invoke(field, new Object[] {object, value});

}
项目:kc-rice    文件:RichTable.java   
private String getSortType(Class<?> dataTypeClass) {
    String sortType = UifConstants.TableToolsValues.STRING;
    if (ClassUtils.isAssignable(dataTypeClass, KualiPercent.class)) {
        sortType = UifConstants.TableToolsValues.PERCENT;
    } else if (ClassUtils.isAssignable(dataTypeClass, KualiInteger.class) || ClassUtils.isAssignable(dataTypeClass,
            KualiDecimal.class)) {
        sortType = UifConstants.TableToolsValues.CURRENCY;
    } else if (ClassUtils.isAssignable(dataTypeClass, Timestamp.class)) {
        sortType = "date";
    } else if (ClassUtils.isAssignable(dataTypeClass, java.sql.Date.class) || ClassUtils.isAssignable(dataTypeClass,
            java.util.Date.class)) {
        sortType = UifConstants.TableToolsValues.DATE;
    } else if (ClassUtils.isAssignable(dataTypeClass, Number.class)) {
        sortType = UifConstants.TableToolsValues.NUMERIC;
    }
    return sortType;
}
项目:kc-rice    文件:WebRuleResponsibility.java   
private void injectWebMembers() throws Exception {
       DelegationRulesProxy delegationRulesProxy = new DelegationRulesProxy(getDelegationRules());
       Class delegationRulesClass = getDelegationRules().getClass();
       //System.err.println("delegation rules class: "+ delegationRulesClass);
       Class[] delegationRulesInterfaces = new Class[0]; // = delegationRulesClass.getInterfaces();
       List<Class> delegationRulesInterfaceList = (List<Class>) ClassUtils.getAllInterfaces(delegationRulesClass);
       delegationRulesInterfaces = delegationRulesInterfaceList.toArray(delegationRulesInterfaces);
       ClassLoader delegationRulesClassLoader = getDelegationRules().getClass().getClassLoader();
       Object o = Proxy.newProxyInstance(delegationRulesClassLoader, delegationRulesInterfaces, delegationRulesProxy);
       //setDelegationRules((List) o);

    if (Integer.parseInt(CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.RULE_DETAIL_TYPE, KewApiConstants.RULE_DELEGATE_LIMIT)) > getDelegationRules().size() || showDelegations) {
        for (Iterator iterator = getDelegationRules().iterator(); iterator.hasNext();) {
            RuleDelegationBo ruleDelegation = (RuleDelegationBo) iterator.next();
            WebRuleBaseValues webRule = new WebRuleBaseValues();
            webRule.load(ruleDelegation.getDelegationRule());
            webRule.edit(ruleDelegation.getDelegationRule());
            ruleDelegation.setDelegationRule(webRule);
        }
    }
}
项目:kc-rice    文件:AnnotationHelper.java   
private AnnotationExpr findAnnotation(final BodyDeclaration n, String fullyQualifiedName, boolean foundAnnImport) {
    final String simpleName = ClassUtils.getShortClassName(fullyQualifiedName);
    final List<AnnotationExpr> annotations = n.getAnnotations() != null ? n.getAnnotations() : new ArrayList<AnnotationExpr>();

    for (AnnotationExpr ae : annotations) {
        final String name = ae.getName().toString();
        if ((simpleName.equals(name) && foundAnnImport)) {
            LOG.info("found " + ae + " on " + getTypeOrFieldNameForMsg(n) + ".");
            return ae;
        }

        if (fullyQualifiedName.equals(name)) {
            LOG.info("found " + ae + " on " + getTypeOrFieldNameForMsg(n) + ".");
            return ae;
        }
    }
    return null;
}
项目:kc-rice    文件:AnnotationHelper.java   
private boolean imported(List<ImportDeclaration> imports, String fullyQualifiedName) {
    final String packageName = ClassUtils.getPackageName(fullyQualifiedName);

    for (final ImportDeclaration i : imports) {
        if (!i.isStatic()) {
            final String importName = i.getName().toString();
            if (i.isAsterisk()) {
                if (packageName.equals(importName)) {
                    if ( LOG.isDebugEnabled() ) {
                        LOG.debug("found import " + packageName + ".* on " + getTypeNameForMsg(i) + ".");
                    }
                    return true;
                }
            } else {
                if (fullyQualifiedName.equals(importName)) {
                    if ( LOG.isDebugEnabled() ) {
                        LOG.debug("found import " + fullyQualifiedName + " on " + getTypeNameForMsg(i) + ".");
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
项目:SparkCommerce    文件:AdminPermissionDaoImpl.java   
public boolean isUserQualifiedForOperationOnCeilingEntityViaDefaultPermissions(String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_BY_PERMISSION_AND_CEILING_ENTITY");
        query.setParameter("permissionNames", Arrays.asList(AdminSecurityService.DEFAULT_PERMISSIONS));
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:SparkCommerce    文件:AdminPermissionDaoImpl.java   
public boolean doesOperationExistForCeilingEntity(PermissionType permissionType, String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_PERMISSIONS_BY_TYPE_AND_CEILING_ENTITY");
        query.setParameter("type", permissionType.getType());
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:blcdemo    文件:AdminPermissionDaoImpl.java   
public boolean isUserQualifiedForOperationOnCeilingEntityViaDefaultPermissions(String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_BY_PERMISSION_AND_CEILING_ENTITY");
        query.setParameter("permissionNames", Arrays.asList(AdminSecurityService.DEFAULT_PERMISSIONS));
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:blcdemo    文件:AdminPermissionDaoImpl.java   
public boolean doesOperationExistForCeilingEntity(PermissionType permissionType, String ceilingEntityFullyQualifiedName) {
    //the ceiling may be an impl, which will fail because entity permission is normally specified for the interface
    //try the passed in ceiling first, but also try an interfaces implemented
    List<String> testClasses = new ArrayList<String>();
    testClasses.add(ceilingEntityFullyQualifiedName);
    try {
        for (Object interfaze : ClassUtils.getAllInterfaces(Class.forName(ceilingEntityFullyQualifiedName))) {
            testClasses.add(((Class<?>) interfaze).getName());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    for (String testClass : testClasses) {
        Query query = em.createNamedQuery("BC_COUNT_PERMISSIONS_BY_TYPE_AND_CEILING_ENTITY");
        query.setParameter("type", permissionType.getType());
        query.setParameter("ceilingEntity", testClass);
        query.setHint(QueryHints.HINT_CACHEABLE, true);

        Long count = (Long) query.getSingleResult();
        if (count > 0) {
            return true;
        }
    }
    return false;
}
项目:gama    文件:GamaBasicTypeConverter.java   
@Override
public boolean canConvert(final Class arg0) {
    final List<Class<?>> allClassesApa = ClassUtils.getAllSuperclasses(arg0);
    for (final Object c : allClassesApa) {
        if (c.equals(GamaType.class))
            return true;
    }
    // if((arg0.equals(GamaType.class)) ||
    // (arg0.getSuperclass().equals(GamaType.class)))
    // {return true;}

    // List allInterfaceApa = ClassUtils.getAllInterfaces(arg0);
    //
    // for(Object i : allInterfaceApa) {
    // if(i.equals(IType.class))
    // return true;
    // }
    return false;
}
项目:motech    文件:TypeHelper.java   
/**
 * Returns concrete class, for the given collection interface or abstract class. If given class
 * is already concrete, it will return that class.
 *
 * @param collectionClass collection class to find implementation for
 * @return concrete class
 */
public static Class<? extends Collection> suggestCollectionImplementation(Class<? extends Collection> collectionClass) {
    Class<? extends Collection> collClass = null;

    if (collectionClass != null && (collectionClass.isInterface() || Modifier.isAbstract(collectionClass.getModifiers()))) {
        // for interface such as List (or abstract classes), go to the implementation map
        collClass = COLLECTION_IMPLEMENTATIONS.get(collectionClass.getName());
    } else if (collectionClass != null &&
            ConstructorUtils.getAccessibleConstructor(collectionClass, new Class[0]) == null) {
        // this is an implementation class, but no default constructor, datanucleus collection for example
        // go through interfaces and try to find an interface we have in the collection map
        for (Object intClassObj : ClassUtils.getAllInterfaces(collectionClass)) {
            Class intClass = (Class) intClassObj;
            collClass = COLLECTION_IMPLEMENTATIONS.get(intClass.getName());
            if (collClass != null) {
                break;
            }
        }
    } else {
        // this is an implementation that can be instantiated, return it
        collClass = collectionClass;
    }
    return collClass == null ? ArrayList.class : collClass; // NOPMD - bug in PMD, objects to ArrayList.class here
}
项目:daikon    文件:GatewayOperations.java   
/**
 * Handle {@link Call}-annotated methods.
 * @param pjp The wrapped method
 * @return The result of the service call as configured by {@link Call}.
 * @throws Throwable No exception/error is handled in aspect.
 */
@Around("@annotation(org.talend.daikon.annotation.Call)")
public Object call(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature ms = (MethodSignature) pjp.getSignature();
    Method m = ms.getMethod();
    final Call callAnnotation = AnnotationUtils.getAnnotation(m, Call.class);
    if (callAnnotation != null) {
        final Object[] args = pjp.getArgs();
        if (!callAnnotation.using().equals(DefaultHystrixCommand.class)) {
            if (!ClassUtils.isAssignable(callAnnotation.service(), DefaultService.class) || StringUtils.isEmpty(callAnnotation.operation())) {
                LOGGER.warn("Method '{}' use custom invocation but also sets service and operation name", m.getName());
            }
            return handleCustomExecution(callAnnotation, args);
        } else {
            return handleServiceForward(callAnnotation, args);
        }
    }
    return pjp.proceed();
}
项目:vaadin-sample-portlet    文件:LazyUserContainer.java   
@Override
public boolean addContainerProperty(Object propertyId, final Class<?> type, Object defaultValue) throws UnsupportedOperationException {
    if (propertyId != null && type != null && ClassUtils.isAssignable(propertyId.getClass(), String.class)) {
        String pid = (String) propertyId;

        if(extraPropertyIds.contains(pid)) {
            return false;
        } else {
            extraPropertyIds.add(pid);
            extraTypes.put(pid, type);

            fireContainerPropertySetChange();

            return true;
        }
    } else {
        return false;
    }
}
项目:vaadin-sample-portlet    文件:LazyUserContainer.java   
@Override
public Class<?> getType(Object propertyId) {
    if (extraPropertyIds != null && ! extraPropertyIds.isEmpty()) {
        if (propertyId != null && ClassUtils.isAssignable(propertyId.getClass(), String.class)) {
            return extraTypes.get((String) propertyId);
        }
    }

    Class<?> type = super.getType(propertyId);

    if (type != null) return type;

    logger.warn("Could not find type for [" + propertyId + "].");

    return Object.class;
}
项目:astor    文件:ReflectionToStringBuilder.java   
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Rject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
        && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
项目:astor    文件:ReflectionToStringBuilder.java   
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Rject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
        && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
项目:sglj    文件:RmiUtils.java   
/**
    * Get the number of steps required to promote a primitive number to another type.
    * @param srcClass the (primitive) source class
    * @param destClass the (primitive) destination class
    * @return The cost of promoting the primitive
    */
   @SuppressWarnings("rawtypes")
private static float getPrimitivePromotionCost(final Class srcClass,
           final Class destClass) {
       float cost = 0.0f;
       Class cls = srcClass;
       if (!cls.isPrimitive()) {
           // slight unwrapping penalty
           cost += 0.1f;
           cls = ClassUtils.wrapperToPrimitive(cls);
       }
       for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
           if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
               cost += 0.1f;
               if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
                   cls = ORDERED_PRIMITIVE_TYPES[i + 1];
               }
           }
       }
       return cost;
   }
项目:data-prep    文件:TransformationContext.java   
/**
 * Cleanup transformation context.
 */
public void cleanup() {
    final Collection<ActionContext> allActionsContexts = getAllActionsContexts();
    LOGGER.debug("cleaning up {} action context(s) ", allActionsContexts.size());
    for (ActionContext currentContext : allActionsContexts) {
        currentContext.getContextEntries().forEach(contextEntry -> {
            try {
                try {
                    final Method destroy = ClassUtils.getPublicMethod(contextEntry.getClass(), "destroy", new Class[0]);
                    LOGGER.debug("destroy {}", contextEntry);
                    destroy.invoke(contextEntry);
                } catch (NoSuchMethodException e) {
                    LOGGER.trace("Context entry {} does not need clean up.", contextEntry, e);
                }
            } catch (Exception error) {
                LOGGER.warn("error cleaning action context {}", contextEntry, error);
            }
        });
    }
}
项目:MLDS    文件:RequestMappingSecurityTest.java   
/**
 * Make sure we use a limited set of role lists, in a standard order
 */
@Test
public void shouldUseStereotypedRolesLists() throws Exception {
    final Set<List<String>> allowedRoleLists = Sets.newHashSet();
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.PUBLIC));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.STAFF_OR_ADMIN));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.AUTHENTICATED));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.ADMIN_ONLY));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.USER_ONLY));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.UNAUTHENTICATED));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.USER_OR_ADMIN));
    allowedRoleLists.add(Arrays.asList(AuthoritiesConstants.USER_OR_STAFF_ADMIN));

    ControllerMethodTraversal controllerMethodTraversal = new ControllerMethodTraversal();
    controllerMethodTraversal.visitClasses(new MethodVisitor() {
        @Override
        public void visit(Class<?> controllerClass, Method method) {
            if(method.isAnnotationPresent(RequestMapping.class) && method.isAnnotationPresent(RolesAllowed.class)){
                List<String> roles = Arrays.asList(method.getAnnotation(RolesAllowed.class).value());

                Assert.assertTrue(ClassUtils.getShortClassName(controllerClass) + "." + method.getName() + " fails to use a standard role list", allowedRoleLists.contains(roles));
            }
        }
    });
}
项目:org.fastnate    文件:AbstractCsvDataProvider.java   
@SuppressWarnings("unchecked")
private <T> CsvPropertyConverter<? super T> findConverter(final Class<T> targetType) {
    if (targetType == null) {
        return null;
    }
    if (targetType.isPrimitive()) {
        return findConverter(ClassUtils.primitiveToWrapper(targetType));
    }
    CsvPropertyConverter<? super T> converter = (CsvPropertyConverter<? super T>) PROPERTY_CONVERTER
            .get(targetType);
    if (converter == null) {
        converter = findConverter(targetType.getSuperclass());
        if (converter == null) {
            for (final Class<?> interf : targetType.getInterfaces()) {
                converter = findConverter((Class<? super T>) interf);
                if (converter != null) {
                    return converter;
                }
            }
        }
    }
    return converter;
}
项目:org.fastnate    文件:CsvNumberConverter.java   
@Override
public Number convert(final Class<? extends Number> targetType, final String value) {
    if (StringUtils.isBlank(value)) {
        if (targetType.isPrimitive()) {
            return convert(targetType, "0");
        }
        return null;
    }
    if (targetType == Number.class) {
        return new Float(value);
    }
    final Class<? extends Number> wrapperType = targetType.isPrimitive() ? ClassUtils.primitiveToWrapper(targetType)
            : targetType;
    try {
        return wrapperType.getConstructor(String.class).newInstance(value);
    } catch (final InstantiationException | IllegalAccessException | InvocationTargetException
            | NoSuchMethodException e) {
        throw new IllegalArgumentException(e);
    }
}