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:org.bytesoft.bytetcc.supports.dubbo.validator.ReferenceConfigValidator.java

public void validate() throws BeansException {
    MutablePropertyValues mpv = this.beanDefinition.getPropertyValues();
    PropertyValue retries = mpv.getPropertyValue("retries");
    PropertyValue loadbalance = mpv.getPropertyValue("loadbalance");
    PropertyValue cluster = mpv.getPropertyValue("cluster");
    PropertyValue filter = mpv.getPropertyValue("filter");

    if (retries == null || retries.getValue() == null || "0".equals(retries.getValue()) == false) {
        throw new FatalBeanException(
                String.format("The value of attr 'retries'(beanId= %s) should be '0'.", this.beanName));
    } else if (loadbalance == null || loadbalance.getValue() == null
            || "compensable".equals(loadbalance.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attr 'loadbalance'(beanId= %s) should be 'compensable'.", this.beanName));
    } else if (cluster == null || cluster.getValue() == null
            || "failfast".equals(cluster.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attribute 'cluster' (beanId= %s) must be 'failfast'.", this.beanName));
    } else if (filter == null || filter.getValue() == null
            || "compensable".equals(filter.getValue()) == false) {
        throw new FatalBeanException(String
                .format("The value of attr 'filter'(beanId= %s) should be 'compensable'.", this.beanName));
    }//  w ww. ja va  2  s .c  o m

    PropertyValue pv = mpv.getPropertyValue("interface");
    String clazzName = String.valueOf(pv.getValue());
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    Class<?> clazz = null;
    try {
        clazz = cl.loadClass(clazzName);
    } catch (Exception ex) {
        throw new FatalBeanException(String.format("Cannot load class %s.", clazzName));
    }

    Method[] methodArray = clazz.getMethods();
    for (int i = 0; i < methodArray.length; i++) {
        Method method = methodArray[i];
        boolean declared = false;
        Class<?>[] exceptionTypeArray = method.getExceptionTypes();
        for (int j = 0; j < exceptionTypeArray.length; j++) {
            Class<?> exceptionType = exceptionTypeArray[j];
            if (RemotingException.class.isAssignableFrom(exceptionType)) {
                declared = true;
                break;
            }
        }

        if (declared == false) {
            // throw new FatalBeanException(String.format(
            // "The remote call method(%s) must be declared to throw a remote exception:
            // org.bytesoft.compensable.RemotingException!",
            // method));
            logger.warn("The remote call method({}) should be declared to throw a remote exception: {}!",
                    method, RemotingException.class.getName());
        }

    }

}

From source file:ch.entwine.weblounge.common.impl.content.page.PageletRendererImpl.java

/**
 * Initializes this pagelet renderer from an XML node that was generated using
 * {@link #toXml()}./*from  w  ww.  j  a v a2 s  .c o m*/
 * 
 * @param node
 *          the pagelet renderer node
 * @param xpath
 *          the xpath processor
 * @throws IllegalStateException
 *           if the pagelet renderer cannot be parsed
 * @see #fromXml(Node)
 * @see #toXml()
 */
public static PageletRenderer fromXml(Node node, XPath xpath) throws IllegalStateException {

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // Identifier
    String id = XPathHelper.valueOf(node, "@id", xpath);
    if (id == null)
        throw new IllegalStateException("Missing id in page template definition");

    // Class
    String className = XPathHelper.valueOf(node, "m:class", xpath);

    // Create the pagelet renderer
    PageletRenderer renderer = null;
    if (className != null) {
        Class<? extends PageletRenderer> c = null;
        try {
            c = (Class<? extends PageletRenderer>) classLoader.loadClass(className);
            renderer = c.newInstance();
            renderer.setIdentifier(id);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(
                    "Implementation " + className + " for pagelet renderer '" + id + "' not found", e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(
                    "Error instantiating impelementation " + className + " for pagelet renderer '" + id + "'",
                    e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Access violation instantiating implementation " + className
                    + " for pagelet renderer '" + id + "'", e);
        } catch (Throwable t) {
            throw new IllegalStateException(
                    "Error loading implementation " + className + " for pagelet renderer '" + id + "'", t);
        }
    } else {
        renderer = new PageletRendererImpl();
        renderer.setIdentifier(id);
    }

    // Renderer url
    NodeList rendererUrlNodes = XPathHelper.selectList(node, "m:renderer", xpath);
    if (rendererUrlNodes.getLength() == 0)
        throw new IllegalStateException("Missing renderer in page template definition");
    for (int i = 0; i < rendererUrlNodes.getLength(); i++) {
        Node rendererUrlNode = rendererUrlNodes.item(i);
        URL rendererUrl = null;
        Node typeNode = rendererUrlNode.getAttributes().getNamedItem("type");
        String type = (typeNode != null) ? typeNode.getNodeValue() : RendererType.Page.toString();
        try {
            rendererUrl = new URL(rendererUrlNode.getFirstChild().getNodeValue());
            renderer.addRenderer(rendererUrl, type);
        } catch (MalformedURLException e) {
            throw new IllegalStateException(
                    "Malformed renderer url in page template definition: " + rendererUrlNode);
        }
    }

    // Composeable
    renderer.setComposeable("true".equals(XPathHelper.valueOf(node, "@composeable", xpath)));

    // Preview mode
    String previewMode = XPathHelper.valueOf(node, "m:preview", xpath);
    if (previewMode != null)
        renderer.setPreviewMode(PagePreviewMode.parse(previewMode));

    // Editor url
    String editorUrlNode = XPathHelper.valueOf(node, "m:editor", xpath);
    try {
        if (editorUrlNode != null) {
            URL editorUrl = new URL(editorUrlNode);
            renderer.setEditor(editorUrl);
        }
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Malformed editor url in page template definition: " + editorUrlNode);
    }

    // client revalidation time
    String recheck = XPathHelper.valueOf(node, "m:recheck", xpath);
    if (recheck != null) {
        try {
            renderer.setClientRevalidationTime(ConfigurationUtils.parseDuration(recheck));
        } catch (NumberFormatException e) {
            throw new IllegalStateException(
                    "The pagelet renderer revalidation time is malformed: '" + recheck + "'");
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "The pagelet renderer revalidation time is malformed: '" + recheck + "'");
        }
    }

    // cache expiration time
    String valid = XPathHelper.valueOf(node, "m:valid", xpath);
    if (valid != null) {
        try {
            renderer.setCacheExpirationTime(ConfigurationUtils.parseDuration(valid));
        } catch (NumberFormatException e) {
            throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e);
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException("The pagelet renderer valid time is malformed: '" + valid + "'", e);
        }
    }

    // name
    String name = XPathHelper.valueOf(node, "m:name", xpath);
    renderer.setName(name);

    // scripts
    NodeList scripts = XPathHelper.selectList(node, "m:includes/m:script", xpath);
    for (int i = 0; i < scripts.getLength(); i++) {
        renderer.addHTMLHeader(ScriptImpl.fromXml(scripts.item(i)));
    }

    // links
    NodeList includes = XPathHelper.selectList(node, "m:includes/m:link", xpath);
    for (int i = 0; i < includes.getLength(); i++) {
        renderer.addHTMLHeader(LinkImpl.fromXml(includes.item(i)));
    }

    return renderer;
}

From source file:com.liferay.portal.servlet.SharedServletWrapper.java

public void init(ServletConfig sc) throws ServletException {
    super.init(sc);

    ServletContext ctx = getServletContext();

    _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE,
            StringPool.UNDERLINE);//from www.j av  a 2s.  c  o  m

    _servletClass = sc.getInitParameter("servlet-class");

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {
        _servletInstance = (Servlet) contextClassLoader.loadClass(_servletClass).newInstance();
    } catch (ClassNotFoundException cnfe) {
        throw new ServletException(cnfe.getMessage());
    } catch (IllegalAccessException iae) {
        throw new ServletException(iae.getMessage());
    } catch (InstantiationException ie) {
        throw new ServletException(ie.getMessage());
    }

    if (_servletInstance instanceof HttpServlet) {
        _httpServletInstance = (HttpServlet) _servletInstance;

        _httpServletInstance.init(sc);
    } else {
        _servletInstance.init(sc);
    }
}

From source file:net.mlw.vlh.adapter.jdbc.util.ResultSetMapGenerator.java

/**
 * <p>Loads and returns the <code>Class</code> of the given name.
 * By default, a load from the thread context class loader is attempted.
 * If there is no such class loader, the class loader used to load this
 * class will be utilized.</p>/*w  w w  .j av a  2  s  .  c o m*/
 *
 * @exception SQLException if an exception was thrown trying to load
 *  the specified class
 */
protected Class loadClass(String className) throws SQLException {
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = this.getClass().getClassLoader();
        }
        return (cl.loadClass(className));
    } catch (Exception e) {
        throw new SQLException("Cannot load column class '" + className + "': " + e);
    }
}

From source file:org.jsonschema2pojo.integration.json.RealJsonExamplesIT.java

@Test
public void torrentProducesValidTypes() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/examples/torrent.json", "com.example",
            config("sourceType", "json", "propertyWordDelimiters", "_"));

    Class<?> torrentType = resultsClassLoader.loadClass("com.example.Torrent");

    Object torrent = OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/json/examples/torrent.json"),
            torrentType);/*w  w w  .  j  a v a 2s .  com*/

    Object props = torrentType.getMethod("getProps").invoke(torrent);
    Object prop0 = ((List<?>) props).get(0);
    assertThat((Integer) prop0.getClass().getMethod("getSeedRatio").invoke(prop0), is(1500));

}

From source file:org.jsonschema2pojo.integration.json.RealJsonExamplesIT.java

@Test
public void getUserDataProducesValidTypes() throws Exception {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/json/examples/GetUserData.json",
            "com.example", config("sourceType", "json", "useLongIntegers", true));

    Class<?> userDataType = resultsClassLoader.loadClass("com.example.GetUserData");

    Object userData = OBJECT_MAPPER
            .readValue(this.getClass().getResourceAsStream("/json/examples/GetUserData.json"), userDataType);
    Object result = userDataType.getMethod("getResult").invoke(userData);
    Object data = result.getClass().getMethod("getData").invoke(result);
    Object userUIPref = data.getClass().getMethod("getUserUIPref").invoke(data);

    assertThat(userUIPref.getClass().getMethod("getPimColor").invoke(userUIPref).toString(), is("blue"));

    Object externalAccounts = data.getClass().getMethod("getExternalAccounts").invoke(data);
    Object extAccount = externalAccounts.getClass().getMethod("getExtAccount").invoke(externalAccounts);
    Object extAccount0 = ((List<?>) extAccount).get(0);
    assertThat(extAccount0.getClass().getMethod("getFolder").invoke(extAccount0).toString(), is("Inbox"));

}

From source file:boa.evaluator.BoaEvaluator.java

public void evaluate() {
    final String[] actualArgs = createHadoopProgramArguments();
    final File srcDir = new File(this.COMPILATION_DIR);

    try {/*from  ww w . ja v a  2 s  .co m*/
        final URL srcDirUrl = srcDir.toURI().toURL();

        final ClassLoader cl = new URLClassLoader(new URL[] { srcDirUrl }, ClassLoader.getSystemClassLoader());
        final Class<?> cls = cl.loadClass("boa." + jarToClassname(this.PROG_PATH));
        final Method method = cls.getMethod("main", String[].class);

        method.invoke(null, (Object) actualArgs);
    } catch (final Throwable e) {
        System.err.print(e);
    }
}

From source file:com.openteach.diamond.container.DefaultClassLoaderDelegateHook.java

public Class postFindClass(String name, BundleClassLoader classloader, BundleData data)
        throws ClassNotFoundException {
    // ??groovy??
    if ((name != null) && (name.startsWith("groovy.runtime.metaclass"))) {
        return null;
    }/* www.ja  va 2  s . c  om*/
    for (ClassLoader thirdClassLoader : thirdClassLoaders) {
        if (thirdClassLoader != null) {
            try {
                return thirdClassLoader.loadClass(name);
            } catch (ClassNotFoundException e) {
                // IGNORE,continue find
            }
        }
    }
    return null;
}

From source file:com.googlecode.jsonschema2pojo.integration.json.JsonTypesIT.java

@Test
@SuppressWarnings("rawtypes")
public void arrayTypePropertiesProduceLists() throws Exception {

    ClassLoader resultsClassLoader = generateAndCompile("/json/array.json", "com.example",
            config("sourceType", "json"));

    Class<?> arrayType = resultsClassLoader.loadClass("com.example.Array");
    Class<?> itemType = resultsClassLoader.loadClass("com.example.A");

    Object deserialisedValue = OBJECT_MAPPER.readValue(this.getClass().getResourceAsStream("/json/array.json"),
            arrayType);// w w  w.  ja  v a2  s . c  om

    List<?> valueA = (List) arrayType.getMethod("getA").invoke(deserialisedValue);
    assertThat(((ParameterizedType) arrayType.getMethod("getA").getGenericReturnType())
            .getActualTypeArguments()[0], is(equalTo((Type) itemType)));
    assertThat((Integer) itemType.getMethod("get0").invoke(valueA.get(0)), is(0));
    assertThat((Integer) itemType.getMethod("get1").invoke(valueA.get(1)), is(1));
    assertThat((Integer) itemType.getMethod("get2").invoke(valueA.get(2)), is(2));

    Object valueB = arrayType.getMethod("getB").invoke(deserialisedValue);
    assertThat(valueB, is(instanceOf(List.class)));
    assertThat(((ParameterizedType) arrayType.getMethod("getB").getGenericReturnType())
            .getActualTypeArguments()[0], is(equalTo((Type) Integer.class)));

}

From source file:org.jsonschema2pojo.integration.config.CustomRuleFactoryIT.java

@Test
public void customAnnotatorIsAbleToAddCustomAnnotations()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/format/formattedProperties.json",
            "com.example", config("customRuleFactory", TestRuleFactory.class.getName()));

    Class<?> generatedType = resultsClassLoader.loadClass("com.example.FormattedProperties");

    Method getter = generatedType.getMethod("getStringAsDate");

    Class<?> returnType = getter.getReturnType();
    assertThat(returnType.equals(LocalDate.class), is(true));
}