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.mybatis.spring.extend.SqlSessionFactoryBean.java

private void parseExtTypeAliases(Configuration configuration) {
    if (!hasLength(extTypeAliasesPackage)) {
        return;//from  w  ww .  java 2s  .c o  m
    }
    String prefix = "classpath:";
    String suffix = "/*.class";
    String[] extArr = tokenizeToStringArray(extTypeAliasesPackage,
            ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    ClassLoader classLoader = getClass().getClassLoader();
    try {
        for (String ext : extArr) {
            Resource[] resources = resolver.getResources(prefix + ext + suffix);
            if (resources != null) {
                for (Resource resource : resources) {
                    String classFilePath = resource.getURI().getPath();
                    int index = classFilePath.indexOf("classes");
                    String className = classFilePath.substring(index + 8, classFilePath.length() - 6)
                            .replaceAll("/", ".");
                    Class<?> clz = classLoader.loadClass(className);
                    configuration.getTypeAliasRegistry().registerAlias(clz);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("parse extTypeAliasesPackage failed", e);
    }
}

From source file:com.bfd.harpc.config.ServerConfig.java

/**
 * ??TProcessor/*  w  ww . ja  va2s. c o m*/
 * <p>
 * 
 * @param rpcMonitor
 * @param serverNode
 * @return TProcessor
 */
@SuppressWarnings("rawtypes")
protected TProcessor reflectProcessor(RpcMonitor rpcMonitor, ServerNode serverNode) {
    Class serviceClass = getRef().getClass();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class<?>[] interfaces = serviceClass.getInterfaces();
    if (interfaces.length == 0) {
        throw new RpcException("Service class should implements Iface!");
    }

    // ??,load "Processor";
    TProcessor processor = null;
    for (Class clazz : interfaces) {
        String cname = clazz.getSimpleName();
        if (!cname.equals("Iface")) {
            continue;
        }
        String pname = clazz.getEnclosingClass().getName() + "$Processor";
        try {
            Class<?> pclass = classLoader.loadClass(pname);
            Constructor constructor = pclass.getConstructor(clazz);
            processor = (TProcessor) constructor
                    .newInstance(getProxy(classLoader, clazz, getRef(), rpcMonitor, serverNode));
        } catch (Exception e) {
            throw new RpcException("Refact error,please check your thift gen class!", e.getCause());
        }
    }

    if (processor == null) {
        throw new RpcException("Service class should implements $Iface!");
    }
    return processor;
}

From source file:ar.edu.taco.TacoMain.java

/**
 * /*from w w  w .j a  v a2  s. co m*/
 * @param configFile
 * @param overridingProperties
 *            Properties that overrides properties file's values
 */

public TacoAnalysisResult run(String configFile, Properties overridingProperties)
        throws IllegalArgumentException {

    AlloyTyping varsEncodingValueOfArithmeticOperationsInObjectInvariants = new AlloyTyping();
    List<AlloyFormula> predsEncodingValueOfArithmeticOperationsInObjectInvariants = new ArrayList<AlloyFormula>();

    if (configFile == null) {
        throw new IllegalArgumentException("Config file not found, please verify option -cf");
    }

    List<JCompilationUnitType> compilation_units = null;
    String classToCheck = null;
    String methodToCheck = null;

    // Start configurator
    JDynAlloyConfig.reset();
    JDynAlloyConfig.buildConfig(configFile, overridingProperties);

    List<JDynAlloyModule> jdynalloy_modules = new ArrayList<JDynAlloyModule>();
    SimpleJmlToJDynAlloyContext simpleJmlToJDynAlloyContext;
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JMLPARSER_ENABLED,
            TacoConfigurator.JMLPARSER_ENABLED_DEFAULT)) {
        // JAVA PARSING
        String sourceRootDir = TacoConfigurator.getInstance()
                .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);

        if (TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD) == null) {
            throw new TacoException(
                    "Config key 'CLASS_TO_CHECK_FIELD' is mandatory. Please check your config file or add the -c parameter");
        }
        List<String> files = new ArrayList<String>(Arrays.asList(JDynAlloyConfig.getInstance().getClasses()));

        classToCheck = TacoConfigurator.getInstance().getString(TacoConfigurator.CLASS_TO_CHECK_FIELD);
        String[] splitName = classToCheck.split("_");
        classToCheck = "";
        for (int idx = 0; idx < splitName.length - 2; idx++) {
            classToCheck += splitName[idx] + "_";
        }

        if (splitName.length >= 2)
            classToCheck += splitName[splitName.length - 2] + "Instrumented_";
        classToCheck += splitName[splitName.length - 1];

        if (!files.contains(classToCheck)) {
            files.add(classToCheck);
        }

        List<String> processedFileNames = new ArrayList<String>();
        for (String file : files) {
            String begin = file.substring(0, file.lastIndexOf('.'));
            String end = file.substring(file.lastIndexOf('.'), file.length());
            processedFileNames.add(begin + "Instrumented" + end);
        }

        files = processedFileNames;

        JmlParser.getInstance().initialize(sourceRootDir,
                System.getProperty("user.dir") + System.getProperty("file.separator") + "bin" /* Unused */,
                files);
        compilation_units = JmlParser.getInstance().getCompilationUnits();
        // END JAVA PARSING

        // SIMPLIFICATION
        JmlStage aJavaCodeSimplifier = new JmlStage(compilation_units);
        aJavaCodeSimplifier.execute();
        JmlToSimpleJmlContext jmlToSimpleJmlContext = aJavaCodeSimplifier.getJmlToSimpleJmlContext();
        List<JCompilationUnitType> simplified_compilation_units = aJavaCodeSimplifier
                .get_simplified_compilation_units();
        // END SIMPLIFICATION

        // JAVA TO JDYNALLOY TRANSLATION
        SimpleJmlStage aJavaToDynJAlloyTranslator = new SimpleJmlStage(simplified_compilation_units);
        aJavaToDynJAlloyTranslator.execute();
        // END JAVA TO JDYNALLOY TRANSLATION
        simpleJmlToJDynAlloyContext = aJavaToDynJAlloyTranslator.getSimpleJmlToJDynAlloyContext();
        varsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getVarsEncodingValueOfArithmeticOperationsInInvariants();
        predsEncodingValueOfArithmeticOperationsInObjectInvariants = aJavaToDynJAlloyTranslator
                .getPredsEncodingValueOfArithmeticOperationsInInvariants();

        // JFSL TO JDYNALLOY TRANSLATION
        JfslStage aJfslToDynJAlloyTranslator = new JfslStage(simplified_compilation_units,
                aJavaToDynJAlloyTranslator.getModules(), jmlToSimpleJmlContext, simpleJmlToJDynAlloyContext);
        aJfslToDynJAlloyTranslator.execute();
        /**/ aJfslToDynJAlloyTranslator = null;
        // END JFSL TO JDYNALLOY TRANSLATION

        // PRINT JDYNALLOY
        JDynAlloyPrinterStage printerStage = new JDynAlloyPrinterStage(aJavaToDynJAlloyTranslator.getModules());
        printerStage.execute();
        /**/ printerStage = null;
        // END PRINT JDYNALLOY

        jdynalloy_modules.addAll(aJavaToDynJAlloyTranslator.getModules());

    } else {
        simpleJmlToJDynAlloyContext = null;
    }

    // JDYNALLOY BUILT-IN MODULES
    PrecompiledModules precompiledModules = new PrecompiledModules();
    precompiledModules.execute();
    jdynalloy_modules.addAll(precompiledModules.getModules());
    // END JDYNALLOY BUILT-IN MODULES

    // JDYNALLOY STATIC FIELDS CLASS
    JDynAlloyModule staticFieldsModule = precompiledModules.generateStaticFieldsModule();
    jdynalloy_modules.add(staticFieldsModule);
    /**/ staticFieldsModule = null;
    // END JDYNALLOY STATIC FIELDS CLASS

    // JDYNALLOY PARSING
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.JDYNALLOY_PARSER_ENABLED,
            TacoConfigurator.JDYNALLOY_PARSER_ENABLED_DEFAULT)) {
        log.info("****** START: Parsing JDynAlloy files ****** ");
        JDynAlloyParsingStage jDynAlloyParser = new JDynAlloyParsingStage(jdynalloy_modules);
        jDynAlloyParser.execute();
        jdynalloy_modules.addAll(jDynAlloyParser.getParsedModules());
        /**/ jDynAlloyParser = null;
        log.info("****** END: Parsing JDynAlloy files ****** ");
    } else {
        log.info(
                "****** INFO: Parsing JDynAlloy is disabled (hint enablet it using 'jdynalloy.parser.enabled') ****** ");
    }
    // END JDYNALLOY PARSING

    // JDYNALLOY TO DYNALLOY TRANSLATION
    JDynAlloyStage dynJAlloyToDynAlloyTranslator = new JDynAlloyStage(jdynalloy_modules);
    /**/ jdynalloy_modules = null;
    dynJAlloyToDynAlloyTranslator.execute();
    // BEGIN JDYNALLOY TO DYNALLOY TRANSLATION

    AlloyAnalysisResult alloy_analysis_result = null;
    DynalloyStage dynalloyToAlloy = null;

    // DYNALLOY TO ALLOY TRANSLATION
    if (TacoConfigurator.getInstance().getBoolean(TacoConfigurator.DYNALLOY_TO_ALLOY_ENABLE)) {

        dynalloyToAlloy = new DynalloyStage(dynJAlloyToDynAlloyTranslator.getOutputFileNames());
        dynalloyToAlloy.setSourceJDynAlloy(dynJAlloyToDynAlloyTranslator.getPrunedModules());
        /**/ dynJAlloyToDynAlloyTranslator = null;
        dynalloyToAlloy.execute();
        // DYNALLOY TO ALLOY TRANSLATION

        log.info("****** Transformation process finished ****** ");

        if (TacoConfigurator.getInstance().getNoVerify() == false) {
            // Starts dynalloy to alloy tranlation and alloy verification

            AlloyStage alloy_stage = new AlloyStage(dynalloyToAlloy.get_alloy_filename());
            /**/ dynalloyToAlloy = null;

            alloy_stage.execute();

            alloy_analysis_result = alloy_stage.get_analysis_result();
            /**/ alloy_stage = null;
        }
    }

    TacoAnalysisResult tacoAnalysisResult = new TacoAnalysisResult(alloy_analysis_result);

    String junitFile = null;

    if (TacoConfigurator.getInstance().getGenerateUnitTestCase()
            || TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        // Begin JUNIT Generation Stage
        methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);

        SnapshotStage snapshotStage = new SnapshotStage(compilation_units, tacoAnalysisResult, classToCheck,
                methodToCheck);
        snapshotStage.execute();

        RecoveredInformation recoveredInformation = snapshotStage.getRecoveredInformation();
        recoveredInformation.setFileNameSuffix(StrykerStage.fileSuffix);
        JUnitStage jUnitStage = new JUnitStage(recoveredInformation);
        jUnitStage.execute();
        junitFile = jUnitStage.getJunitFileName();
        //         StrykerStage.fileSuffix++;
        // End JUNIT Generation Stage
    } else {
        log.info("****** JUnit with counterexample values will not be generated. ******* ");
        if (!TacoConfigurator.getInstance().getGenerateUnitTestCase()) {
            log.info("****** generateUnitTestCase=false ******* ");
        }

    }

    if (TacoConfigurator.getInstance().getBuildJavaTrace()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT()) {
            log.info("****** START: Java Trace Generation ****** ");
            DynAlloyCompiler compiler = dynalloyToAlloy.getDynAlloyCompiler();
            JavaTraceStage javaTraceStage = new JavaTraceStage(compiler.getSpecContext(), alloy_analysis_result,
                    false);
            javaTraceStage.execute();
            //            DynAlloySolution dynAlloySolution = javaTraceStage.getDynAlloySolution();
            //            List<TraceStep> trace = dynAlloySolution.getTrace();

            log.info("****** FINISH: Java Trace Generation ****** ");
        }
    } else {
        log.info("****** Java Trace will not be generated. ******* ");
        log.info("****** generateJavaTrace=false ******* ");
    }

    if (TacoConfigurator.getInstance().getAttemptToCorrectBug()) {
        if (tacoAnalysisResult.get_alloy_analysis_result().isSAT() && tacoAnalysisResult
                .get_alloy_analysis_result().getAlloy_solution().getOriginalCommand().startsWith("Check")) {
            log.info("****** START: Stryker ****** ");
            methodToCheck = overridingProperties.getProperty(TacoConfigurator.METHOD_TO_CHECK_FIELD);
            String sourceRootDir = TacoConfigurator.getInstance()
                    .getString(TacoConfigurator.JMLPARSER_SOURCE_PATH_STR);
            StrykerStage strykerStage = new StrykerStage(compilation_units, sourceRootDir, classToCheck,
                    methodToCheck, configFile, overridingProperties,
                    TacoConfigurator.getInstance().getMaxStrykerMethodsForFile());
            StrykerStage.junitInputs = new Class<?>[50];

            try {
                String currentJunit = null;

                String tempFilename = junitFile.substring(0,
                        junitFile.lastIndexOf(FILE_SEP) + 1) /*+ FILE_SEP*/;
                String packageToWrite = "ar.edu.output.junit";
                String fileClasspath = tempFilename.substring(0, tempFilename
                        .lastIndexOf(new String("ar.edu.generated.junit").replaceAll("\\.", FILE_SEP)));
                fileClasspath = fileClasspath.replaceFirst("generated", "output");
                //               String currentClasspath = System.getProperty("java.class.path")+PATH_SEP+fileClasspath/*+PATH_SEP+System.getProperty("user.dir")+FILE_SEP+"generated"*/;
                currentJunit = editTestFileToCompile(junitFile, classToCheck, packageToWrite, methodToCheck);

                File[] file1 = new File[] { new File(currentJunit) };
                JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
                StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
                Iterable<? extends JavaFileObject> compilationUnit1 = fileManager
                        .getJavaFileObjectsFromFiles(Arrays.asList(file1));
                javaCompiler.getTask(null, fileManager, null, null, null, compilationUnit1).call();
                fileManager.close();
                javaCompiler = null;
                file1 = null;
                fileManager = null;

                ///*mfrias*/      int compilationResult =   javaCompiler.run(null, null, null /*new NullOutputStream()*/, new String[]{"-classpath", currentClasspath, currentJunit});
                ///**/            javaCompiler = null;
                //               if(compilationResult == 0) {
                log.warn("junit counterexample compilation succeded");
                ClassLoader cl = ClassLoader.getSystemClassLoader();
                @SuppressWarnings("resource")
                ClassLoader cl2 = new URLClassLoader(new URL[] { new File(fileClasspath).toURI().toURL() }, cl);
                //                  ClassLoaderTools.addFile(fileClasspath);
                Class<?> clazz = cl2.loadClass(packageToWrite + "." + obtainClassNameFromFileName(junitFile));
                //                  Method[] meth = clazz.getMethods();
                //                  log.info("preparing to add a class containing a test input to the pool... "+packageToWrite+"."+MuJavaController.obtainClassNameFromFileName(junitFile));
                //                  Result result = null;
                //                  final Object oToRun = clazz.newInstance();
                StrykerStage.junitInputs[StrykerStage.indexToLastJUnitInput] = clazz;
                StrykerStage.indexToLastJUnitInput++;
                cl = null;
                cl2 = null;

                //               
                //               } else {
                //                  log.warn("compilation failed");
                //               }
                //                     File originalFile = new File(tempFilename);
                //                     originalFile.delete();

            } catch (ClassNotFoundException e) {
                //                     e.printStackTrace();
            } catch (IOException e) {
                //                     e.printStackTrace();
            } catch (IllegalArgumentException e) {
                //                     e.printStackTrace();
            } catch (Exception e) {
                //                     e.printStackTrace();
            }

            strykerStage.execute();

            log.info("****** FINISH: Stryker ****** ");
        }
    } else {
        log.info("****** BugFix will not be generated. ******* ");
        log.info("****** attemptToCorrectBug=false ******* ");
    }

    return tacoAnalysisResult;
}

From source file:com.liferay.maven.arquillian.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.
    SecurityManager securityManager = new SecurityManager() {

        @Override/*from  ww w .j a  va  2 s .c  o m*/
        public void checkPermission(Permission permission) {
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:com.redhat.rhn.frontend.taglibs.list.ListTag.java

/**
 * Sets the filter used to filter list data
 * @param filterIn name of the filter class to use
 * @throws JspException error occurred creating an instance of the filter
 */// w  ww.j a  v  a 2  s . co  m
public void setFilter(String filterIn) throws JspException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        Class klass = cl.loadClass(filterIn);
        filter = (ListFilter) klass.newInstance();
        Context threadContext = Context.getCurrentContext();
        filter.prepare(threadContext.getLocale());
    } catch (Exception e) {
        throw new JspException(e.getMessage());
    }
}

From source file:interactivespaces.launcher.bootstrap.InteractiveSpacesFrameworkBootstrap.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   www . j  a  v  a  2s .  c o m*/
 *           if any errors occur.
 **/
private FrameworkFactory getFrameworkFactory() throws Exception {
    // using the ServiceLoader to get a factory.
    ClassLoader classLoader = InteractiveSpacesFrameworkBootstrap.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) != '#') {
                    return (FrameworkFactory) classLoader.loadClass(s).newInstance();
                }
            }
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

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

From source file:com.quinsoft.zeidon.objectdefinition.EntityDef.java

private int executeVmlConstraint(View view, EntityConstraintType type) {
    ObjectEngine oe = view.getObjectEngine();
    String className = getSourceFileName();
    try {//from  w  w  w . j a  va2s . co m
        ClassLoader classLoader = oe.getClassLoader(className);
        Class<?> operationsClass;
        operationsClass = classLoader.loadClass(className);
        Constructor<?> constructor = operationsClass.getConstructor(VML_CONSTRUCTOR_ARG_TYPES);
        Object object = constructor.newInstance(view);
        Method method = object.getClass().getMethod(getConstraintOper(), VML_ARGUMENT_TYPES);
        return (Integer) method.invoke(object, view, this.getName(), type.toInt(), 0);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).prependEntityDef(this)
                .appendMessage("EntityConstraint class = %s", className)
                .appendMessage("Constraint oper = %s", getConstraintOper())
                .appendMessage("See inner exception for more info.");
    }
}

From source file:com.novell.ldap.SPMLConnection.java

private void loadImpl(String className, ClassLoader loader) {
    SPMLImpl impl = null;/* w w  w .j a  v  a2s.com*/

    if (loader == null) {
        try {
            impl = (SPMLImpl) Class.forName(className).newInstance();
        } catch (Exception e) {
            return;
        }
    } else {
        try {
            impl = (SPMLImpl) loader.loadClass(className).newInstance();
        } catch (Exception e) {
            return;
        }

    }

    this.vendorImpl = impl;
    this.con = impl.getSpmlClient();

}

From source file:com.liferay.arquillian.maven.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        @Override//from w  ww  .ja v a2s  . c  o m
        public void checkPermission(Permission permission) {
            //It is not needed to check permissions
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}