Example usage for java.lang Class getInterfaces

List of usage examples for java.lang Class getInterfaces

Introduction

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

Prototype

public Class<?>[] getInterfaces() 

Source Link

Document

Returns the interfaces directly implemented by the class or interface represented by this object.

Usage

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {//from  w  w  w  .j av a 2 s. com

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:org.apache.axis.encoding.SerializationContext.java

/**
 * Walk the interfaces of a class looking for a serializer for that
 * interface.  Include any parent interfaces in the search also.
 *
 *//*  www  .  jav  a  2 s . c  om*/
private SerializerFactory getSerializerFactoryFromInterface(Class javaType, QName xmlType, TypeMapping tm) {
    SerializerFactory serFactory = null;
    Class[] interfaces = javaType.getInterfaces();
    if (interfaces != null) {
        for (int i = 0; i < interfaces.length; i++) {
            Class iface = interfaces[i];
            serFactory = (SerializerFactory) tm.getSerializer(iface, xmlType);
            if (serFactory == null)
                serFactory = getSerializerFactoryFromInterface(iface, xmlType, tm);
            if (serFactory != null)
                break;

        }
    }
    return serFactory;
}

From source file:org.jabsorb.ng.JSONRPCBridge.java

/**
 * Check whether a class is registered as a callable reference type.
 * //from w w  w.ja  v a  2  s .com
 * @param clazz
 *            The class object to check is a callable reference.
 * @return true if it is, false otherwise
 */
public boolean isCallableReference(final Class<?> clazz) {

    if (this == globalBridge) {
        return false;
    }
    if (!referencesEnabled) {
        return false;
    }
    if (callableReferenceSet.contains(clazz)) {
        return true;
    }

    // check if the class implements any interface that is
    // registered as a callable reference...
    final Class<?>[] interfaces = clazz.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (callableReferenceSet.contains(interfaces[i])) {
            return true;
        }
    }

    // check super classes as well...
    Class<?> superClass = clazz.getSuperclass();
    while (superClass != null) {
        if (callableReferenceSet.contains(superClass)) {
            return true;
        }
        superClass = superClass.getSuperclass();
    }

    // should interfaces of each superclass be checked too???
    // not sure...

    return globalBridge.isCallableReference(clazz);
}

From source file:com.netcrest.pado.tools.pado.PadoShell.java

@SuppressWarnings("rawtypes")
private boolean isImplement(Class cls, Class interf) {
    Class interfaces[] = cls.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (interfaces[i] == interf) {
            return true;
        }/*from  w w  w  .j ava 2 s  . c  om*/
    }
    return false;
}

From source file:org.grouplens.grapht.BindingImpl.java

private void recordTypes(Class<?> src, Class<?> type, Map<Class<?>, RuleSet> bindPoints) {
    // check exclusions
    if (type == null || excludeTypes.contains(type)) {
        // the type is excluded, terminate recursion (this relies on Object
        // being included in the exclude set)
        return;//from   w  ww .  j  a  v  a2 s .  c o m
    }

    RuleSet set;
    if (type.equals(src)) {
        // type is the source type, so this is the manual rule
        set = RuleSet.EXPLICIT;
    } else if (src.isAssignableFrom(type)) {
        // type is a subclass of the source type, and a superclass
        // of the target type
        set = RuleSet.INTERMEDIATE_TYPES;
    } else if (type.isAssignableFrom(src)) {
        // type is a superclass of the source type, so it is also a superclass
        // of the target type
        set = RuleSet.SUPER_TYPES;
    } else {
        // type is a superclass of the target type, but not of the source type
        // so we don't generate any bindings
        return;
    }

    // record the type's weight
    bindPoints.put(type, set);

    // recurse to superclass and implemented interfaces
    // - superclass is null for Object, interfaces, and primitives
    // - interfaces holds implemented or extended interfaces depending on
    //   if the type is a class or interface
    recordTypes(src, type.getSuperclass(), bindPoints);
    for (Class<?> i : type.getInterfaces()) {
        recordTypes(src, i, bindPoints);
    }
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Does the class implement SimpleType/*w w w.j  av  a 2 s . c  om*/
 *
 * @param type input Class
 * @return true if the type implements SimpleType
 */
boolean implementsSimpleType(Class type) {

    Class[] impls = type.getInterfaces();

    for (int i = 0; i < impls.length; i++) {
        if (impls[i] == SimpleType.class) {
            return true;
        }
    }

    return false;
}

From source file:com.opensymphony.xwork2.util.DefaultLocalizedTextProvider.java

/**
 * Traverse up class hierarchy looking for message.  Looks at class, then implemented interface,
 * before going up hierarchy.//w  w  w  . jav  a2 s  .c  om
 *
 * @return the message
 */
private String findMessage(Class clazz, String key, String indexedKey, Locale locale, Object[] args,
        Set<String> checked, ValueStack valueStack) {
    if (checked == null) {
        checked = new TreeSet<String>();
    } else if (checked.contains(clazz.getName())) {
        return null;
    }

    // look in properties of this class
    String msg = getMessage(clazz.getName(), locale, key, valueStack, args);

    if (msg != null) {
        return msg;
    }

    if (indexedKey != null) {
        msg = getMessage(clazz.getName(), locale, indexedKey, valueStack, args);

        if (msg != null) {
            return msg;
        }
    }

    // look in properties of implemented interfaces
    Class[] interfaces = clazz.getInterfaces();

    for (Class anInterface : interfaces) {
        msg = getMessage(anInterface.getName(), locale, key, valueStack, args);

        if (msg != null) {
            return msg;
        }

        if (indexedKey != null) {
            msg = getMessage(anInterface.getName(), locale, indexedKey, valueStack, args);

            if (msg != null) {
                return msg;
            }
        }
    }

    // traverse up hierarchy
    if (clazz.isInterface()) {
        interfaces = clazz.getInterfaces();

        for (Class anInterface : interfaces) {
            msg = findMessage(anInterface, key, indexedKey, locale, args, checked, valueStack);

            if (msg != null) {
                return msg;
            }
        }
    } else {
        if (!clazz.equals(Object.class) && !clazz.isPrimitive()) {
            return findMessage(clazz.getSuperclass(), key, indexedKey, locale, args, checked, valueStack);
        }
    }

    return null;
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Recursive helper class for loadServiceDescByIntrospection
 *//*from   w  w  w  .  j a v  a2  s.c o m*/
private void loadServiceDescByIntrospectionRecursive(Class implClass) {
    if (Skeleton.class.equals(implClass)) {
        return;
    }

    Method[] methods = getMethods(implClass);

    for (int i = 0; i < methods.length; i++) {
        if (Modifier.isPublic(methods[i].getModifiers()) && !isServiceLifeCycleMethod(implClass, methods[i])) {
            getSyncedOperationsForName(implClass, methods[i].getName());
        }
    }

    if (implClass.isInterface()) {
        Class[] superClasses = implClass.getInterfaces();
        for (int i = 0; i < superClasses.length; i++) {
            Class superClass = superClasses[i];
            if (!superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.")
                    && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
                loadServiceDescByIntrospectionRecursive(superClass);
            }
        }
    } else {
        Class superClass = implClass.getSuperclass();
        if (superClass != null && !superClass.getName().startsWith("java.")
                && !superClass.getName().startsWith("javax.")
                && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
            loadServiceDescByIntrospectionRecursive(superClass);
        }
    }
}

From source file:com.silverwrist.dynamo.app.ApplicationContainer.java

private final RegisteredRenderer searchArrayRenderers(Class klass, String template) {
    if (klass.isPrimitive() || (klass == Object.class))
        return null; // should have been picked up already

    // look at this level for the class member
    RegisteredRenderer rc = null;/*w  w w.  jav  a 2 s. c  o m*/
    try { // load the array class corresponding to the right depth, then check the renderer map
        Class tmp = Class.forName(StringUtils.replace(template, TEMPLATE_CLASSNAME, klass.getName()));
        rc = (RegisteredRenderer) (m_class_renderers.get(tmp));
        if (rc != null)
            return rc;

    } // end try
    catch (ClassNotFoundException e) { // this class was not found, so it can't be present
        rc = null;

    } // end catch

    // Try all interfaces implemented by the object.
    Class[] ifaces = klass.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) { // look for interfaces implemented by the object
        rc = searchArrayRenderers(ifaces[i], template);
        if (rc != null)
            return rc;

    } // end for

    Class superclass = klass.getSuperclass();
    if (superclass != null) { // try the superclass now
        rc = searchArrayRenderers(superclass, template);
        if (rc != null)
            return rc;

    } // end if

    return null; // give up

}

From source file:org.seedstack.spring.internal.SpringModule.java

@SuppressWarnings("unchecked")
private void bindFromApplicationContext() {
    boolean debugEnabled = LOGGER.isDebugEnabled();

    ConfigurableListableBeanFactory currentBeanFactory = this.beanFactory;
    do {/*from  ww  w . j  av  a 2s .  c o m*/
        for (String beanName : currentBeanFactory.getBeanDefinitionNames()) {
            BeanDefinition beanDefinition = currentBeanFactory.getMergedBeanDefinition(beanName);
            if (!beanDefinition.isAbstract()) {
                Class<?> beanClass;
                try {
                    beanClass = Class.forName(beanDefinition.getBeanClassName());
                } catch (ClassNotFoundException e) {
                    LOGGER.warn("Cannot bind spring bean " + beanName + " because its class "
                            + beanDefinition.getBeanClassName() + " failed to load", e);
                    continue;
                }

                // FactoryBean special case: retrieve it and query for the object type it creates
                if (FactoryBean.class.isAssignableFrom(beanClass)) {
                    beanClass = ((FactoryBean) currentBeanFactory.getBean('&' + beanName)).getObjectType();
                    if (beanClass == null) {
                        LOGGER.warn("Cannot bind spring bean " + beanName
                                + " because its factory bean cannot determine its class");
                        continue;
                    }
                }

                SpringBeanDefinition springBeanDefinition = new SpringBeanDefinition(beanName,
                        currentBeanFactory);

                // Adding bean with its base type
                addBeanDefinition(beanClass, springBeanDefinition);

                // Adding bean with its parent type if enabled
                Class<?> parentClass = beanClass.getSuperclass();
                if (parentClass != null && parentClass != Object.class) {
                    addBeanDefinition(parentClass, springBeanDefinition);
                }

                // Adding bean with its immediate interfaces if enabled
                for (Class<?> i : beanClass.getInterfaces()) {
                    addBeanDefinition(i, springBeanDefinition);
                }
            }
        }
        BeanFactory factory = currentBeanFactory.getParentBeanFactory();
        if (factory != null) {
            if (factory instanceof ConfigurableListableBeanFactory) {
                currentBeanFactory = (ConfigurableListableBeanFactory) factory;
            } else {
                LOGGER.info(
                        "Cannot go up further in the bean factory hierarchy, parent bean factory doesn't implement ConfigurableListableBeanFactory");
                currentBeanFactory = null;
            }
        } else {
            currentBeanFactory = null;
        }
    } while (currentBeanFactory != null);

    for (Map.Entry<Class<?>, Map<String, SpringBeanDefinition>> entry : this.beanDefinitions.entrySet()) {
        Class<?> type = entry.getKey();
        Map<String, SpringBeanDefinition> definitions = entry.getValue();

        // Bind by name for each bean of this type and by type if there is no ambiguity
        for (SpringBeanDefinition candidate : definitions.values()) {
            if (debugEnabled) {
                LOGGER.info("Binding spring bean " + candidate.getName() + " by name and type "
                        + type.getCanonicalName());
            }

            bind(type).annotatedWith(Names.named(candidate.getName()))
                    .toProvider(new SpringBeanProvider(type, candidate.getName(), candidate.getBeanFactory()));
        }
    }
}