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.bfd.harpc.config.ClientConfig.java

/**
 * ?/*  ww  w  .  ja va 2s  .  c  o  m*/
 * <p>
 * 
 * @param registryConfig
 * @return {client?}
 * @throws Exception
 */
public T createProxy(RegistryConfig registryConfig) throws Exception {
    check(); // ?

    // 
    IRegistry registry;
    ServerNode clientNode = new ServerNode(NetUtils.getLocalHost(), 0);
    if (getAddress() != null) {
        registry = new DefaultRegistry(getAddress());
    } else if (registryConfig != null) {
        registry = new ZkClientRegistry(service, registryConfig.obtainZkClient(), clientNode);
    } else {
        throw new RpcException(RpcException.CONFIG_EXCEPTION,
                "The params 'addess' and '<registry>' node cannot all unexist!");
    }

    registry.register(genConfigJson());

    // 
    RpcMonitor rpcMonitor = null;
    // client?monitor
    // if (monitor) {
    // rpcMonitor = new RpcMonitor(interval,
    // registryConfig.obtainZkClient(), service, true);
    // }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // Iface?
    Class<?> objectClass = classLoader.loadClass(iface);

    GenericKeyedObjectPool<ServerNode, T> pool = bulidClientPool(classLoader, objectClass);
    DynamicHostSet hostSet = registry.findAllService();

    HeartBeatManager<T> heartBeatManager = new HeartBeatManager<T>(hostSet, heartbeat, heartbeatTimeout,
            heartbeatTimes, heartbeatInterval, pool);
    heartBeatManager.startHeatbeatTimer();

    this.registry = registry;
    this.rpcMonitor = rpcMonitor;
    this.heartBeatManager = heartBeatManager;
    this.pool = pool;

    // ShutdownHook
    addShutdownHook(registry, rpcMonitor, heartBeatManager);

    LoadBalancer<ServerNode> loadBalancer = LoadBalancerFactory.createLoadBalancer(registry.findAllService(),
            loadbalance, heartBeatManager);

    Invoker invoker = new DefaultInvoker<T>(clientNode, pool, loadBalancer, retry, rpcMonitor, hostSet);
    DynamicClientHandler dynamicClientHandler = new DynamicClientHandler(invoker);
    return dynamicClientHandler.<T>bind(classLoader, objectClass);
}

From source file:org.bytesoft.bytetcc.supports.dubbo.CompensableDubboConfigValidator.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    final Map<String, Class<?>> beanClassMap = new HashMap<String, Class<?>>();
    final Map<String, BeanDefinition> serviceMap = new HashMap<String, BeanDefinition>();
    final Map<String, BeanDefinition> references = new HashMap<String, BeanDefinition>();

    String[] beanNameArray = beanFactory.getBeanDefinitionNames();
    for (int i = 0; i < beanNameArray.length; i++) {
        String beanName = beanNameArray[i];
        BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        Class<?> beanClass = null;
        try {/*from w  w w  . ja v a  2s .co  m*/
            beanClass = cl.loadClass(beanClassName);
            beanClassMap.put(beanName, beanClass);
        } catch (Exception ex) {
            continue;
        }

        if (com.alibaba.dubbo.config.spring.ServiceBean.class.equals(beanClass)) {
            serviceMap.put(beanName, beanDef);
        } else if (com.alibaba.dubbo.config.spring.ReferenceBean.class.equals(beanClass)) {
            references.put(beanName, beanDef);
        }

    }

    for (Iterator<Map.Entry<String, BeanDefinition>> itr = serviceMap.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<String, BeanDefinition> entry = itr.next();
        String beanKey = entry.getKey();
        BeanDefinition beanDef = entry.getValue();
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        PropertyValue ref = mpv.getPropertyValue("ref");
        PropertyValue filter = mpv.getPropertyValue("filter");
        PropertyValue group = mpv.getPropertyValue("group");
        if (ref == null || ref.getValue() == null
                || RuntimeBeanReference.class.equals(ref.getValue().getClass()) == false) {
            continue;
        }
        RuntimeBeanReference beanRef = (RuntimeBeanReference) ref.getValue();
        Class<?> refClass = beanClassMap.get(beanRef.getBeanName());
        if (refClass.getAnnotation(Compensable.class) == null) {
            continue;
        }

        if (group == null || group.getValue() == null
                || KEY_GROUP_COMPENSABLE.equals(group.getValue()) == false) {
            logger.warn("The value of attr 'group'(beanId= {}) should be 'org.bytesoft.bytetcc'.", beanKey);
            continue;
        } else if (filter == null || filter.getValue() == null
                || KEY_FILTER_COMPENSABLE.equals(filter.getValue()) == false) {
            logger.warn("The value of attr 'filter'(beanId= {}) should be 'compensable'.", beanKey);
            continue;
        }

        PropertyValue timeoutPv = mpv.getPropertyValue(KEY_TIMEOUT);
        Object value = timeoutPv == null ? null : timeoutPv.getValue();
        if (String.valueOf(Integer.MAX_VALUE).equals(value) == false) {
            throw new FatalBeanException(String.format("Timeout value(beanId= %s) must be %s." //
                    , beanKey, Integer.MAX_VALUE));
        }
    }

    for (Iterator<Map.Entry<String, BeanDefinition>> itr = references.entrySet().iterator(); itr.hasNext();) {
        Map.Entry<String, BeanDefinition> entry = itr.next();
        String beanKey = entry.getKey();
        BeanDefinition beanDef = entry.getValue();
        MutablePropertyValues mpv = beanDef.getPropertyValues();
        PropertyValue filter = mpv.getPropertyValue("filter");
        PropertyValue group = mpv.getPropertyValue("group");

        if (group == null || group.getValue() == null
                || KEY_GROUP_COMPENSABLE.equals(group.getValue()) == false) {
            logger.warn("The value of attr 'group'(beanId= {}) should be 'org.bytesoft.bytetcc'.", beanKey);
            continue;
        } else if (filter == null || filter.getValue() == null
                || KEY_FILTER_COMPENSABLE.equals(filter.getValue()) == false) {
            logger.warn("The value of attr 'filter'(beanId= {}) should be 'compensable'.", beanKey);
            continue;
        }

        PropertyValue timeoutPv = mpv.getPropertyValue(KEY_TIMEOUT);
        Object value = timeoutPv == null ? null : timeoutPv.getValue();
        if (String.valueOf(Integer.MAX_VALUE).equals(value) == false) {
            throw new FatalBeanException(
                    String.format("The value of attribute 'timeout' (beanId= %s) must be %s." //
                            , beanKey, Integer.MAX_VALUE));
        }
    }
}

From source file:any.Linker.java

/** 
 * initialise with properties// w  ww . j a v  a2s. c o  m
 * 
 * @param properties
 */
public Linker(Properties properties) {
    this.properties = properties;

    final LoopConnection loop = new LoopConnection(this);
    //      namedCon.put("host", loop);
    namedCon.put("loop", loop); // FIXME

    // setup services from properties file
    ClassLoader cl;
    cl = Linker.class.getClassLoader();
    try {

        for (Map.Entry<Object, Object> p : properties.entrySet()) {

            String key = p.getKey().toString();

            if (key.startsWith("serve.")) {

                String name = key.substring(6);
                String classstr = p.getValue().toString();

                if (logger.isDebugEnabled())
                    logger.debug("setup servable with name: " + name + " and " + classstr);

                Servable s = (Servable) cl.loadClass(classstr).newInstance();
                servableMap.put(name, s);
                s.init(properties, loop.getOutQueue(), this);
            }
        }

    } catch (InstantiationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    ConfigServable configServable = new ConfigServable();
    servableMap.put("config", configServable);
    configServable.init(properties, null, null);

}

From source file:com.google.gdt.eclipse.designer.model.widgets.panels.LayoutPanelInfo.java

/**
 * @return the <code>Unit</code> object by its name.
 *//*from  ww  w.ja  v  a 2  s.c  om*/
private Object getUnitByName(String name) throws ClassNotFoundException {
    ClassLoader classLoader = JavaInfoUtils.getClassLoader(this);
    Class<?> classUnit = classLoader.loadClass("com.google.gwt.dom.client.Style$Unit");
    return ReflectionUtils.getFieldObject(classUnit, name);
}

From source file:biz.wolschon.finance.jgnucash.JGnucash.java

/**
 * @return the {@link AccountAction} we have including the ones offered by plugins.
 *///from   w w  w  .  j  a v a  2s .co  m
@SuppressWarnings("unchecked")
@Override
protected Collection<AccountAction> getAccountActions() {
    if (myAccountActions == null) {
        myAccountActions = super.getAccountActions();

        PluginManager manager = getPluginManager();
        // if we are configured for the plugin-api
        if (manager != null) {
            ExtensionPoint toolExtPoint = manager.getRegistry().getExtensionPoint(getPluginDescriptor().getId(),
                    "AccountAction");
            for (Iterator<Extension> it = toolExtPoint.getConnectedExtensions().iterator(); it.hasNext();) {
                Extension ext = it.next();
                String pluginName = "unknown";

                try {
                    getPluginManager().activatePlugin(ext.getDeclaringPluginDescriptor().getId());
                    // Get plug-in class loader.
                    ClassLoader classLoader = getPluginManager()
                            .getPluginClassLoader(ext.getDeclaringPluginDescriptor());
                    // Load Tool class.
                    Class toolCls = classLoader.loadClass(ext.getParameter("class").valueAsString());
                    // Create Tool instance.
                    Object o = toolCls.newInstance();
                    if (!(o instanceof AccountAction)) {
                        LOGGER.error("Plugin '" + pluginName + "' does not implement AccountAction-interface.");
                        JOptionPane.showMessageDialog(this, "Error",
                                "The AccountAction-Plugin '" + pluginName + "'"
                                        + " does not implement AccountAction-interface.",
                                JOptionPane.ERROR_MESSAGE);
                    } else {
                        myAccountActions.add((AccountAction) o);
                    }
                } catch (Exception e) {
                    LOGGER.error("cannot load TransactionMenuAction-Plugin '" + pluginName + "'", e);
                    JOptionPane.showMessageDialog(this, "Error",
                            "Cannot load AccountAction-Plugin '" + pluginName + "'", JOptionPane.ERROR_MESSAGE);
                }
            }
        }

    }
    return myAccountActions;
}

From source file:net.mojodna.sprout.SproutAutoLoaderPlugIn.java

private void autoloadFromDirectory(final ClassLoader loader, final int baseLength, File directory) {
    File[] files = directory.listFiles();

    for (int i = 0; i < files.length; i++) {
        File file = files[i];/*  www  .  j a v a 2 s . c  om*/

        if (file.isDirectory()) {
            autoloadFromDirectory(loader, baseLength, file);
        } else {
            String path = file.getPath();

            if (path.endsWith(".class")) {
                int length = path.length();
                String className = path.substring(baseLength, length - 6).replace('/', '.');

                try {
                    Class c = loader.loadClass(className);

                    if (decendsFrom(ActionForm.class, c)) {
                        loadForm(c);
                    } else if (decendsFrom(org.apache.struts.action.Action.class, c)) {
                        loadAction(c);
                    }
                } catch (ClassNotFoundException ex) {
                    log.error("Failed to load class, " + ex.getMessage());
                }
            }
        }
    }
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.util.NameSupport.java

/**
 * Adds <code>JField</code> with given name and @UiField annotation into "form" <code>JType</code>
 * .//from   w ww .  ja v a 2  s  .c o  m
 */
private void addFormJField(Class<?> componentClass, String name) throws Exception {
    IDevModeBridge bridge = m_context.getState().getDevModeBridge();
    ClassLoader devClassLoader = bridge.getDevClassLoader();
    // prepare "form" JType
    Object formType = bridge.findJType(m_context.getFormType().getFullyQualifiedName());
    // prepare @UiField annotation instance
    Class<?> uiFieldAnnotationClass = devClassLoader.loadClass("com.google.gwt.uibinder.client.UiField");
    java.lang.annotation.Annotation annotation = (java.lang.annotation.Annotation) Proxy.newProxyInstance(
            uiFieldAnnotationClass.getClassLoader(), new Class[] { uiFieldAnnotationClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) {
                    return Boolean.TRUE;
                }
            });
    // add new JField
    Object newField;
    {
        Constructor<?> fieldConstructor;
        Class<?> fieldClass;
        if (m_context.getState().getVersion().isHigherOrSame(Utils.GWT_2_2)) {
            fieldClass = devClassLoader.loadClass("com.google.gwt.dev.javac.typemodel.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.dev.javac.typemodel.JClassType,java.lang.String,java.util.Map)");
        } else {
            fieldClass = devClassLoader.loadClass("com.google.gwt.core.ext.typeinfo.JField");
            fieldConstructor = ReflectionUtils.getConstructorBySignature(fieldClass,
                    "<init>(com.google.gwt.core.ext.typeinfo.JClassType,java.lang.String,java.util.Map)");
        }
        newField = fieldConstructor.newInstance(formType, name,
                ImmutableMap.of(uiFieldAnnotationClass, annotation));
    }
    // set "widget" JType for JField
    Object widgetType = bridge.findJType(ReflectionUtils.getCanonicalName(componentClass));
    ReflectionUtils.invokeMethod(newField, "setType(com.google.gwt.core.ext.typeinfo.JType)", widgetType);
}

From source file:backup.namenode.NameNodeBackupServicePlugin.java

@Override
public void start(Object service) {
    UserGroupInformation ugi;//from   w w w . ja  v  a2s . c  om
    try {
        ugi = UserGroupInformation.getCurrentUser();
        LOG.info("Starting NameNodeBackupServicePlugin with ugi {}", ugi);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Configuration conf = getConf();
    NameNode namenode = (NameNode) service;
    BlockManager blockManager = namenode.getNamesystem().getBlockManager();
    // This object is created here so that it's lifecycle follows the namenode
    try {
        restoreProcessor = SingletonManager.getManager(NameNodeRestoreProcessor.class).getInstance(namenode,
                () -> new NameNodeRestoreProcessor(getConf(), namenode, ugi));
        LOG.info("NameNode Backup plugin setup using UGI {}", ugi);

        NameNodeBackupRPCImpl backupRPCImpl = new NameNodeBackupRPCImpl(blockManager);

        InetSocketAddress listenerAddress = namenode.getServiceRpcAddress();
        int ipcPort = listenerAddress.getPort();
        String bindAddress = listenerAddress.getAddress().getHostAddress();
        int port = conf.getInt(DFS_BACKUP_NAMENODE_RPC_PORT_KEY, DFS_BACKUP_NAMENODE_RPC_PORT_DEFAULT);
        if (port == 0) {
            port = ipcPort + 1;
        }
        server = new RPC.Builder(conf).setBindAddress(bindAddress).setPort(port).setInstance(backupRPCImpl)
                .setProtocol(NameNodeBackupRPC.class).build();
        ServiceAuthorizationManager serviceAuthorizationManager = server.getServiceAuthorizationManager();
        serviceAuthorizationManager.refresh(conf, new BackupPolicyProvider());
        server.start();

        LOG.info("NameNode Backup RPC listening on {}", port);

        int httpPort = getConf().getInt(DFS_BACKUP_NAMENODE_HTTP_PORT_KEY,
                DFS_BACKUP_NAMENODE_HTTP_PORT_DEFAULT);
        if (httpPort != 0) {
            ClassLoader classLoader = getClassLoader();
            if (classLoader != null) {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                try {
                    BackupWebService<Stats> stats = getBackupWebService(ugi, blockManager, restoreProcessor);

                    // Have to setup classloader in thread context to get the static
                    // files in the http server tp be setup correctly.
                    Thread.currentThread().setContextClassLoader(classLoader);
                    Class<?> backupStatusServerClass = classLoader.loadClass(BACKUP_WEB_BACKUP_WEB_SERVER);

                    Object server = DuckTypeUtil.newInstance(backupStatusServerClass,
                            new Class[] { Integer.TYPE, BackupWebService.class },
                            new Object[] { httpPort, stats });
                    httpServer = DuckTypeUtil.wrap(HttpServer.class, server);
                    httpServer.start();
                    LOG.info("NameNode Backup HTTP listening on {}", httpPort);
                } finally {
                    Thread.currentThread().setContextClassLoader(contextClassLoader);
                }
            } else {
                LOG.info("NameNode Backup HTTP classes not found.");
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.sbt.services.endpoints.AbstractEndpoint.java

@Override
public ClientService getClientService() throws ClientServicesException {
    // If the client service class is defined, then we instanciate it
    String cls = getClientServiceClass();
    if (StringUtil.isNotEmpty(cls)) {
        try {/* w w w.  j a  v  a  2 s . c om*/
            ClientService clientService = null;
            // order of precedence for the classloader to use 
            Context ctx = Context.getUnchecked();
            Application app = Application.getUnchecked();
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (ctx != null) {
                clientService = (ClientService) ctx.getClassLoader().loadClass(cls).newInstance();
            } else if (app != null) {
                clientService = (ClientService) app.getClassLoader().loadClass(cls).newInstance();
            } else if (cl != null) {
                clientService = (ClientService) cl.loadClass(cls).newInstance();
            } else {
                clientService = (ClientService) Class.forName(cls).newInstance();
            }
            // set endpoint
            clientService.setEndpoint(this);
            clientService.setListener(this.listener);
            return clientService;
        } catch (Exception ex) {
            throw new ClientServicesException(ex, "Cannot create ClientService class {0}", cls);
        }
    }
    ClientService clientService = new GenericService(this);
    clientService.setListener(this.listener);
    return clientService;
}