List of usage examples for java.net URLClassLoader URLClassLoader
URLClassLoader(URL[] urls, AccessControlContext acc)
From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java
@Override public int run(String[] args) throws Exception { JobConf conf = new JobConf(getConf()); String phylip = null;//from ww w. j a va2 s .c o m String packedRow = null; int fractionDigits = 6; //String userJarLocation = "/path/to/jar"; //conf.setJar(userJarLocation); //were conf is the JobConf object ArrayList<String> other_args = new ArrayList<String>(); for (int i = 0; i < args.length; ++i) { try { if ("-m".equals(args[i])) { conf.setNumMapTasks(Integer.parseInt(args[++i])); } else if ("-r".equals(args[i])) { conf.setNumReduceTasks(Integer.parseInt(args[++i])); } else if ("-D".equals(args[i])) { String[] props = args[++i].split("="); conf.set(props[0], props[1]); } else if ("-libjars".equals(args[i])) { conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf)); URL[] libjars = FileUtils.getLibJars(conf); if (libjars != null && libjars.length > 0) { // Add libjars to client/tasks classpath conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader())); // Adds libjars to our classpath Thread.currentThread().setContextClassLoader( new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader())); } } else if ("-phylip".equals(args[i])) { phylip = args[++i]; } else if ("-packedRow".equals(args[i])) { packedRow = args[++i]; } else if ("-digits".equals(args[i])) { fractionDigits = Integer.parseInt(args[++i]); } else { other_args.add(args[i]); } } catch (NumberFormatException except) { System.out.println("ERROR: Integer expected instead of " + args[i]); return printUsage(); } catch (ArrayIndexOutOfBoundsException except) { System.out.println("ERROR: Required parameter missing from " + args[i - 1]); return printUsage(); } } boolean writeMatrix = (phylip != null || packedRow != null) ? true : false; // Make sure there are exactly 3 parameters left. if ((other_args.size() != 2 && !writeMatrix) || (other_args.size() == 0 && writeMatrix)) { System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 2."); return printUsage(); } int ret = 0; if (other_args.size() == 2) { ret = this.initJob(conf, other_args.get(0), other_args.get(1)); } // check writing out in Phylip format if (ret == 0 && other_args.size() == 1 && phylip != null) { printPhylipSquare(conf, other_args.get(0), phylip, fractionDigits); } else if (ret == 0 && other_args.size() == 2 && phylip != null) { printPhylipSquare(conf, other_args.get(1), phylip, fractionDigits); } // check writing out in row packed order if (ret == 0 && other_args.size() == 1 && packedRow != null) { printRowMajorMatrix(conf, other_args.get(0), packedRow, fractionDigits); } else if (ret == 0 && other_args.size() == 2 && packedRow != null) { printRowMajorMatrix(conf, other_args.get(1), packedRow, fractionDigits); } return ret; }
From source file:org.bonitasoft.console.common.server.utils.FormsResourcesUtils.java
/** * Create a classloader for the process/* w w w . j a v a2s . co m*/ * * @param processDefinitionID * the process definition ID * @param bdmFolder * the process application resources directory * @return a Classloader * @throws java.io.IOException */ protected static ClassLoader createProcessClassloaderWithBDM(final long processDefinitionID, final File bdmFolder, final ClassLoader parentClassloader) throws IOException { ClassLoader processClassLoader = null; try { final URL[] librariesURLs = getBDMLibrariesURLs(bdmFolder); if (librariesURLs.length > 0) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Creating the classloader for process " + processDefinitionID); } if (parentClassloader == null) { processClassLoader = new URLClassLoader(librariesURLs, Thread.currentThread().getContextClassLoader()); } else { processClassLoader = new URLClassLoader(librariesURLs, parentClassloader); } } } catch (final IOException e) { final String message = "Unable to create the class loader for the application's libraries"; if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, message, e); } throw new IOException(message); } return processClassLoader; }
From source file:com.serotonin.m2m2.Main.java
private static ClassLoader loadModules() throws Exception { Common.documentationManifest.parseManifestFile("web/WEB-INF/dox"); File modulesPath = new File(new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString()); File[] modules = modulesPath.listFiles(); if (modules == null) { modules = new File[0]; }//from ww w . ja v a 2 s .c om List classLoaderUrls = new ArrayList(); Map<Module, List<String>> moduleClasses = new HashMap<Module, List<String>>(); VersionData coreVersion = Common.getVersion(); List<ModuleWrapper> moduleWrappers = new ArrayList(); for (File moduleDir : modules) { if (!moduleDir.isDirectory()) { continue; } if (new File(moduleDir, "DELETE").exists()) { deleteDir(moduleDir); LOG.info(new StringBuilder().append("Deleted module directory ").append(moduleDir).toString()); } else { Properties props = null; try { props = getProperties(moduleDir); } catch (ModulePropertiesException e) { LOG.warn(new StringBuilder().append("Error loading properties for module ") .append(moduleDir.getPath()).toString(), e.getCause()); } if (props == null) { continue; } String moduleName = props.getProperty("name"); if (moduleName == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleDir.getPath()) .append(": ").append("name").append(" not defined in module properties").toString()); } if (!ModuleUtils.validateName(moduleName)) { throw new RuntimeException( new StringBuilder().append("Module ").append(moduleDir.getPath()).append(": ") .append("name").append(" has an invalid name: ").append(moduleName).toString()); } String version = props.getProperty("version"); if (version == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleName).append(": ") .append("version").append(" not defined in module properties").toString()); } String moduleCoreVersion = props.getProperty("coreVersion"); if (moduleCoreVersion == null) { throw new RuntimeException(new StringBuilder().append("Module ").append(moduleName).append(": ") .append("coreVersion").append(" not defined in module properties").toString()); } DependencyData moduleCoreDependency = new DependencyData(moduleCoreVersion); if (!moduleCoreDependency.matches(coreVersion)) { LOG.warn(new StringBuilder().append("Module ").append(moduleName) .append(": this module requires a core version of ").append(moduleCoreVersion) .append(", which does not match the current core version of ") .append(coreVersion.getFullString()).append(". Module not loaded.").toString()); } else { String descriptionKey = props.getProperty("descriptionKey"); TranslatableMessage description = null; if (org.apache.commons.lang3.StringUtils.isBlank(descriptionKey)) { String desc = props.getProperty("description"); if (!org.apache.commons.lang3.StringUtils.isBlank(desc)) description = new TranslatableMessage("common.default", new Object[] { desc }); } else { description = new TranslatableMessage(descriptionKey); } String vendor = props.getProperty("vendor"); String vendorUrl = props.getProperty("vendorUrl"); String dependencies = props.getProperty("dependencies"); String loadOrderStr = props.getProperty("loadOrder"); int loadOrder = 50; if (!org.apache.commons.lang3.StringUtils.isBlank(loadOrderStr)) { try { loadOrder = Integer.parseInt(loadOrderStr); } catch (Exception e) { loadOrder = -1; } if ((loadOrder < 1) || (loadOrder > 100)) { LOG.warn(new StringBuilder().append("Module ").append(moduleName) .append(": bad loadOrder value '").append(loadOrderStr) .append("', must be a number between 1 and 100. Defaulting to 50").toString()); loadOrder = 50; } } Module module = new Module(moduleName, version, description, vendor, vendorUrl, dependencies, loadOrder); moduleWrappers.add(new ModuleWrapper(module, props, moduleDir)); } } } Collections.sort(moduleWrappers, new Comparator<ModuleWrapper>() { public int compare(ModuleWrapper m1, ModuleWrapper m2) { return m1.module.getLoadOrder() - m2.module.getLoadOrder(); } }); for (ModuleWrapper moduleWrapper : moduleWrappers) { Module module = moduleWrapper.module; String moduleName = moduleWrapper.module.getName(); String version = moduleWrapper.module.getVersion(); String vendor = moduleWrapper.module.getVendor(); Properties props = moduleWrapper.props; File moduleDir = moduleWrapper.moduleDir; ModuleRegistry.addModule(module); LOG.info( new StringBuilder().append("Loading module '").append(moduleName).append("', v").append(version) .append(" by ").append(vendor == null ? "(unknown vendor)" : vendor).toString()); String classes = props.getProperty("classes"); if (!org.apache.commons.lang3.StringUtils.isBlank(classes)) { String[] parts = classes.split(","); for (String className : parts) { if (!org.apache.commons.lang3.StringUtils.isBlank(className)) { className = className.trim(); List classNames = (List) moduleClasses.get(module); if (classNames == null) { classNames = new ArrayList(); moduleClasses.put(module, classNames); } classNames.add(className); } } } File classesDir = new File(moduleDir, "classes"); if (classesDir.exists()) { classLoaderUrls.add(classesDir.toURI().toURL()); } loadLib(moduleDir, classLoaderUrls); String logo = props.getProperty("logo"); if (!org.apache.commons.lang3.StringUtils.isBlank(logo)) { Common.applicationLogo = new StringBuilder().append("/modules/").append(moduleName).append("/") .append(logo).toString(); } String favicon = props.getProperty("favicon"); if (!org.apache.commons.lang3.StringUtils.isBlank(favicon)) { Common.applicationFavicon = new StringBuilder().append("/modules/").append(moduleName).append("/") .append(favicon).toString(); } String styles = props.getProperty("styles"); if (!org.apache.commons.lang3.StringUtils.isBlank(styles)) { for (String style : styles.split(",")) { style = com.serotonin.util.StringUtils.trimWhitespace(style); if (!org.apache.commons.lang3.StringUtils.isBlank(style)) { Common.moduleStyles.add(new StringBuilder().append("modules/").append(moduleName) .append("/").append(style).toString()); } } } String scripts = props.getProperty("scripts"); if (!org.apache.commons.lang3.StringUtils.isBlank(scripts)) { for (String script : scripts.split(",")) { script = com.serotonin.util.StringUtils.trimWhitespace(script); if (!org.apache.commons.lang3.StringUtils.isBlank(script)) { Common.moduleScripts.add(new StringBuilder().append("modules/").append(moduleName) .append("/").append(script).toString()); } } } String jspfs = props.getProperty("jspfs"); if (!org.apache.commons.lang3.StringUtils.isBlank(jspfs)) { for (String jspf : jspfs.split(",")) { jspf = com.serotonin.util.StringUtils.trimWhitespace(jspf); if (!org.apache.commons.lang3.StringUtils.isBlank(jspf)) { Common.moduleJspfs.add(new StringBuilder().append("/modules/").append(moduleName) .append("/").append(jspf).toString()); } } } String dox = props.getProperty("documentation"); if (!org.apache.commons.lang3.StringUtils.isBlank(dox)) { Common.documentationManifest.parseManifestFile(new StringBuilder().append("web/modules/") .append(moduleName).append("/").append(dox).toString()); } String locales = props.getProperty("locales"); if (!org.apache.commons.lang3.StringUtils.isBlank(locales)) { String[] s = locales.split(","); for (String locale : s) { module.addLocaleDefinition(locale.trim()); } } String tagdir = props.getProperty("tagdir"); if (!org.apache.commons.lang3.StringUtils.isBlank(tagdir)) { File from = new File(moduleDir, tagdir); File to = new File(new StringBuilder().append(Common.MA_HOME).append("/web/WEB-INF/tags/") .append(moduleName).toString()); deleteDir(to); if (from.exists()) { FileUtils.copyDirectory(from, to); } } String graphics = props.getProperty("graphics"); if (!org.apache.commons.lang3.StringUtils.isBlank(graphics)) { graphics = com.serotonin.util.StringUtils.trimWhitespace(graphics); if (!org.apache.commons.lang3.StringUtils.isBlank(graphics)) { module.setGraphicsDir(graphics); } } String emailTemplates = props.getProperty("emailTemplates"); if (!org.apache.commons.lang3.StringUtils.isBlank(emailTemplates)) { emailTemplates = com.serotonin.util.StringUtils.trimWhitespace(emailTemplates); if (!org.apache.commons.lang3.StringUtils.isBlank(emailTemplates)) { module.setEmailTemplatesDir(emailTemplates); } } } for (Module module : ModuleRegistry.getModules()) { String dependenciesStr = module.getDependencies(); if (!org.apache.commons.lang3.StringUtils.isBlank(dependenciesStr)) { String[] parts = dependenciesStr.split(","); for (String dependencyStr : parts) { DependencyData depVer = null; dependencyStr = dependencyStr.trim(); int pos = dependencyStr.lastIndexOf(45); String depName; if (pos == -1) { depName = dependencyStr; } else { depName = dependencyStr.substring(0, pos); String ver = dependenciesStr.substring(pos + 1); try { depVer = new DependencyData(ver); } catch (Exception e) { throw new RuntimeException(new StringBuilder().append("Invalid dependency version in '") .append(dependencyStr).append("'").toString(), e); } } Module depModule = ModuleRegistry.getModule(depName); if (depModule == null) { throw new RuntimeException(new StringBuilder().append("Module '").append(depName) .append("' not found, but required by '").append(module.getName()).append("'") .toString()); } if ((depVer != null) && (!depVer.matches(new VersionData(depModule.getVersion())))) { throw new RuntimeException(new StringBuilder().append("Module '").append(depName) .append("' has version '").append(depModule.getVersion()).append("' but module '") .append(module.getName()).append("' requires version '") .append(depVer.getFullString()).append("'").toString()); } } } } URL[] arr = (URL[]) classLoaderUrls.toArray(new URL[0]); URLClassLoader cl = new URLClassLoader(arr, Main.class.getClassLoader()); Thread.currentThread().setContextClassLoader(cl); for (Map.Entry mod : moduleClasses.entrySet()) { try { for (String className : (List<String>) mod.getValue()) { Class clazz = cl.loadClass(className); boolean used = false; if (ModuleElementDefinition.class.isAssignableFrom(clazz)) { ModuleElementDefinition def = (ModuleElementDefinition) clazz.newInstance(); ((Module) mod.getKey()).addDefinition(def); used = true; } if (!used) LOG.warn(new StringBuilder().append("Unused classes entry: ").append(className).toString()); } } catch (Exception e) { throw new Exception(new StringBuilder().append("Exception loading classes in module ") .append(((Module) mod.getKey()).getName()).toString(), e); } } return cl; }
From source file:org.kchine.rpf.db.DBLayer.java
public Remote getRemoteObject(String stub, String codeBaseStr) throws RemoteException { try {/*from w w w.jav a2 s. c om*/ ClassLoader cl = null; if (codeBaseStr != null) { cl = new URLClassLoader(new URL[] { new URL(codeBaseStr) }, DBLayer.class.getClassLoader()); } return hexToStub(stub, cl); } catch (Exception e) { throw new RemoteException("", (e)); } }
From source file:ar.edu.taco.TacoMain.java
/** * //from w w w .j a v a 2 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:org.codehaus.enunciate.modules.BasicAppModule.java
/** * Whether to exclude a file from copying to the WEB-INF/lib directory. * * @param file The file to exclude./*w w w .j a v a 2s . c om*/ * @return Whether to exclude a file from copying to the lib directory. */ protected boolean knownExclude(File file) throws IOException { //instantiate a loader with this library only in its path... URLClassLoader loader = new URLClassLoader(new URL[] { file.toURL() }, null); if (loader.findResource("META-INF/enunciate/preserve-in-war") != null) { debug("%s is a known include because it contains the entry META-INF/enunciate/preserve-in-war.", file); //if a jar happens to have the enunciate "preserve-in-war" file, it is NOT excluded. return false; } else if (loader .findResource(com.sun.tools.apt.Main.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be tools.jar.", file); //exclude tools.jar. return true; } else if (loader.findResource( net.sf.jelly.apt.Context.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be apt-jelly.", file); //exclude apt-jelly-core.jar return true; } else if (loader.findResource(net.sf.jelly.apt.freemarker.FreemarkerModel.class.getName().replace('.', '/') .concat(".class")) != null) { debug("%s is a known exclude because it appears to be the apt-jelly-freemarker libs.", file); //exclude apt-jelly-freemarker.jar return true; } else if (loader.findResource( freemarker.template.Configuration.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be the freemarker libs.", file); //exclude freemarker.jar return true; } else if (loader.findResource(Enunciate.class.getName().replace('.', '/').concat(".class")) != null) { debug("%s is a known exclude because it appears to be the enunciate core jar.", file); //exclude enunciate-core.jar return true; } else if (loader.findResource("javax/servlet/ServletContext.class") != null) { debug("%s is a known exclude because it appears to be the servlet api.", file); //exclude the servlet api. return true; } else if (loader.findResource( "org/codehaus/enunciate/modules/xfire_client/EnunciatedClientSoapSerializerHandler.class") != null) { debug("%s is a known exclude because it appears to be the enunciated xfire client tools jar.", file); //exclude xfire-client-tools return true; } else if (loader.findResource("javax/swing/SwingBeanInfoBase.class") != null) { debug("%s is a known exclude because it appears to be dt.jar.", file); //exclude dt.jar return true; } else if (loader.findResource("HTMLConverter.class") != null) { debug("%s is a known exclude because it appears to be htmlconverter.jar.", file); return true; } else if (loader.findResource("sun/tools/jconsole/JConsole.class") != null) { debug("%s is a known exclude because it appears to be jconsole.jar.", file); return true; } else if (loader.findResource("sun/jvm/hotspot/debugger/Debugger.class") != null) { debug("%s is a known exclude because it appears to be sa-jdi.jar.", file); return true; } else if (loader.findResource("sun/io/ByteToCharDoubleByte.class") != null) { debug("%s is a known exclude because it appears to be charsets.jar.", file); return true; } else if (loader.findResource("com/sun/deploy/ClientContainer.class") != null) { debug("%s is a known exclude because it appears to be deploy.jar.", file); return true; } else if (loader.findResource("com/sun/javaws/Globals.class") != null) { debug("%s is a known exclude because it appears to be javaws.jar.", file); return true; } else if (loader.findResource("javax/crypto/SecretKey.class") != null) { debug("%s is a known exclude because it appears to be jce.jar.", file); return true; } else if (loader.findResource("sun/net/www/protocol/https/HttpsClient.class") != null) { debug("%s is a known exclude because it appears to be jsse.jar.", file); return true; } else if (loader.findResource("sun/plugin/JavaRunTime.class") != null) { debug("%s is a known exclude because it appears to be plugin.jar.", file); return true; } else if (loader.findResource("com/sun/corba/se/impl/activation/ServerMain.class") != null) { debug("%s is a known exclude because it appears to be rt.jar.", file); return true; } else if (ServiceLoader.load(DeploymentModule.class, loader).iterator().hasNext()) { debug("%s is a known exclude because it appears to be an enunciate module.", file); //exclude by default any deployment module libraries. return true; } return false; }
From source file:gdt.jgui.entity.procedure.JProcedurePanel.java
private String[] run() { try {/*from w w w.j av a 2s. c om*/ File procedureJava = new File(entihome$ + "/" + entityKey$ + "/" + entityKey$ + ".java"); if (!procedureJava.exists()) createSource(entityKey$); else { FileInputStream fis = new FileInputStream(procedureJava); InputStreamReader ins = new InputStreamReader(fis, "UTF-8"); BufferedReader rds = new BufferedReader(ins); String ss; StringBuffer sbs = new StringBuffer(); while ((ss = rds.readLine()) != null) { sbs.append(ss + "\n"); } rds.close(); sourcePanel.setText(sbs.toString()); } File procedureHome = new File(entihome$ + "/" + entityKey$); URL url = procedureHome.toURI().toURL(); URL[] urls = new URL[] { url }; ClassLoader parentLoader = JMainConsole.class.getClassLoader(); URLClassLoader cl = new URLClassLoader(urls, parentLoader); Class<?> cls = cl.loadClass(entityKey$); Object obj = cls.newInstance(); Method method = obj.getClass().getDeclaredMethod("run", JMainConsole.class, String.class, Integer.class); Integer dividerLocation = new Integer(splitPane.getDividerLocation()); method.invoke(obj, console, entihome$, dividerLocation); } catch (Exception e) { Logger.getLogger(getClass().getName()).severe(e.toString()); } return null; }
From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java
/** * Auto-detect the class names of the implementation of <code>com.sun.tools.doclets.Taglet</code> class from a * given jar file.//w ww . ja va 2 s . com * <br/> * <b>Note</b>: <code>JAVA_HOME/lib/tools.jar</code> is a requirement to find * <code>com.sun.tools.doclets.Taglet</code> class. * * @param jarFile not null * @return the list of <code>com.sun.tools.doclets.Taglet</code> class names from a given jarFile. * @throws IOException if jarFile is invalid or not found, or if the <code>JAVA_HOME/lib/tools.jar</code> * is not found. * @throws ClassNotFoundException if any * @throws NoClassDefFoundError if any */ protected static List<String> getTagletClassNames(File jarFile) throws IOException, ClassNotFoundException, NoClassDefFoundError { List<String> classes = getClassNamesFromJar(jarFile); ClassLoader cl; // Needed to find com.sun.tools.doclets.Taglet class File tools = new File(System.getProperty("java.home"), "../lib/tools.jar"); if (tools.exists() && tools.isFile()) { cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL(), tools.toURI().toURL() }, null); } else { cl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }, null); } List<String> tagletClasses = new ArrayList<String>(); Class<?> tagletClass = cl.loadClass("com.sun.tools.doclets.Taglet"); for (String s : classes) { Class<?> c = cl.loadClass(s); if (tagletClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) { tagletClasses.add(c.getName()); } } return tagletClasses; }
From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java
private void startPU(String springXml) throws IOException, ClassNotFoundException { if (logger.isDebugEnabled()) { logger.debug(logMessage("Starting PU with [" + springXml + "]")); }/*from ww w. j a v a 2 s . c o m*/ String puName = (String) context.getInitParameter("puName"); String puPath = (String) context.getInitParameter("puPath"); String codeserver = context.getExportCodebase(); org.openspaces.pu.sla.SLA sla = getSLA(getServiceBeanContext()); Integer instanceId = this.instanceId; Integer backupId = this.backupId; // Derive instanceId and backupId if not explicitly set if (instanceId == null) { boolean hasBackups = sla.getNumberOfBackups() > 0; if (hasBackups) { instanceId = clusterGroup; //the first instance is primary so no backupid if (context.getServiceBeanConfig().getInstanceID().intValue() > 1) { backupId = (context.getServiceBeanConfig().getInstanceID().intValue() - 1); } } else { instanceId = context.getServiceBeanConfig().getInstanceID().intValue(); } } //set cluster info clusterInfo = new ClusterInfo(); String clusterSchema = sla.getClusterSchema(); if (clusterSchema != null) { clusterInfo.setSchema(clusterSchema); int slaMax = getSLAMax(context); int numberOfInstances = Math.max(slaMax, sla.getNumberOfInstances()); clusterInfo.setNumberOfInstances(numberOfInstances); } else { clusterInfo.setNumberOfInstances(sla.getNumberOfInstances()); } clusterInfo.setNumberOfBackups(sla.getNumberOfBackups()); clusterInfo.setInstanceId(instanceId); clusterInfo.setBackupId(backupId); clusterInfo.setName(puName); ClusterInfoParser.guessSchema(clusterInfo); logger.info(logMessage("ClusterInfo [" + clusterInfo + "]")); MarshalledObject beanLevelPropertiesMarshObj = (MarshalledObject) getServiceBeanContext() .getInitParameter("beanLevelProperties"); BeanLevelProperties beanLevelProperties; if (beanLevelPropertiesMarshObj != null) { beanLevelProperties = (BeanLevelProperties) beanLevelPropertiesMarshObj.get(); logger.info(logMessage("BeanLevelProperties " + beanLevelProperties)); } else { beanLevelProperties = new BeanLevelProperties(); } beanLevelProperties.getContextProperties() .putAll(ClusterInfoPropertyPlaceholderConfigurer.createProperties(clusterInfo)); // set a generic work location that can be used by container providers File workLocation = new File(SystemInfo.singleton().locations().work()); workLocation.mkdirs(); beanLevelProperties.getContextProperties().setProperty("com.gs.work", workLocation.getAbsolutePath()); boolean downloadPU = false; //create PU Container ProcessingUnitContainerProvider factory; // identify if this is a web app final InputStream webXml = openUrlStream(codeserver + puPath + "/WEB-INF/web.xml"); // identify if this is a .NET one final InputStream puConfig = openUrlStream(codeserver + puPath + "/pu.config"); // identify if this is a .NET interop one final InputStream puInteropConfig = openUrlStream(codeserver + puPath + "/pu.interop.config"); String processingUnitContainerProviderClass; if (webXml != null) { webXml.close(); downloadPU = true; String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties); String[] classesToLoad = null; if ("jetty".equals(jeeContainer)) { // pre load the jetty server class so the static shutdown thread will be loaded under it classesToLoad = new String[] { "org.eclipse.jetty.server.Server" }; } // setup class loaders correcly try { Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs( new String[] { JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer) })); ((ServiceClassLoader) contextClassLoader) .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad)); } catch (Exception e) { throw new CannotCreateContainerException("Failed to configure JEE class loader", e); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } String className = StringUtils.capitalize(jeeContainer) + "JeeProcessingUnitContainerProvider"; processingUnitContainerProviderClass = "org.openspaces.pu.container.jee." + jeeContainer + "." + className; } else if (puConfig != null) { puConfig.close(); downloadPU = true; processingUnitContainerProviderClass = DotnetProcessingUnitContainerProvider.class.getName(); } else if (puInteropConfig != null) { puInteropConfig.close(); downloadPU = true; processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName(); } else { processingUnitContainerProviderClass = IntegratedProcessingUnitContainerProvider.class.getName(); if (beanLevelProperties.getContextProperties().getProperty("pu.download", "true") .equalsIgnoreCase("true")) { downloadPU = true; } } if (beanLevelProperties != null) { processingUnitContainerProviderClass = beanLevelProperties.getContextProperties().getProperty( ProcessingUnitContainerProvider.CONTAINER_CLASS_PROP, processingUnitContainerProviderClass); } if (downloadPU) { String deployName = puName + "_" + clusterInfo.getRunningNumberOffset1(); String deployedProcessingUnitsLocation = workLocation.getAbsolutePath() + "/processing-units"; int uuid = Math.abs(new Random().nextInt()); deployPath = new File( deployedProcessingUnitsLocation + "/" + deployName.replace('.', '_') + "_" + uuid); FileSystemUtils.deleteRecursively(deployPath); deployPath.mkdirs(); // backward compatible beanLevelProperties.getContextProperties().setProperty("jee.deployPath", deployPath.getAbsolutePath()); beanLevelProperties.getContextProperties().setProperty("dotnet.deployPath", deployPath.getAbsolutePath()); beanLevelProperties.getContextProperties().setProperty( ProcessingUnitContainerProvider.CONTEXT_PROPERTY_DEPLOY_PATH, deployPath.getAbsolutePath()); try { if (isOnGsmHost()) { copyPu(puPath, deployPath); } else { long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation)); logDownloadSize(size); } } catch (MalformedURLException mle) { logger.warn("Could not determine if GSC and GSM are on the same host", mle); // fallback to download long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation)); logDownloadSize(size); } catch (UnknownHostException unhe) { logger.warn("Could not determine if GSC and GSM are on the same host", unhe); // fallback to download long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation)); logDownloadSize(size); } catch (RemoteException re) { logger.warn("Could not determine if GSC and GSM are on the same host", re); // fallback to download long size = downloadAndExtractPU(puName, puPath, codeserver, deployPath, new File(deployedProcessingUnitsLocation)); logDownloadSize(size); } // go over listed files that needs to be resolved with properties for (Map.Entry entry : beanLevelProperties.getContextProperties().entrySet()) { String key = (String) entry.getKey(); if (key.startsWith("com.gs.resolvePlaceholder")) { String path = (String) entry.getValue(); File input = new File(deployPath, path); if (logger.isDebugEnabled()) { logger.debug("Resolving placeholder for file [" + input.getAbsolutePath() + "]"); } BeanLevelPropertiesUtils.resolvePlaceholders(beanLevelProperties, input); } } } boolean sharedLibEnabled; if (beanLevelProperties.getContextProperties().containsKey("pu.shared-lib.enable")) { sharedLibEnabled = beanLevelProperties.getContextProperties().getProperty("pu.shared-lib") .equals("true"); } else { sharedLibEnabled = System.getProperty("com.gs.pu.shared-lib.enable", "false").equals("true"); } final boolean disableManifestClassPathJars = Boolean.getBoolean("com.gs.pu.manifest.classpath.disable"); final boolean disableManifestClassPathCommonPuJars = Boolean .getBoolean("com.gs.pu.manifest.classpath.common.disable"); // this is used to inject the manifest jars to the webapp classloader (if exists) List<URL> manifestClassPathJars = new ArrayList<URL>(); CommonClassLoader commonClassLoader = CommonClassLoader.getInstance(); // handles class loader libraries if (downloadPU) { List<URL> libUrls = new ArrayList<URL>(); File libDir = new File(deployPath, "lib"); if (libDir.exists()) { File[] libFiles = BootIOUtils.listFiles(libDir); for (File libFile : libFiles) { libUrls.add(libFile.toURI().toURL()); } } if (!disableManifestClassPathJars) { File manifestFile = new File(deployPath, JarFile.MANIFEST_NAME); if (manifestFile.isFile()) { try { InputStream manifestStream = new FileInputStream(manifestFile); manifestClassPathJars = getManifestClassPathJars(puName, manifestStream); libUrls.addAll(manifestClassPathJars); } catch (IOException e) { if (logger.isWarnEnabled()) { logger.warn(failedReadingManifest(puName), e); } } } } // add to common class loader List<URL> sharedlibUrls = new ArrayList<URL>(); File sharedlibDir = new File(deployPath, "shared-lib"); if (sharedlibDir.exists()) { File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir); for (File sharedlibFile : sharedlibFiles) { sharedlibUrls.add(sharedlibFile.toURI().toURL()); } } sharedlibDir = new File(deployPath, "WEB-INF/shared-lib"); if (sharedlibDir.exists()) { File[] sharedlibFiles = BootIOUtils.listFiles(sharedlibDir); for (File sharedlibFile : sharedlibFiles) { sharedlibUrls.add(sharedlibFile.toURI().toURL()); } } if (sharedLibEnabled) { ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL()); ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs()))); } commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Common Class Loader " + sharedlibUrls)); } } else { if (sharedlibUrls.size() > 0) { logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'"); } libUrls.addAll(sharedlibUrls); // add pu-common jar files String gsLibOpt = Locator.getLibOptional(); String gsPuCommon = System.getProperty("com.gs.pu-common", gsLibOpt + "pu-common"); final String gsLibOptSecurity = Locator.getLibOptionalSecurity(); libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsPuCommon, gsLibOptSecurity }))); if (ScalaIdentifier.isScalaLibInClassPath()) { String gsLibPlatform = Locator.getLibPlatform(); // note that we assume BootUtil.toURLs does not work recursively here // i.e, only gs-openspaces-scala.jar will be added and not all the files under /lib String gsLibPlatformScala = gsLibPlatform + "scala"; libUrls.addAll(Arrays.asList(BootUtil.toURLs(new String[] { gsLibPlatformScala }))); } if (!disableManifestClassPathJars && !disableManifestClassPathCommonPuJars) { URLClassLoader urlClassLoader = new URLClassLoader(BootUtil.toURLs(new String[] { gsPuCommon }), null /* parent */); InputStream puCommonManifestMF = urlClassLoader.getResourceAsStream(JarFile.MANIFEST_NAME); if (puCommonManifestMF != null) { List<URL> manifestClassPathComonPuJars = getManifestClassPathJars(puName, puCommonManifestMF); manifestClassPathJars.addAll(manifestClassPathComonPuJars); libUrls.addAll(manifestClassPathComonPuJars); } } ((ServiceClassLoader) contextClassLoader).setSlashPath(deployPath.toURI().toURL()); ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs()))); } } try { prepareWebApplication(deployPath, clusterInfo, beanLevelProperties); } catch (Exception e) { throw new CannotCreateContainerException("Failed to bootstrap web application", e); } } else { // add to service class loader List<URL> libUrls = new ArrayList<URL>(); WebsterFile libDir = new WebsterFile(new URL(codeserver + puPath + "/lib")); File[] libFiles = libDir.listFiles(); for (int i = 0; i < libFiles.length; i++) { libUrls.add(new URL(codeserver + puPath + "/lib/" + libFiles[i].getName())); } if (!disableManifestClassPathJars) { InputStream manifestStream = readManifestFromCodeServer(puName, puPath, codeserver, workLocation); if (manifestStream != null) { manifestClassPathJars = getManifestClassPathJars(puName, manifestStream); libUrls.addAll(manifestClassPathJars); } } // add to common class loader WebsterFile sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/shared-lib")); File[] sharedlibFiles = sharedlibDir.listFiles(); List<URL> sharedlibUrls = new ArrayList<URL>(); for (File sharedlibFile : sharedlibFiles) { sharedlibUrls.add(new URL(codeserver + puPath + "/shared-lib/" + sharedlibFile.getName())); } sharedlibDir = new WebsterFile(new URL(codeserver + puPath + "/WEB-INF/shared-lib")); sharedlibFiles = sharedlibDir.listFiles(); for (File sharedlibFile : sharedlibFiles) { sharedlibUrls.add(new URL(codeserver + puPath + "/WEB-INF/shared-lib/" + sharedlibFile.getName())); } if (sharedLibEnabled) { ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/")); ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs()))); } commonClassLoader.addComponent(puName, sharedlibUrls.toArray(new URL[sharedlibUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Common Class Loader " + sharedlibUrls)); } } else { if (sharedlibUrls.size() > 0) { logger.warn("Using old 'shared-lib' directory, will add jars under it as if it was 'lib'"); } libUrls.addAll(sharedlibUrls); ((ServiceClassLoader) contextClassLoader).setSlashPath(new URL(codeserver + puPath + "/")); ((ServiceClassLoader) contextClassLoader).setLibPath(libUrls.toArray(new URL[libUrls.size()])); if (logger.isDebugEnabled()) { logger.debug(logMessage("Service Class Loader " + Arrays.toString(((ServiceClassLoader) contextClassLoader).getURLs()))); } } } // handle mule os if there is one class loader try { contextClassLoader.loadClass("org.mule.api.MuleContext"); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { SystemInfo.singleton().locations().lib() + "/optional/openspaces/mule-os.jar" })); } catch (Throwable e) { // no mule } //apply the following only if the pu has the rest element if (springXml.contains("<os-core:rest")) { String jeeContainer = JeeProcessingUnitContainerProvider.getJeeContainer(beanLevelProperties); // pre load the jetty server class so the static shutdown thread will be loaded under it String[] classesToLoad = new String[] { "org.eclipse.jetty.server.Server" }; String jettyJars = System.getProperty("com.gigaspaces.rest.jetty", JeeProcessingUnitContainerProvider.getJeeContainerJarPath(jeeContainer)); // setup class loaders correctly try { Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { jettyJars, SystemInfo.singleton().locations().lib() + "/platform/jetty/org.apache.jasper.glassfish-2.2.2.v201112011158.jar", SystemInfo.singleton().locations().lib() + "/optional/spring/spring-web-4.1.1.RELEASE.jar", SystemInfo.singleton().locations().lib() + "/optional/spring/spring-webmvc-4.1.1.RELEASE.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-core-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-databind-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/optional/jackson/jackson-annotations-2.3.0.jar", SystemInfo.singleton().locations().lib() + "/platform/rest/xap-rest.jar" })); ((ServiceClassLoader) contextClassLoader) .setParentClassLoader(SharedServiceData.getJeeClassLoader(jeeContainer, classesToLoad)); } catch (Exception e) { throw new CannotCreateContainerException("Failed to configure class loader", e); } finally { //TODO check if we need this Thread.currentThread().setContextClassLoader(contextClassLoader); } } //apply the following only if the pu has the mapdb-blob-store element if (springXml.contains("<blob-store:mapdb-blob-store")) { String mapdbJar = System.getProperty("com.gigaspaces.blobstore.mapdb", SystemInfo.singleton().locations().lib() + "/optional/blobstore/mapdb-blobstore.jar"); Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { mapdbJar })); Thread.currentThread().setContextClassLoader(contextClassLoader); } //apply the following only if the pu has the rocksdb-blob-store element if (springXml.contains("<blob-store:rocksdb-blob-store") || springXml.contains("class=\"com.gigaspaces.blobstore.rocksdb.RocksDBBlobStoreHandler\"")) { String rocksdbJar = System.getProperty("com.gigaspaces.blobstore.rocksdb", SystemInfo.singleton().locations().lib() + "/optional/blobstore/rocksdb-blobstore.jar"); Thread.currentThread().setContextClassLoader(CommonClassLoader.getInstance()); ((ServiceClassLoader) contextClassLoader).addURLs(BootUtil.toURLs(new String[] { rocksdbJar })); Thread.currentThread().setContextClassLoader(contextClassLoader); } final Map<String, String> puTags = buildPuTags(clusterInfo); MetricRegistrator puMetricRegistrator = metricManager.createRegistrator("pu", puTags); this.metricRegistrators = metricManager.registerProcessMetrics(puTags); this.metricRegistrators.add(puMetricRegistrator); for (Map.Entry<String, String> entry : puTags.entrySet()) beanLevelProperties.getContextProperties().setProperty("metrics." + entry.getKey(), entry.getValue()); //inject quiesce state changed event in order let space know to be initialized in quiesced mode if (quiesceDetails != null && quiesceDetails.getStatus() == QuiesceState.QUIESCED) { beanLevelProperties.getContextProperties().setProperty("quiesce.token", quiesceDetails.getToken().toString()); beanLevelProperties.getContextProperties().setProperty("quiesce.description", quiesceDetails.getDescription()); } factory = createContainerProvider(processingUnitContainerProviderClass); factory.setDeployPath(deployPath); factory.setClassLoader(contextClassLoader); factory.setManifestUrls(manifestClassPathJars); // only load the spring xml file if it is not a web application (if it is a web application, we will load it with the Bootstrap servlet context loader) if (webXml == null && factory instanceof ApplicationContextProcessingUnitContainerProvider) { if (StringUtils.hasText(springXml)) { // GS-9350: if this is a processing unit with gateway declarations, always try to // re-load the pu.xml to support "hot-deploy" (refresh) if (springXml.contains("os-gateway:")) { String deployPath = beanLevelProperties.getContextProperties().getProperty("deployPath"); if (StringUtils.hasText(deployPath)) { String newSpringXml = readFile(deployPath + "/META-INF/spring/pu.xml"); if (StringUtils.hasText(newSpringXml)) { springXml = newSpringXml; //override with new one } } } Resource resource = new ByteArrayResource(springXml.getBytes()); ((ApplicationContextProcessingUnitContainerProvider) factory).addConfigLocation(resource); } } factory.setClusterInfo(clusterInfo); factory.setBeanLevelProperties(beanLevelProperties); factory.setMetricRegistrator(puMetricRegistrator); container = factory.createContainer(); // set the context class loader to the web app class loader if there is one // this menas that from now on, and the exported service, will use the context class loader ClassLoader webAppClassLoader = SharedServiceData.removeWebAppClassLoader(clusterInfo.getUniqueName()); if (webAppClassLoader != null) { contextClassLoader = webAppClassLoader; } Thread.currentThread().setContextClassLoader(contextClassLoader); buildMembersAliveIndicators(); buildUndeployingEventListeners(); buildDumpProcessors(); ArrayList<Object> serviceDetails = buildServiceDetails(); buildServiceMonitors(); buildInvocableServices(); this.puDetails = new PUDetails(context.getParentServiceID(), clusterInfo, beanLevelProperties, serviceDetails.toArray(new Object[serviceDetails.size()])); if (container instanceof ApplicationContextProcessingUnitContainer) { ApplicationContext applicationContext = ((ApplicationContextProcessingUnitContainer) container) .getApplicationContext(); // inject the application context to all the monitors and schedule them // currently use the number of threads in relation to the number of monitors int numberOfThreads = watchTasks.size() / 5; if (numberOfThreads == 0) { numberOfThreads = 1; } executorService = Executors.newScheduledThreadPool(numberOfThreads); for (WatchTask watchTask : watchTasks) { if (watchTask.getMonitor() instanceof ApplicationContextMonitor) { ((ApplicationContextMonitor) watchTask.getMonitor()).setApplicationContext(applicationContext); } executorService.scheduleAtFixedRate(watchTask, watchTask.getMonitor().getPeriod(), watchTask.getMonitor().getPeriod(), TimeUnit.MILLISECONDS); } } }
From source file:com.jaspersoft.jasperserver.api.common.service.impl.JdbcDriverServiceImpl.java
private ClassLoader getClassLoader(String[] pathToDriverFile) throws Exception { URL[] urls = new URL[pathToDriverFile.length]; for (int i = 0; i < pathToDriverFile.length; i++) { urls[i] = new URL(String.format(URL_CLASSLOADER_FORMAT, pathToDriverFile[i])); }/* ww w .ja v a 2 s .c o m*/ return new URLClassLoader(urls, null); }