List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:org.apache.flink.client.program.rest.RestClusterClientTest.java
/** * Tests that we can submit a jobGraph in detached mode. *//*from w w w . j a v a 2 s.c om*/ @Test public void testDetachedJobSubmission() throws Exception { final TestJobSubmitHandler testJobSubmitHandler = new TestJobSubmitHandler(); try (TestRestServerEndpoint ignored = createRestServerEndpoint(testJobSubmitHandler)) { restClusterClient.setDetached(true); final JobSubmissionResult jobSubmissionResult = restClusterClient.submitJob(jobGraph, ClassLoader.getSystemClassLoader()); // if the detached mode didn't work, then we would not reach this point because the execution result // retrieval would have failed. assertThat(jobSubmissionResult, is(not(instanceOf(JobExecutionResult.class)))); assertThat(jobSubmissionResult.getJobID(), is(jobId)); } }
From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { _log.info("Loading Script: " + file.getAbsolutePath()); }/* w w w . java 2 s .com*/ if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from properties file if possible. *///from w w w.j a v a 2 s .c o m private void initializeFromProperties() { try { Properties prop = new Properties(); String propFile = this.getClass().getPackage().getName().replace('.', '/') + '/' + this.getClass().getSimpleName() + ".properties"; java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(propFile); ArrayList<URL> urls = new ArrayList<>(); //HACK: semi sort classpath to put "files" first and "jars" second. //this has an impact once we are workin in tomcat where //the classes in tomcat are not stored in a jar. while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.toString().startsWith("file:")) { urls.add(0, url); } else { boolean added = false; for (int ii = 0; !added && ii < urls.size(); ii++) { if (!urls.get(ii).toString().startsWith("file:")) { urls.add(ii, url); added = true; } } if (!added) { urls.add(url); } } } //reverse the list, so that the item found first in the //classpath will be the last one run though and thus //be the one to set the final value Collections.reverse(urls); PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); for (URL url : urls) { try { prop.load(url.openStream()); ArrayList<String> propKeys = new ArrayList<>(prop.stringPropertyNames()); for (PropertyDescriptor p : props) { if (p.getWriteMethod() != null && p.getReadMethod() != null && p.getReadMethod().getDeclaringClass() != Object.class) { boolean success = false; String val = prop.getProperty(p.getName()); if (val != null) { Object o = TypeHandler.fromString(p.getPropertyType(), val); if (o == null) { try { o = readValue(val, p.getPropertyType()); } catch (Exception ex) { o = null; LOGGER.warn(null, ex); LOGGER.warn( MessageFormat.format("PropertyName: {0}", new Object[] { val })); } } if (o != null) { p.getWriteMethod().invoke(this, o); success = true; } } if (!success && val != null) { // if (TypeHandler.isEnumeratedType(p)) { //// success = setEnumerated(p, val); // } else { success = setValueHelper(p, val); // } } if (success) { propKeys.remove(p.getName()); } } } for (String key : propKeys) { String value = prop.getProperty(key); setNameValuePair(key, value); } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException ex) { } catch (IllegalAccessException ex) { LOGGER.warn(null, ex); } } } catch (IOException ex) { } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } }
From source file:org.rzo.yajsw.app.WrapperManagerImpl.java
/** * Load jar.//from w w w . j av a 2 s .c om * * @param jarName * the jar name * * @return the method */ private Method loadJar(String jarName) { URL url = null; try { url = new File(jarName).toURI().toURL(); } catch (MalformedURLException e2) { e2.printStackTrace(); return null; } Manifest manifest; try { manifest = new JarFile(new File(jarName)).getManifest(); } catch (IOException e1) { e1.printStackTrace(); return null; } Attributes attr = manifest.getMainAttributes(); String cl = attr.getValue("Class-Path"); ClassLoader loader = null; if (cl != null) { ArrayList classpath = new ArrayList(); String[] clArr = cl.split(" "); for (int i = 0; i < clArr.length; i++) { String file = clArr[i]; File myFile; try { myFile = new File(file); classpath.add(myFile); } catch (Exception e) { e.printStackTrace(); } } URL[] urlsArr = new URL[classpath.size()]; int i = 0; for (Iterator it = classpath.iterator(); it.hasNext(); i++) try { urlsArr[i] = ((File) it.next()).toURI().toURL(); } catch (Exception e) { e.printStackTrace(); } loader = new URLClassLoader(urlsArr, ClassLoader.getSystemClassLoader()); } if (loader == null) loader = ClassLoader.getSystemClassLoader(); String mainClassName = attr.getValue("Main-Class"); if (mainClassName == null) return null; Method mainMethod = null; try { Class cls = loader.loadClass(mainClassName);// cl.loadClass(mainClassName); mainMethod = cls.getDeclaredMethod("main", new Class[] { String[].class }); } catch (Exception ex) { ex.printStackTrace(); } return mainMethod; }
From source file:com.amazonaws.services.kinesis.aggregators.configuration.ExternalConfigurationModel.java
public static List<ExternalConfigurationModel> buildFromConfig(String configFilePath) throws Exception { List<ExternalConfigurationModel> response = new ArrayList<>(); // reference the config file as a full path File configFile = new File(configFilePath); if (!configFile.exists()) { // try to load the file from the classpath InputStream classpathConfig = ExternalConfigurationModel.class.getClassLoader() .getResourceAsStream(configFilePath); if (classpathConfig != null && classpathConfig.available() > 0) { configFile = new File(ExternalConfigurationModel.class .getResource((configFilePath.startsWith("/") ? "" : "/") + configFilePath).toURI()); LOG.info(String.format("Loaded Configuration %s from Classpath", configFilePath)); } else {/*w w w . j ava2 s . c o m*/ if (configFilePath.startsWith("s3://")) { AmazonS3 s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain()); TransferManager tm = new TransferManager(s3Client); // parse the config path to get the bucket name and prefix final String s3ProtoRegex = "s3:\\/\\/"; String bucket = configFilePath.replaceAll(s3ProtoRegex, "").split("/")[0]; String prefix = configFilePath.replaceAll(String.format("%s%s\\/", s3ProtoRegex, bucket), ""); // download the file using TransferManager configFile = File.createTempFile(configFilePath, null); Download download = tm.download(bucket, prefix, configFile); download.waitForCompletion(); // shut down the transfer manager tm.shutdownNow(); LOG.info(String.format("Loaded Configuration from Amazon S3 %s/%s to %s", bucket, prefix, configFile.getAbsolutePath())); } else { // load the file from external URL try { configFile = File.createTempFile(configFilePath, null); FileUtils.copyURLToFile(new URL(configFilePath), configFile, 1000, 1000); LOG.info(String.format("Loaded Configuration from %s to %s", configFilePath, configFile.getAbsolutePath())); } catch (IOException e) { // handle the timeouts and so on with a generalised // config // file not found handler later } } } } else { LOG.info(String.format("Loaded Configuration from Filesystem %s", configFilePath)); } // if we haven't been able to load a config file, then bail if (configFile == null || !configFile.exists()) { throw new InvalidConfigurationException( String.format("Unable to Load Config File from %s", configFilePath)); } JsonNode document = StreamAggregatorUtils.asJsonNode(configFile); ExternalConfigurationModel config = null; Iterator<JsonNode> i = document.elements(); while (i.hasNext()) { config = new ExternalConfigurationModel(); JsonNode section = i.next(); // set generic properties config.setNamespace(StreamAggregatorUtils.readValueAsString(section, "namespace")); config.setDateFormat(StreamAggregatorUtils.readValueAsString(section, "dateFormat")); addTimeHorizons(section, config); setAggregatorType(section, config); // set the label items JsonNode labelItems = StreamAggregatorUtils.readJsonValue(section, "labelItems"); if (labelItems != null && labelItems.size() > 0) { Iterator<JsonNode> iterator = labelItems.elements(); while (iterator.hasNext()) { JsonNode n = iterator.next(); config.addLabelItems(n.asText()); } } config.setLabelAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "labelAttributeAlias")); config.setDateItem(StreamAggregatorUtils.readValueAsString(section, "dateItem")); config.setDateAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "dateAttributeAlias")); JsonNode summaryItems = StreamAggregatorUtils.readJsonValue(section, "summaryItems"); if (summaryItems != null && summaryItems.size() > 0) { Iterator<JsonNode> iterator = summaryItems.elements(); while (iterator.hasNext()) { JsonNode n = iterator.next(); config.addSummaryItem(n.asText()); } } config.setTableName(StreamAggregatorUtils.readValueAsString(section, "tableName")); String readIO = StreamAggregatorUtils.readValueAsString(section, "readIOPS"); if (readIO != null) config.setReadIOPs(Long.parseLong(readIO)); String writeIO = StreamAggregatorUtils.readValueAsString(section, "writeIOPS"); if (writeIO != null) config.setWriteIOPs(Long.parseLong(writeIO)); // configure tolerance of data extraction problems String failOnDataExtraction = StreamAggregatorUtils.readValueAsString(section, "failOnDataExtraction"); if (failOnDataExtraction != null) config.setFailOnDataExtraction(Boolean.parseBoolean(failOnDataExtraction)); // configure whether metrics should be emitted String emitMetrics = StreamAggregatorUtils.readValueAsString(section, "emitMetrics"); String metricsEmitterClassname = StreamAggregatorUtils.readValueAsString(section, "metricsEmitterClass"); if (emitMetrics != null || metricsEmitterClassname != null) { if (metricsEmitterClassname != null) { config.setMetricsEmitter((Class<IMetricsEmitter>) ClassLoader.getSystemClassLoader() .loadClass(metricsEmitterClassname)); } else { config.setEmitMetrics(Boolean.parseBoolean(emitMetrics)); } } // configure the data store class String dataStoreClass = StreamAggregatorUtils.readValueAsString(section, "IDataStore"); if (dataStoreClass != null) { Class<IDataStore> dataStore = (Class<IDataStore>) ClassLoader.getSystemClassLoader() .loadClass(dataStoreClass); config.setDataStore(dataStore); } // get the data extractor configuration, so we know what other json // elements to retrieve from the configuration document String useExtractor = null; try { useExtractor = StreamAggregatorUtils.readValueAsString(section, "dataExtractor"); config.setDataExtractor(DataExtractor.valueOf(useExtractor)); } catch (Exception e) { throw new Exception( String.format("Unable to configure aggregator with Data Extractor %s", useExtractor)); } switch (config.getDataExtractor()) { case CSV: configureStringCommon(section, config); configureCsv(section, config); break; case JSON: configureStringCommon(section, config); break; case OBJECT: configureObject(section, config); break; case REGEX: configureRegex(section, config); } response.add(config); } return response; }
From source file:com.eucalyptus.objectstorage.pipeline.binding.ObjectStorageRESTBinding.java
@Override public Object bind(final MappingHttpRequest httpRequest) throws Exception { Map bindingArguments = new HashMap(); final String operationName = getOperation(httpRequest, bindingArguments); if (operationName == null) throw new MethodNotAllowedException(httpRequest.getMethod().toString() + " " + httpRequest.getUri()); Map<String, String> params = httpRequest.getParameters(); OMElement msg;/* w w w . ja va2s .c om*/ GroovyObject groovyMsg; Map<String, String> fieldMap; Class targetType; try { //:: try to create the target class ::// targetType = ClassLoader.getSystemClassLoader() .loadClass("com.eucalyptus.objectstorage.msgs.".concat(operationName).concat("Type")); if (!GroovyObject.class.isAssignableFrom(targetType)) { throw new Exception(); } //:: get the map of parameters to fields ::// fieldMap = this.buildFieldMap(targetType); //:: get an instance of the message ::// groovyMsg = (GroovyObject) targetType.newInstance(); } catch (Exception e) { throw new BindingException("Failed to construct message of type " + operationName); } addLogData((BaseMessage) groovyMsg, bindingArguments); //TODO: Refactor this to be more general List<String> failedMappings = populateObject(groovyMsg, fieldMap, params); populateObjectFromBindingMap(groovyMsg, fieldMap, httpRequest, bindingArguments); User user = Contexts.lookup(httpRequest.getCorrelationId()).getUser(); setRequiredParams(groovyMsg, user); if (!params.isEmpty()) { //ignore params that are not consumed, EUCA-4840 params.clear(); } if (!failedMappings.isEmpty()) { StringBuilder errMsg = new StringBuilder("Failed to bind the following fields:\n"); for (String f : failedMappings) errMsg.append(f).append('\n'); for (Map.Entry<String, String> f : params.entrySet()) errMsg.append(f.getKey()).append(" = ").append(f.getValue()).append('\n'); throw new BindingException(errMsg.toString()); } Logs.extreme().trace(groovyMsg.toString()); try { Binding binding = BindingManager.getDefaultBinding(); msg = binding.toOM(groovyMsg); } catch (RuntimeException e) { throw new BindingException("Failed to build a valid message: " + e.getMessage()); } return groovyMsg; }
From source file:com.anavationllc.o2jb.ConfigurationApp.java
private Scene getScene() { if (scene == null) { scene = new Scene(getGrid(), 700, 400); scene.getStylesheets()/* w ww . j a v a 2s . com*/ .add(ClassLoader.getSystemClassLoader().getResource(msg("css.file")).toExternalForm()); } return scene; }
From source file:org.apache.nifi.registry.jetty.JettyServer.java
private WebAppContext loadWar(final File warFile, final String contextPath, final URL[] additionalResources) throws IOException { final WebAppContext webappContext = new WebAppContext(warFile.getPath(), contextPath); webappContext.setContextPath(contextPath); webappContext.setDisplayName(contextPath); // remove slf4j server class to allow WAR files to have slf4j dependencies in WEB-INF/lib List<String> serverClasses = new ArrayList<>(Arrays.asList(webappContext.getServerClasses())); serverClasses.remove("org.slf4j."); webappContext.setServerClasses(serverClasses.toArray(new String[0])); webappContext.setDefaultsDescriptor(WEB_DEFAULTS_XML); // get the temp directory for this webapp final File webWorkingDirectory = properties.getWebWorkingDirectory(); final File tempDir = new File(webWorkingDirectory, warFile.getName()); if (tempDir.exists() && !tempDir.isDirectory()) { throw new RuntimeException(tempDir.getAbsolutePath() + " is not a directory"); } else if (!tempDir.exists()) { final boolean made = tempDir.mkdirs(); if (!made) { throw new RuntimeException(tempDir.getAbsolutePath() + " could not be created"); }/* ww w .ja v a 2s . c o m*/ } if (!(tempDir.canRead() && tempDir.canWrite())) { throw new RuntimeException(tempDir.getAbsolutePath() + " directory does not have read/write privilege"); } // configure the temp dir webappContext.setTempDirectory(tempDir); // configure the max form size (3x the default) webappContext.setMaxFormContentSize(600000); // start out assuming the system ClassLoader will be the parent, but if additional resources were specified then // inject a new ClassLoader in between the system and webapp ClassLoaders that contains the additional resources ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader(); if (additionalResources != null && additionalResources.length > 0) { URLClassLoader additionalClassLoader = new URLClassLoader(additionalResources, ClassLoader.getSystemClassLoader()); parentClassLoader = additionalClassLoader; } webappContext.setClassLoader(new WebAppClassLoader(parentClassLoader, webappContext)); logger.info("Loading WAR: " + warFile.getAbsolutePath() + " with context path set to " + contextPath); return webappContext; }
From source file:com.buaa.cfs.security.UserGroupInformation.java
@SuppressWarnings("unchecked") private static Class<? extends Principal> getOsPrincipalClass() { ClassLoader cl = ClassLoader.getSystemClassLoader(); try {// ww w .ja v a 2 s.c om String principalClass = null; if (IBM_JAVA) { if (is64Bit) { principalClass = "com.ibm.security.auth.UsernamePrincipal"; } else { if (windows) { principalClass = "com.ibm.security.auth.NTUserPrincipal"; } else if (aix) { principalClass = "com.ibm.security.auth.AIXPrincipal"; } else { principalClass = "com.ibm.security.auth.LinuxPrincipal"; } } } else { principalClass = windows ? "com.sun.security.auth.NTUserPrincipal" : "com.sun.security.auth.UnixPrincipal"; } return (Class<? extends Principal>) cl.loadClass(principalClass); } catch (ClassNotFoundException e) { LOG.error("Unable to find JAAS classes:" + e.getMessage()); } return null; }
From source file:model.settings.ReadSettings.java
private static void installWindows() { /*//from www. j a v a 2s.co m * setting up "open with" links for paint. * Therefore request SUDO rights. */ try { final String userHome = System.getProperty("user.home"); final boolean openWith = false; // not implemented yet. if (openWith) { final String localDest = userHome + "/paint.desktop"; final String finalDest = "/usr/share/applications/paint.desktop"; Util.exportResource("/res/files/paint.desktop", localDest); String passwd = ""; /* * Check whether the execution was successfully (and the password * was correct) or the file already exists */ while (!new File(finalDest).exists()) { /* * Request SUDO privileges. */ passwd = Util.requestSudoRights("mv " + localDest + " " + finalDest); if (passwd.equals("")) { JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges."); return; } try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } String passwd = Util.requestSudoRights("echo hier"); /* * Copy jar file */ /////////////////////////Path for jar file./////////////////// // /usr/lib/paint/paint.jar requests sudo rights. // because of this, each time an update is done these rights // have to be requested. Thus chose another path: // ~/.PaintUni/paint.jar // (PROGRAM_LOCATION/paint.jar) /* * STEP 2: Create (executable) file which is called if the * application is run. */ final String dest_jar_file = PROGRAM_LOCATION + "paint.jar"; final String dest_exec = "/usr/bin/paint"; String orig_jar_file = URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8"); // if Eclipse on-the-fly-compiling final String eclipseSubstring = "target/classes/"; if (orig_jar_file.endsWith(eclipseSubstring)) { orig_jar_file = orig_jar_file.substring(0, orig_jar_file.length() - eclipseSubstring.length()); } orig_jar_file += "paint.jar"; /* * Step 3: Copy .jar file to the destination. */ final String command1 = "cp " + "\"" + orig_jar_file + "\"" + " " + "\"" + dest_jar_file + "\""; String ret1 = Util.executeCommandLinux(command1); System.out.println(command1 + "" + ret1); final String content = "#!/bin/bash \n" + "java -jar " + dest_jar_file + " $1"; PrintWriter writer = new PrintWriter(userHome + "/paint", "UTF-8"); writer.println(content); writer.close(); final String command = "mv " + userHome + "/paint " + dest_exec; Util.execSudoCommand(command, passwd); // if the password was not correct / no sudo rights if (!new File(dest_exec).exists()) { while (!new File(dest_exec).exists()) { /* * Request SUDO privileges. */ passwd = Util.requestSudoRights(command); if (passwd.equals("")) { JOptionPane.showMessageDialog(null, "installation failed due to lack of privileges."); return; } try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Util.execSudoCommand("chmod a+x " + dest_exec, passwd); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }