Example usage for java.lang.reflect Modifier isAbstract

List of usage examples for java.lang.reflect Modifier isAbstract

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isAbstract.

Prototype

public static boolean isAbstract(int mod) 

Source Link

Document

Return true if the integer argument includes the abstract modifier, false otherwise.

Usage

From source file:nl.knaw.huygens.timbuctoo.config.TypeRegistry.java

private boolean shouldNotRegister(Class<?> type) {
    return Modifier.isAbstract(type.getModifiers());
}

From source file:org.springframework.ws.soap.saaj.support.SaajUtils.java

/**
 * Checks whether we can find a SAAJ 1.2 implementation, being aware of the broken WebLogic 9 SAAJ implementation.
 * <p/>/*from  ww  w .java  2 s.c om*/
 * WebLogic 9 does implement SAAJ 1.2, but throws UnsupportedOperationExceptions when a SAAJ 1.2 method is called.
 */
private static boolean isSaaj12(SOAPElement soapElement) {
    try {
        Method m = soapElement.getClass().getMethod("getPrefix", new Class[0]);
        // we might be using the SAAJ 1.2 API, while the impl is 1.1
        // let's see if the method is not abstract
        if (Modifier.isAbstract(m.getModifiers())) {
            logger.warn("Detected SAAJ API version 1.2, while implementation provides version 1.1. "
                    + "Please replace the SAAJ API jar with a version that corresponds to your runtime "
                    + "implementation (which might be provided by your app server).");
            return false;
        } else {
            soapElement.getPrefix();
            return true;
        }
    } catch (NoSuchMethodException e) {
        // getPrefix not found
        return false;
    } catch (UnsupportedOperationException ex) {
        // getPrefix results in UOE, let's see if we're dealing with WL 9
        if (WEBLOGIC_9_SAAJ_EXCEPTION_MESSAGE.equals(ex.getMessage())) {
            return false;
        } else {
            throw ex;
        }
    }
}

From source file:org.obsidian.test.TestAbstract.java

public <T> String buildConstructionStringFromType(Class<T> type, Constructor[] visitedConstructors) {

    //initialize construction String 
    String constructionString;/*  w w  w . ja  va2s . co  m*/

    //append equality method types
    appendEqualityMethodTypes(type);

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    //if class is abstract, replace with concrete substitution
    if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        type = Helpers.getConcreteSubstitution(type);
    }

    //type's simple name
    String name = type.getSimpleName();

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    if (Helpers.PRIMITIVE_CONSTRUCTIONS.get(name) != null) {
        //get construction from PRIMITIVE_CONSTRUCTIONS
        constructionString = Helpers.PRIMITIVE_CONSTRUCTIONS.get(name);
    } else if (type.isArray()) {
        int numberOfDimensions = StringUtils.countMatches(name, "[]");

        constructionString = name.replace("[]", "");

        for (int i = 0; i < numberOfDimensions; i++) {
            constructionString = constructionString + "[0]";
        }

        constructionString = "new " + constructionString;

    } else if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        constructionString = "null";
    } else if (type.getConstructors().length == 0) {
        constructionString = "null";
    } else {
        //not visited constructors
        ArrayList<Constructor> NVC = Helpers.notVisitedConstructors(type.getConstructors(),
                visitedConstructors);

        Constructor constructor = Helpers.getConstructorWithLeastParametersFromList(NVC);

        if (NVC.isEmpty()) {
            constructionString = "null";
        } else if (constructor.getExceptionTypes().length > 0) {
            constructionString = "null";
        } else {

            visitedConstructors = Helpers.addConstructor(visitedConstructors, constructor);
            constructionString = "new " + name + "(";
            Class[] parameters = constructor.getParameterTypes();
            for (int i = 0; i < parameters.length; i++) {
                constructionString = constructionString
                        + buildConstructionStringFromType(parameters[i], visitedConstructors) + ",";
            }
            if (parameters.length != 0) {
                constructionString = constructionString.substring(0, constructionString.length() - 1);
            }
            constructionString = constructionString + ")";
        }
    }

    //this will prevent ambiguity in constructors with parmeter that 
    //cannot be constructed
    if (constructionString.contains("null")) {
        constructionString = "null";
    }

    return constructionString;
}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.JpaEntityDefinition.java

public boolean isAbstract() {
    return Modifier.isAbstract(getJpaClass().getModifiers());
}

From source file:org.apache.tapestry.enhance.DefaultComponentClassEnhancer.java

/**
 *  Invoked to validate that an enhanced class is acceptible.  Primarily, this is to ensure
 *  that the class contains no unimplemented abstract methods or fields.  Normally,
 *  this kind of checking is done at compile time, but for generated
 *  classes, there is no compile time check (!) and you can get runtime
 *  errors when accessing unimplemented abstract methods.
 * //  w ww  .  j a  v a2 s . c o  m
 *
 **/

protected void validateEnhancedClass(Class subject, String className, IComponentSpecification specification) {
    boolean debug = LOG.isDebugEnabled();

    if (debug)
        LOG.debug("Validating " + subject);

    Set implementedMethods = new HashSet();
    Class current = subject;

    while (true) {
        Method m = checkForAbstractMethods(current, implementedMethods);

        if (m != null)
            throw new ApplicationRuntimeException(
                    Tapestry.format("DefaultComponentClassEnhancer.no-impl-for-abstract-method",
                            new Object[] { m, current, className, subject.getName() }),
                    specification.getLocation(), null);

        // An earlier version of this code walked the interfaces directly,
        // but it appears that implementing an interface actually
        // puts abstract method declarations into the class
        // (at least, in terms of what getDeclaredMethods() returns).

        // March up to the super class.

        current = current.getSuperclass();

        // Once advanced up to a concrete class, we trust that
        // the compiler did its checking.

        if (!Modifier.isAbstract(current.getModifiers()))
            break;
    }

}

From source file:ca.uhn.fhir.rest.method.OperationParameter.java

@SuppressWarnings("unchecked")
@Override/*ww w . j av a 2  s . co m*/
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType,
        Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
    if (getContext().getVersion().getVersion().isRi()) {
        if (IDatatype.class.isAssignableFrom(theParameterType)) {
            throw new ConfigurationException("Incorrect use of type " + theParameterType.getSimpleName()
                    + " as parameter type for method when context is for version "
                    + getContext().getVersion().getVersion().name() + " in method: " + theMethod.toString());
        }
    }

    myParameterType = theParameterType;
    if (theInnerCollectionType != null) {
        myInnerCollectionType = CollectionBinder.getInstantiableCollectionType(theInnerCollectionType, myName);
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = OperationParam.MAX_UNLIMITED;
        }
    } else if (IQueryParameterAnd.class.isAssignableFrom(myParameterType)) {
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = OperationParam.MAX_UNLIMITED;
        }
    } else {
        if (myMax == OperationParam.MAX_DEFAULT) {
            myMax = 1;
        }
    }

    boolean typeIsConcrete = !myParameterType.isInterface()
            && !Modifier.isAbstract(myParameterType.getModifiers());

    //@formatter:off
    boolean isSearchParam = IQueryParameterType.class.isAssignableFrom(myParameterType)
            || IQueryParameterOr.class.isAssignableFrom(myParameterType)
            || IQueryParameterAnd.class.isAssignableFrom(myParameterType);
    //@formatter:off

    /*
     * Note: We say here !IBase.class.isAssignableFrom because a bunch of DSTU1/2 datatypes also
     * extend this interface. I'm not sure if they should in the end.. but they do, so we
     * exclude them.
     */
    isSearchParam &= typeIsConcrete && !IBase.class.isAssignableFrom(myParameterType);

    myAllowGet = IPrimitiveType.class.isAssignableFrom(myParameterType) || String.class.equals(myParameterType)
            || isSearchParam || ValidationModeEnum.class.equals(myParameterType);

    /*
     * The parameter can be of type string for validation methods - This is a bit weird. See ValidateDstu2Test. We
     * should probably clean this up..
     */
    if (!myParameterType.equals(IBase.class) && !myParameterType.equals(String.class)) {
        if (IBaseResource.class.isAssignableFrom(myParameterType) && myParameterType.isInterface()) {
            myParamType = "Resource";
        } else if (DateRangeParam.class.isAssignableFrom(myParameterType)) {
            myParamType = "date";
            myMax = 2;
            myAllowGet = true;
        } else if (myParameterType.equals(ValidationModeEnum.class)) {
            myParamType = "code";
        } else if (IBase.class.isAssignableFrom(myParameterType) && typeIsConcrete) {
            myParamType = myContext.getElementDefinition((Class<? extends IBase>) myParameterType).getName();
        } else if (isSearchParam) {
            myParamType = "string";
            mySearchParameterBinding = new SearchParameter(myName, myMin > 0);
            mySearchParameterBinding.setCompositeTypes(COMPOSITE_TYPES);
            mySearchParameterBinding.setType(myContext, theParameterType, theInnerCollectionType,
                    theOuterCollectionType);
            myConverter = new OperationParamConverter();
        } else {
            throw new ConfigurationException("Invalid type for @OperationParam: " + myParameterType.getName());
        }

    }

}

From source file:com.px100systems.data.core.DatabaseStorage.java

@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    if (tenantLoader != null)
        tenantLoader.setDatabase(this);

    configuredEntities = new HashMap<String, Class<? extends Entity>>();

    try {/*ww  w.jav a2 s. com*/
        ClassPath cp = ClassPath.from(getClass().getClassLoader());
        for (String p : baseEntityPackages)
            for (ClassPath.ClassInfo cli : cp.getTopLevelClassesRecursive(p)) {
                Class<?> eClass = Class.forName(cli.getName());
                if (!Modifier.isAbstract(eClass.getModifiers()) && Entity.class.isAssignableFrom(eClass)) {
                    Class<? extends Entity> entityClass = (Class<? extends Entity>) eClass;
                    String name = entityClass.getSimpleName();
                    Class<? extends Entity> cls = configuredEntities.get(name);
                    if (cls != null) {
                        if (cls.getName().equals(entityClass.getName()))
                            continue;
                        throw new RuntimeException("Duplicate entities in different packages: " + name);
                    }
                    configuredEntities.put(name, entityClass);
                    SerializationDefinition.register(entityClass);
                }
            }
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    SerializationDefinition.lock();

    runtimeStorage.getProvider().start();

    List<BaseTenantConfig> tenants = new ArrayList<BaseTenantConfig>();
    if (tenantLoader != null)
        tenants = tenantLoader.load();

    List<EntityInfo> entities = new ArrayList<>();
    for (Class<? extends Entity> entityClass : getConfiguredEntities().values()) {
        Map<String, Class<?>> indexes = Entity.indexes(entityClass);
        List<CompoundIndexDescriptor> compoundIndexes = Entity.compoundIndexes(entityClass);
        if (tenants.isEmpty())
            entities.add(new EntityInfo(entityClass, 0, Entity.unitFromClass(entityClass, 0), indexes,
                    compoundIndexes));
        else
            for (BaseTenantConfig tenant : tenants)
                entities.add(new EntityInfo(entityClass, tenant.getId(),
                        Entity.unitFromClass(entityClass, tenant.getId()), indexes, compoundIndexes));
    }

    init(entities, initializer != null);

    if (initializer != null) {
        initializer.initialize(new Transaction(this, 0));
        log.info("Initialized the database");
    }
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedProxyClassGenerator.java

/**
 * Generates an implementation of the given managed type.
 * <p>//from ww w  .jav  a2s .c  o m
 * The generated class will implement/extend the managed type and will:
 * <ul>
 *     <li>provide implementations for abstract getters and setters that delegate to model nodes</li>
 *     <li>provide a `toString()` implementation</li>
 *     <li>mix-in implementation of {@link ManagedInstance}</li>
 *     <li>provide a constructor that accepts a {@link ModelElementState}, which will be used to implement the above.</li>
 * </ul>
 *
 * In case a delegate schema is supplied, the generated class will also have:
 * <ul>
 *     <li>a constructor that also takes a delegate instance</li>
 *     <li>methods that call through to the delegate instance</li>
 * </ul>
 */
public <T, M extends T, D extends T> Class<? extends M> generate(ModelStructSchema<M> managedSchema,
        ModelStructSchema<D> delegateSchema) {
    if (delegateSchema != null
            && Modifier.isAbstract(delegateSchema.getType().getConcreteClass().getModifiers())) {
        throw new IllegalArgumentException("Delegate type must be null or a non-abstract type");
    }
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);

    ModelType<M> managedType = managedSchema.getType();

    StringBuilder generatedTypeNameBuilder = new StringBuilder(managedType.getName());
    if (delegateSchema != null) {
        generatedTypeNameBuilder.append("$BackedBy_")
                .append(delegateSchema.getType().getName().replaceAll("\\.", "_"));
    } else {
        generatedTypeNameBuilder.append("$Impl");
    }

    String generatedTypeName = generatedTypeNameBuilder.toString();
    Type generatedType = Type.getType("L" + generatedTypeName.replaceAll("\\.", "/") + ";");

    Class<M> managedTypeClass = managedType.getConcreteClass();
    Class<?> superclass;
    final ImmutableSet.Builder<String> interfaceInternalNames = ImmutableSet.builder();
    final ImmutableSet.Builder<Class<?>> typesToDelegate = ImmutableSet.builder();
    typesToDelegate.add(managedTypeClass);
    interfaceInternalNames.add(MANAGED_INSTANCE_TYPE);
    if (managedTypeClass.isInterface()) {
        superclass = Object.class;
        interfaceInternalNames.add(Type.getInternalName(managedTypeClass));
    } else {
        superclass = managedTypeClass;
    }
    // TODO:LPTR This should be removed once BinaryContainer is a ModelMap
    // We need to also implement all the interfaces of the delegate type because otherwise
    // BinaryContainer won't recognize managed binaries as BinarySpecInternal
    if (delegateSchema != null) {
        ModelSchemaUtils.walkTypeHierarchy(delegateSchema.getType().getConcreteClass(),
                new ModelSchemaUtils.TypeVisitor<D>() {
                    @Override
                    public void visitType(Class<? super D> type) {
                        if (type.isInterface()) {
                            typesToDelegate.add(type);
                            interfaceInternalNames.add(Type.getInternalName(type));
                        }
                    }
                });
    }

    generateProxyClass(visitor, managedSchema, delegateSchema, interfaceInternalNames.build(),
            typesToDelegate.build(), generatedType, Type.getType(superclass));

    return defineClass(visitor, managedTypeClass.getClassLoader(), generatedTypeName);
}

From source file:org.apache.syncope.core.provisioning.java.data.ImplementationDataBinderImpl.java

@Override
public void update(final Implementation implementation, final ImplementationTO implementationTO) {
    SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidImplementation);

    if (implementation.getType() != null && implementation.getType() != implementationTO.getType()) {
        sce.getElements().add("ImplementationType cannot be changed");
        throw sce;
    }/*from ww  w  .  jav  a  2  s  .  c o m*/

    if (StringUtils.isBlank(implementationTO.getBody())) {
        sce.getElements().add("No actual implementation provided");
        throw sce;
    }

    BeanUtils.copyProperties(implementationTO, implementation);

    if (implementation.getEngine() == ImplementationEngine.JAVA) {
        Class<?> base = null;
        switch (implementation.getType()) {
        case REPORTLET:
            base = Reportlet.class;
            break;

        case ACCOUNT_RULE:
            base = AccountRule.class;
            break;

        case PASSWORD_RULE:
            base = PasswordRule.class;
            break;

        case ITEM_TRANSFORMER:
            base = ItemTransformer.class;
            break;

        case TASKJOB_DELEGATE:
            base = SchedTaskJobDelegate.class;
            break;

        case RECON_FILTER_BUILDER:
            base = ReconFilterBuilder.class;
            break;

        case LOGIC_ACTIONS:
            base = LogicActions.class;
            break;

        case PROPAGATION_ACTIONS:
            base = PropagationActions.class;
            break;

        case PULL_ACTIONS:
            base = PullActions.class;
            break;

        case PUSH_ACTIONS:
            base = PushActions.class;
            break;

        case PULL_CORRELATION_RULE:
            base = PullCorrelationRule.class;
            break;

        case VALIDATOR:
            base = Validator.class;
            break;

        case RECIPIENTS_PROVIDER:
            base = RecipientsProvider.class;
            break;

        default:
        }

        if (base == null) {
            sce.getElements().add("No Java interface found for " + implementation.getType());
            throw sce;
        }

        if (implementation.getType() == ImplementationType.REPORTLET) {
            ReportletConf reportlet = POJOHelper.deserialize(implementation.getBody(), ReportletConf.class);
            if (reportlet == null) {
                sce.getElements().add("Could not deserialize as ReportletConf");
                throw sce;
            }
        } else if (implementation.getType() == ImplementationType.ACCOUNT_RULE
                || implementation.getType() == ImplementationType.PASSWORD_RULE
                || implementation.getType() == ImplementationType.PULL_CORRELATION_RULE) {

            RuleConf rule = POJOHelper.deserialize(implementation.getBody(), RuleConf.class);
            if (rule == null) {
                sce.getElements()
                        .add("Could not deserialize as neither Account, Password nor PullCorrelation RuleConf");
                throw sce;
            }
        } else {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(implementation.getBody());
            } catch (Exception e) {
                LOG.error("Class '{}' not found", implementation.getBody(), e);
                sce.getElements().add("No Java class found: " + implementation.getBody());
                throw sce;
            }
            if (!base.isAssignableFrom(clazz)) {
                sce.getElements()
                        .add("Java class " + implementation.getBody() + " must comply with " + base.getName());
                throw sce;
            }
            if (Modifier.isAbstract(clazz.getModifiers())) {
                sce.getElements().add("Java class " + implementation.getBody() + " is abstract");
                throw sce;
            }
        }
    }
}

From source file:org.apache.bval.cdi.BValExtension.java

public <A> void processAnnotatedType(final @Observes ProcessAnnotatedType<A> pat) {
    if (!isExecutableValidationEnabled) {
        return;/*from w ww.  j av a2  s .c o  m*/
    }

    final AnnotatedType<A> annotatedType = pat.getAnnotatedType();

    if (!annotatedTypeFilter.accept(annotatedType)) {
        return;
    }

    final Class<A> javaClass = annotatedType.getJavaClass();
    final int modifiers = javaClass.getModifiers();
    if (!javaClass.isInterface() && !Modifier.isFinal(modifiers) && !Modifier.isAbstract(modifiers)) {
        try {
            ensureFactoryValidator();
            try {
                final BeanDescriptor classConstraints = validator.getConstraintsForClass(javaClass);
                if (annotatedType.isAnnotationPresent(ValidateOnExecution.class)
                        || hasValidationAnnotation(annotatedType.getMethods())
                        || hasValidationAnnotation(annotatedType.getConstructors())
                        || classConstraints != null && (validBean && classConstraints.isBeanConstrained()
                                || validConstructors && !classConstraints.getConstrainedConstructors().isEmpty()
                                || validBusinessMethods && !classConstraints
                                        .getConstrainedMethods(MethodType.NON_GETTER).isEmpty()
                                || validGetterMethods && !classConstraints
                                        .getConstrainedMethods(MethodType.GETTER).isEmpty())) {
                    final BValAnnotatedType<A> bValAnnotatedType = new BValAnnotatedType<A>(annotatedType);
                    pat.setAnnotatedType(bValAnnotatedType);
                }
            } catch (final NoClassDefFoundError ncdfe) {
                // skip
            }
        } catch (final ValidationException ve) {
            LOGGER.log(Level.FINEST, ve.getMessage(), ve);
        } catch (final Exception e) { // just info
            LOGGER.log(Level.INFO, e.getMessage());
        }
    }
}