Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

In this page you can find the example usage for java.lang ClassLoader loadClass.

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:com.haulmont.cuba.desktop.sys.DesktopExternalUIComponentsSource.java

@SuppressWarnings("unchecked")
protected void _registerComponent(InputStream is) throws ClassNotFoundException {
    ClassLoader classLoader = App.class.getClassLoader();

    Element rootElement = Dom4j.readDocument(is).getRootElement();
    List<Element> components = rootElement.elements("component");
    for (Element component : components) {
        String name = trimToEmpty(component.elementText("name"));
        String componentClassName = trimToEmpty(component.elementText("class"));

        String componentLoaderClassName = trimToEmpty(component.elementText("componentLoader"));
        String tag = trimToEmpty(component.elementText("tag"));
        if (StringUtils.isEmpty(tag)) {
            tag = name;/* www .j  av  a  2 s.c om*/
        }

        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(tag)) {
            log.warn("You have to provide name or tag for custom component");
            // skip this <component> element
            continue;
        }

        if (StringUtils.isEmpty(componentLoaderClassName) && StringUtils.isEmpty(componentClassName)) {
            log.warn("You have to provide at least <class> or <componentLoader> for custom component {} / <{}>",
                    name, tag);
            // skip this <component> element
            continue;
        }

        if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(componentClassName)) {
            Class<?> componentClass = classLoader.loadClass(componentClassName);

            if (Component.class.isAssignableFrom(componentClass)) {
                log.trace("Register component {} class {}", name, componentClass.getCanonicalName());

                DesktopComponentsFactory.registerComponent(name, (Class<? extends Component>) componentClass);
            } else {
                log.warn("Component {} is not a subclass of com.haulmont.cuba.gui.components.Component",
                        componentClassName);
            }
        }

        if (StringUtils.isNotEmpty(tag) && StringUtils.isNotEmpty(componentLoaderClassName)) {
            Class<?> componentLoaderClass = classLoader.loadClass(componentLoaderClassName);

            if (ComponentLoader.class.isAssignableFrom(componentLoaderClass)) {
                log.trace("Register tag {} loader {}", tag, componentLoaderClass.getCanonicalName());

                LayoutLoaderConfig.registerLoader(tag, (Class<? extends ComponentLoader>) componentLoaderClass);
            } else {
                log.warn(
                        "Component loader {} is not a subclass of com.haulmont.cuba.gui.xml.layout.ComponentLoader",
                        componentLoaderClassName);
            }
        }
    }

    _loadWindowLoaders(rootElement);
}

From source file:com.haulmont.cuba.web.sys.WebExternalUIComponentsSource.java

@SuppressWarnings("unchecked")
protected void _registerComponent(InputStream is) throws ClassNotFoundException {
    ClassLoader classLoader = App.class.getClassLoader();

    Element rootElement = Dom4j.readDocument(is).getRootElement();
    List<Element> components = rootElement.elements("component");
    for (Element component : components) {
        String name = trimToEmpty(component.elementText("name"));
        String componentClassName = trimToEmpty(component.elementText("class"));

        String componentLoaderClassName = trimToEmpty(component.elementText("componentLoader"));
        String tag = trimToEmpty(component.elementText("tag"));
        if (StringUtils.isEmpty(tag)) {
            tag = name;/*  w  w  w .j a va  2 s.com*/
        }

        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(tag)) {
            log.warn("You have to provide name or tag for custom component");
            // skip this <component> element
            continue;
        }

        if (StringUtils.isEmpty(componentLoaderClassName) && StringUtils.isEmpty(componentClassName)) {
            log.warn("You have to provide at least <class> or <componentLoader> for custom component {} / <{}>",
                    name, tag);
            // skip this <component> element
            continue;
        }

        if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(componentClassName)) {
            Class<?> componentClass = classLoader.loadClass(componentClassName);

            if (Component.class.isAssignableFrom(componentClass)) {
                log.trace("Register component {} class {}", name, componentClass.getCanonicalName());

                webComponentsFactory.register(name, (Class<? extends Component>) componentClass);
            } else {
                log.warn("Component {} is not a subclass of com.haulmont.cuba.gui.components.Component",
                        componentClassName);
            }
        }

        if (StringUtils.isNotEmpty(tag) && StringUtils.isNotEmpty(componentLoaderClassName)) {
            Class<?> componentLoaderClass = classLoader.loadClass(componentLoaderClassName);

            if (ComponentLoader.class.isAssignableFrom(componentLoaderClass)) {
                log.trace("Register tag {} loader {}", tag, componentLoaderClass.getCanonicalName());

                LayoutLoaderConfig.registerLoader(tag, (Class<? extends ComponentLoader>) componentLoaderClass);
            } else {
                log.warn(
                        "Component loader {} is not a subclass of com.haulmont.cuba.gui.xml.layout.ComponentLoader",
                        componentLoaderClassName);
            }
        }
    }

    _loadWindowLoaders(rootElement);
}

From source file:io.smartspaces.launcher.bootstrap.SmartSpacesFrameworkBootstrap.java

/**
 * Simple method to parse META-INF/services file for framework factory.
 * Currently, it assumes the first non-commented line is the class nodeName of
 * the framework factory implementation.
 *
 * @return the created <tt>FrameworkFactory</tt> instance
 *
 * @throws Exception//from   w  w  w  .j a va 2  s.co  m
 *           if any errors occur.
 **/
private FrameworkFactory getFrameworkFactory() throws Exception {
    // using the ServiceLoader to get a factory.
    ClassLoader classLoader = SmartSpacesFrameworkBootstrap.class.getClassLoader();
    URL url = classLoader.getResource(OSGI_FRAMEWORK_LAUNCH_FRAMEWORK_FACTORY);
    if (url != null) {
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        try {
            for (String s = br.readLine(); s != null; s = br.readLine()) {
                // Try to load first non-empty, non-commented line.
                s = s.trim();
                if (!s.isEmpty() && s.charAt(0) != META_INF_COMMENT_CHARACTER) {
                    return (FrameworkFactory) classLoader.loadClass(s).newInstance();
                }
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

    throw new Exception("Could not find framework factory.");
}

From source file:Utils.java

/**
 * This methods load a class given the classloader and the name of the class, and work for
 * extended names of primitive types. <p>
 * If you try to do ClassLoader.loadClass("boolean") it barfs it cannot find the class,
 * so this method cope with this problem.
 *//*ww w.j  ava  2  s . c o  m*/
public static Class loadClass(ClassLoader loader, String name) throws ClassNotFoundException {
    if (name == null)
        throw new ClassNotFoundException("null");

    name = name.trim();
    if (name.equals("boolean"))
        return boolean.class;
    else if (name.equals("byte"))
        return byte.class;
    else if (name.equals("char"))
        return char.class;
    else if (name.equals("short"))
        return short.class;
    else if (name.equals("int"))
        return int.class;
    else if (name.equals("long"))
        return long.class;
    else if (name.equals("float"))
        return float.class;
    else if (name.equals("double"))
        return double.class;
    else if (name.equals("java.lang.String"))
        return String.class;
    else if (name.equals("java.lang.Object"))
        return Object.class;
    else if (name.startsWith("[")) {
        // It's an array, figure out how many dimensions
        int dimension = 0;
        while (name.charAt(dimension) == '[') {
            ++dimension;
        }
        char type = name.charAt(dimension);
        Class cls = null;
        switch (type) {
        case 'Z':
            cls = boolean.class;
            break;
        case 'B':
            cls = byte.class;
            break;
        case 'C':
            cls = char.class;
            break;
        case 'S':
            cls = short.class;
            break;
        case 'I':
            cls = int.class;
            break;
        case 'J':
            cls = long.class;
            break;
        case 'F':
            cls = float.class;
            break;
        case 'D':
            cls = double.class;
            break;
        case 'L':
            // Strip the semicolon at the end
            String n = name.substring(dimension + 1, name.length() - 1);
            cls = loadClass(loader, n);
            break;
        }

        if (cls == null) {
            throw new ClassNotFoundException(name);
        } else {
            int[] dim = new int[dimension];
            return Array.newInstance(cls, dim).getClass();
        }
    } else {
        if (loader != null)
            return loader.loadClass(name);
        else
            return Class.forName(name, false, null);
    }
}

From source file:org.apache.servicemix.platform.testing.support.SmxPlatform.java

public void start() throws Exception {
    Set<String> jars = getJars(Felix.class);
    ClassLoader classLoader = new GuardClassLoader(toURLs(jars.toArray(new String[jars.size()])), null);

    BundleActivator activator = new BundleActivator() {
        private ServiceRegistration registration;

        public void start(BundleContext context) {
            registration = context.registerService(MainService.class.getName(), new MainService() {
                public String[] getArgs() {
                    return new String[0];
                }/*  www.ja  v  a 2  s  .c  o  m*/

                public int getExitCode() {
                    return 0;
                }

                public void setExitCode(int exitCode) {
                }
            }, null);
        }

        public void stop(BundleContext context) {
            registration.unregister();
        }
    };
    List<BundleActivator> activations = new ArrayList<BundleActivator>();
    activations.add(activator);

    Properties props = getConfigurationProperties();
    props.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, activations);

    Thread.currentThread().setContextClassLoader(classLoader);
    Class cl = classLoader.loadClass(Felix.class.getName());
    Constructor cns = cl.getConstructor(Map.class);
    platform = cns.newInstance(props);
    platform.getClass().getMethod("start").invoke(platform);

    Bundle systemBundle = (Bundle) platform;

    // call getBundleContext
    final Method getContext = systemBundle.getClass().getMethod("getBundleContext", null);

    AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            getContext.setAccessible(true);
            return null;
        }
    });
    context = (BundleContext) getContext.invoke(systemBundle, null);
}

From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java

/**
 * Initializes this site from an XML node that was generated using
 * {@link #toXml()}.//from w  w  w . ja va2s .c o m
 * 
 * @param config
 *          the site node
 * @param xpathProcessor
 *          xpath processor to use
 * @throws IllegalStateException
 *           if the site cannot be parsed
 * @see #toXml()
 */
public static Site fromXml(Node config, XPath xpathProcessor) throws IllegalStateException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // identifier
    String identifier = XPathHelper.valueOf(config, "@id", xpathProcessor);
    if (identifier == null)
        throw new IllegalStateException("Unable to create sites without identifier");

    // class
    Site site = null;
    String className = XPathHelper.valueOf(config, "ns:class", xpathProcessor);
    if (className != null) {
        try {
            Class<? extends Site> c = (Class<? extends Site>) classLoader.loadClass(className);
            site = c.newInstance();
            site.setIdentifier(identifier);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(
                    "Implementation " + className + " for site '" + identifier + "' not found", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(
                    "Error instantiating impelementation " + className + " for site '" + identifier + "'", e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for site '" + identifier + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for site '" + identifier + "'", t);
        }

    } else {
        site = new SiteImpl();
        site.setIdentifier(identifier);
    }

    // name
    String name = XPathHelper.valueOf(config, "ns:name", xpathProcessor);
    if (name == null)
        throw new IllegalStateException("Site '" + identifier + " has no name");
    site.setName(name);

    // domains
    NodeList urlNodes = XPathHelper.selectList(config, "ns:domains/ns:url", xpathProcessor);
    if (urlNodes.getLength() == 0)
        throw new IllegalStateException("Site '" + identifier + " has no hostname");
    String url = null;
    try {
        for (int i = 0; i < urlNodes.getLength(); i++) {
            Node urlNode = urlNodes.item(i);
            url = urlNode.getFirstChild().getNodeValue();
            boolean defaultUrl = ConfigurationUtils.isDefault(urlNode);
            Environment environment = Environment.Production;
            Node environmentAttribute = urlNode.getAttributes().getNamedItem("environment");
            if (environmentAttribute != null && environmentAttribute.getNodeValue() != null)
                environment = Environment.valueOf(StringUtils.capitalize(environmentAttribute.getNodeValue()));

            SiteURLImpl siteURL = new SiteURLImpl(new URL(url));
            siteURL.setDefault(defaultUrl);
            siteURL.setEnvironment(environment);

            site.addHostname(siteURL);
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Site '" + identifier + "' defines malformed url: " + url);
    }

    // languages
    NodeList languageNodes = XPathHelper.selectList(config, "ns:languages/ns:language", xpathProcessor);
    if (languageNodes.getLength() == 0)
        throw new IllegalStateException("Site '" + identifier + " has no languages");
    for (int i = 0; i < languageNodes.getLength(); i++) {
        Node languageNode = languageNodes.item(i);
        Node defaultAttribute = languageNode.getAttributes().getNamedItem("default");
        String languageId = languageNode.getFirstChild().getNodeValue();
        try {
            Language language = LanguageUtils.getLanguage(languageId);
            if (ConfigurationUtils.isTrue(defaultAttribute))
                site.setDefaultLanguage(language);
            else
                site.addLanguage(language);
        } catch (UnknownLanguageException e) {
            throw new IllegalStateException(
                    "Site '" + identifier + "' defines unknown language: " + languageId);
        }
    }

    // templates
    NodeList templateNodes = XPathHelper.selectList(config, "ns:templates/ns:template", xpathProcessor);
    PageTemplate firstTemplate = null;
    for (int i = 0; i < templateNodes.getLength(); i++) {
        PageTemplate template = PageTemplateImpl.fromXml(templateNodes.item(i), xpathProcessor);
        boolean isDefault = ConfigurationUtils.isDefault(templateNodes.item(i));
        if (isDefault && site.getDefaultTemplate() != null) {
            logger.warn("Site '{}' defines more than one default templates", site.getIdentifier());
        } else if (isDefault) {
            site.setDefaultTemplate(template);
            logger.debug("Site '{}' uses default template '{}'", site.getIdentifier(),
                    template.getIdentifier());
        } else {
            site.addTemplate(template);
            logger.debug("Added template '{}' to site '{}'", template.getIdentifier(), site.getIdentifier());
        }
        if (firstTemplate == null)
            firstTemplate = template;
    }

    // Make sure we have a default template
    if (site.getDefaultTemplate() == null) {
        if (firstTemplate == null)
            throw new IllegalStateException(
                    "Site '" + site.getIdentifier() + "' does not specify any page templates");
        logger.warn("Site '{}' does not specify a default template. Using '{}'", site.getIdentifier(),
                firstTemplate.getIdentifier());
        site.setDefaultTemplate(firstTemplate);
    }

    // security
    String securityConfiguration = XPathHelper.valueOf(config, "ns:security/ns:configuration", xpathProcessor);
    if (securityConfiguration != null) {
        URL securityConfig = null;

        // If converting the path into a URL fails, we are assuming that the
        // configuration is part of the bundle
        try {
            securityConfig = new URL(securityConfiguration);
        } catch (MalformedURLException e) {
            logger.debug("Security configuration {} is pointing to the bundle", securityConfiguration);
            securityConfig = SiteImpl.class.getResource(securityConfiguration);
            if (securityConfig == null) {
                throw new IllegalStateException("Security configuration " + securityConfig + " of site '"
                        + site.getIdentifier() + "' cannot be located inside of bundle", e);
            }
        }
        site.setSecurity(securityConfig);
    }

    // administrator
    Node adminNode = XPathHelper.select(config, "ns:security/ns:administrator", xpathProcessor);
    if (adminNode != null) {
        site.setAdministrator(SiteAdminImpl.fromXml(adminNode, site, xpathProcessor));
    }

    // digest policy
    Node digestNode = XPathHelper.select(config, "ns:security/ns:digest", xpathProcessor);
    if (digestNode != null) {
        site.setDigestType(DigestType.valueOf(digestNode.getFirstChild().getNodeValue()));
    }

    // role definitions
    NodeList roleNodes = XPathHelper.selectList(config, "ns:security/ns:roles/ns:*", xpathProcessor);
    for (int i = 0; i < roleNodes.getLength(); i++) {
        Node roleNode = roleNodes.item(i);
        String roleName = roleNode.getLocalName();
        String localRoleName = roleNode.getFirstChild().getNodeValue();
        if (Security.SITE_ADMIN_ROLE.equals(roleName))
            site.addLocalRole(Security.SITE_ADMIN_ROLE, localRoleName);
        if (Security.PUBLISHER_ROLE.equals(roleName))
            site.addLocalRole(Security.PUBLISHER_ROLE, localRoleName);
        if (Security.EDITOR_ROLE.equals(roleName))
            site.addLocalRole(Security.EDITOR_ROLE, localRoleName);
        if (Security.GUEST_ROLE.equals(roleName))
            site.addLocalRole(Security.GUEST_ROLE, localRoleName);
    }

    // options
    Node optionsNode = XPathHelper.select(config, "ns:options", xpathProcessor);
    OptionsHelper.fromXml(optionsNode, site, xpathProcessor);

    return site;
}

From source file:com.rapidminer.tools.Tools.java

public static void findImplementationsInJar(ClassLoader loader, JarFile jar, Class<?> superClass,
        List<String> implementations) {
    Enumeration<JarEntry> e = jar.entries();
    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        String name = entry.getName();
        int dotClass = name.lastIndexOf(".class");
        if (dotClass < 0) {
            continue;
        }/*from www .  j a  v  a2  s.  c o  m*/
        name = name.substring(0, dotClass);
        name = name.replaceAll("/", "\\.");
        try {
            Class<?> c = loader.loadClass(name);
            if (superClass.isAssignableFrom(c)) {
                if (!java.lang.reflect.Modifier.isAbstract(c.getModifiers())) {
                    implementations.add(name);
                }
            }
        } catch (Throwable t) {
        }
    }
}

From source file:com.edgenius.wiki.render.impl.FilterPipeImpl.java

public void load() throws FilterInitializeException {
    ClassLoader classLoader = Filter.class.getClassLoader();
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter configure XML file
    try {/* w w  w .  j a va2 s .  c  om*/
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader reader = parser.getXMLReader();

        reader.setContentHandler(this.new FilterMetaParaser());
        reader.parse(new InputSource(classLoader.getResourceAsStream(filterResource)));
    } catch (Exception e) {
        log.error("Unable load filter configuare file " + filterResource, e);
        throw new FilterInitializeException(e);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter Pattern resource bundle file
    Properties patternResource = new Properties();
    try {
        patternResource.load(classLoader.getResourceAsStream(filterResourcePattern));
    } catch (Exception e) {
        log.error("Unable load PatternFilter pattern file " + filterResourcePattern, e);
        throw new FilterInitializeException(e);
    }

    Map<Integer, Filter> sortSet = new TreeMap<Integer, Filter>(new CompareToComparator());
    Map<Integer, RegionContentFilter> regionSortSet = new TreeMap<Integer, RegionContentFilter>(
            new CompareToComparator());
    for (FilterMetadata filterMeta : filterMetaList) {
        try {
            Object obj = classLoader.loadClass(filterMeta.getClassName().trim()).newInstance();
            if (obj instanceof Filter) {
                if (obj instanceof MacroFilter)
                    ((MacroFilter) obj).setMacroMgr(macroManager);

                //initial filter, if it is patternFilter, then do further initial
                if (obj instanceof PatternFilter) {
                    //!!! this markupPring must happen before setRegex() which may need getMarkupPrint() to build regex
                    String markupPrintVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MARKUP_PRINT);
                    if (!StringUtils.isBlank(markupPrintVal)) {
                        ((PatternFilter) obj).setMarkupPrint(markupPrintVal);
                    }
                    String matchVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MATCH);
                    if (!StringUtils.isBlank(matchVal)) {
                        //special for link replacer
                        if (obj instanceof LinkFilter) {
                            linkReplacerFilter.setRegex(matchVal);
                        }
                        ((PatternFilter) obj).setRegex(matchVal);
                    }
                    String printVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_PRINT);
                    if (!StringUtils.isBlank(printVal)) {
                        ((PatternFilter) obj).setReplacement(printVal);
                    }
                    String htmlIDVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_HTML_IDENTIFIER);
                    if (!StringUtils.isBlank(htmlIDVal)) {
                        ((PatternFilter) obj).setHTMLIdentifier(htmlIDVal);
                    }

                }
                filterNameMap.put(obj.getClass().getName(), (Filter) obj);

                ((Filter) obj).init();

                //new line filter always be last, but need special handle. see MarkupRenderEngineImpl.render()
                sortSet.put(filterMeta.getOrder(), (Filter) obj);
                if (obj instanceof RegionContentFilter) {
                    regionSortSet.put(filterMeta.getOrder(), (RegionContentFilter) obj);
                }

                log.info("Filter loaded into FilterPipe:" + obj.getClass().getName());
            } else {
                log.warn("Class " + obj.getClass().getName() + " does not implement Filter interface. "
                        + "It cannot be loaded into FilterPipe.");
            }
        } catch (InstantiationException e) {
            log.error("Filter failed on Instantiation " + filterMeta, e);
        } catch (IllegalAccessException e) {
            log.error("Filter failed on IllegalAccessException " + filterMeta, e);
        } catch (ClassNotFoundException e) {
            log.error("Filter ClassNotFoundException failed " + filterMeta, e);
        }
    }

    linkReplacerFilter.init();

    filterList.clear();
    filterList.addAll(sortSet.values());
    regionFilterList.clear();
    regionFilterList.addAll(regionSortSet.values());
}

From source file:io.neba.core.logviewer.LogfileViewerConsolePluginTest.java

@Test
@SuppressWarnings("unchecked")
public void testLogViewerToleratesMissingDecoratedObjectFactoryFactory() throws Exception {
    ClassLoader classLoaderWithoutDecoratedObjectFactory = new ClassLoader(getClass().getClassLoader()) {
        @Override/*from  w  ww  .j  av  a  2 s . com*/
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (DecoratedObjectFactory.class.getName().equals(name)) {
                // This optional dependency is not present on the class path in this test scenario.
                throw new ClassNotFoundException("THIS IS AN EXPECTED TEST EXCEPTION. The presence of "
                        + DecoratedObjectFactory.class.getName() + " is optional.");
            }
            if (LogfileViewerConsolePlugin.class.getName().equals(name)) {
                // Define the test subject's class class in this class loader, thus its dependencies -
                // such as the DecoratedObjectFactory - are also loaded via this class loader.
                try {
                    byte[] classFileData = toByteArray(
                            getResourceAsStream(name.replace('.', '/').concat(".class")));
                    return defineClass(name, classFileData, 0, classFileData.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException("Unable to load " + name + ".", e);
                }
            }

            return super.loadClass(name);
        }
    };

    Class<? extends Servlet> type = (Class<? extends Servlet>) classLoaderWithoutDecoratedObjectFactory
            .loadClass(LogfileViewerConsolePlugin.class.getName());
    Servlet logViewerInstance = type.newInstance();

    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    doReturn(context).when(config).getServletContext();
    injectTailServlet(logViewerInstance);
    invokeInit(logViewerInstance, config);
    invokeDestroy(logViewerInstance);

    verify(context, never()).setAttribute(any(), any());
    verify(context, never()).removeAttribute(any());
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.widgets.CellPanelInfo.java

/**
 * Contributes <code>"Cell"</code> complex property for each {@link WidgetInfo} child of this
 * {@link CellPanelInfo}./*  ww w  .j  a  v a 2s .c o m*/
 */
private void contributeCellProperties() {
    final CellPanelInfo panel = this;
    addBroadcastListener(new XmlObjectAddProperties() {
        public void invoke(XmlObjectInfo object, List<Property> properties) throws Exception {
            if (object instanceof WidgetInfo && object.getParent() == panel) {
                WidgetInfo widget = (WidgetInfo) object;
                // prepare "Cell" property
                Property cellProperty = (Property) widget.getArbitraryValue(this);
                if (cellProperty == null) {
                    cellProperty = getCellComplexProperty(widget);
                    widget.putArbitraryValue(this, cellProperty);
                }
                // add "Cell" property
                properties.add(cellProperty);
            }
        }

        private Property getCellComplexProperty(WidgetInfo widget) throws Exception {
            ClassLoader editorLoader = getContext().getClassLoader();
            String namespace = StringUtils.substringBefore(getElement().getTag(), ":") + ":";
            // "width"
            Property widthProperty;
            {
                ExpressionAccessor expressionAccessor = new CellExpressionAccessor(namespace, "width");
                GenericPropertyDescription propertyDescription = new GenericPropertyDescription(null, "width",
                        String.class, expressionAccessor);
                propertyDescription.setEditor(StringPropertyEditor.INSTANCE);
                propertyDescription.setConverter(StringConverter.INSTANCE);
                widthProperty = new GenericPropertyImpl(widget, propertyDescription);
            }
            // "height"
            Property heightProperty;
            {
                ExpressionAccessor expressionAccessor = new CellExpressionAccessor(namespace, "height");
                GenericPropertyDescription propertyDescription = new GenericPropertyDescription(null, "height",
                        String.class, expressionAccessor);
                propertyDescription.setEditor(StringPropertyEditor.INSTANCE);
                propertyDescription.setConverter(StringConverter.INSTANCE);
                heightProperty = new GenericPropertyImpl(widget, propertyDescription);
            }
            // "horizontalAlignment"
            Property horizontalAlignmentProperty;
            {
                StaticFieldPropertyEditor propertyEditor = new StaticFieldPropertyEditor();
                Class<?> hasHorizontalAlignmentClass = editorLoader
                        .loadClass("com.google.gwt.user.client.ui.HasHorizontalAlignment");
                propertyEditor.configure(hasHorizontalAlignmentClass,
                        new String[] { "ALIGN_LEFT", "ALIGN_CENTER", "ALIGN_RIGHT" });
                Object defaultValue = ReflectionUtils.getFieldObject(hasHorizontalAlignmentClass, "ALIGN_LEFT");
                // create property
                ExpressionAccessor expressionAccessor = new CellExpressionAccessor(namespace,
                        "horizontalAlignment");
                GenericPropertyDescription propertyDescription = new GenericPropertyDescription(null,
                        "horizontalAlignment", String.class, expressionAccessor);
                propertyDescription.setEditor(propertyEditor);
                propertyDescription.setDefaultValue(defaultValue);
                horizontalAlignmentProperty = new GenericPropertyImpl(widget, propertyDescription);
            }
            // "verticalAlignment"
            Property verticalAlignmentProperty;
            {
                StaticFieldPropertyEditor propertyEditor = new StaticFieldPropertyEditor();
                Class<?> hasVerticalAlignmentClass = editorLoader
                        .loadClass("com.google.gwt.user.client.ui.HasVerticalAlignment");
                propertyEditor.configure(hasVerticalAlignmentClass,
                        new String[] { "ALIGN_TOP", "ALIGN_MIDDLE", "ALIGN_BOTTOM" });
                Object defaultValue = ReflectionUtils.getFieldObject(hasVerticalAlignmentClass, "ALIGN_TOP");
                // create property
                ExpressionAccessor expressionAccessor = new CellExpressionAccessor(namespace,
                        "verticalAlignment");
                GenericPropertyDescription propertyDescription = new GenericPropertyDescription(null,
                        "verticalAlignment", String.class, expressionAccessor);
                propertyDescription.setEditor(propertyEditor);
                propertyDescription.setDefaultValue(defaultValue);
                verticalAlignmentProperty = new GenericPropertyImpl(widget, propertyDescription);
            }
            // create complex "Cell" property
            ComplexProperty cellProperty = new ComplexProperty("Cell", "(cell properties)");
            cellProperty.setCategory(PropertyCategory.system(7));
            cellProperty.setProperties(new Property[] { widthProperty, heightProperty,
                    horizontalAlignmentProperty, verticalAlignmentProperty });
            return cellProperty;
        }
    });
}