private static void printHelp() { String app = System.getProperty("paoding.try.app", "TryPaodingAnalyzer"); String cmd = System.getProperty("paoding.try.cmd", "java " + TryPaodingAnalyzer.class.getName()); System.out.println(app + "的用法:"); System.out.println("\t" + cmd + " [OPTIONS] [text_content]"); System.out.println("\nOPTIONS:"); System.out.println("\t--file, -f:\n\t\t文章以文件的形式输入,在前缀加上\"classpath:\"表示从类路径中寻找该文件。"); System.out.println("\t--charset, -c:\n\t\t文章的字符集编码,比如gbk,utf-8等。如果没有设置该选项,则使用Java环境默认的字符集编码。"); System.out.println( "\t--properties, -p:\n\t\t不读取默认的类路径下的庖丁分词属性文件,而使用指定的文件,在前缀加上\"classpath:\"表示从类路径中寻找该文件。"); System.out.println( "\t--mode, -m:\n\t\t强制使用给定的mode的分词器;可以设定为default,most-words,max-word-length或指定类名的其他mode(指定类名的,需要加前缀\"class:\")。"); System.out.println("\t--input, -i:\n\t\t要被分词的文章内容;当没有通过-f或--file指定文章输入文件时可选择这个选项指定要被分词的内容。"); System.out.println( "\t--analyzer, -a:\n\t\t测试其他分词器,通过--analyzer或-a指定其完整类名。特别地,paoding、cjk、chinese、st分别对应PaodingAnalyzer、CJKAnalyzer、ChineseAnalyzer、StandardAnalyzer"); System.out.println( "\t--print, -P:\n\t\t 是否打印分词结果。默认打印前50行。规则:no表示不打印;50等价于1-50行;1-50表示打印1至50行;可以以逗号组合使用,如20,40-50表示打印1-20以及40-50行"); System.out.println("\n示例:"); System.out.println("\t" + cmd); System.out.println("\t" + cmd + " ?"); System.out.println("\t" + cmd + " 中华人民共和国"); System.out.println("\t" + cmd + " -m max 中华人民共和国"); System.out.println("\t" + cmd + " -f e:/content.txt -c utf8"); System.out.println("\t" + cmd + " -f e:/content.txt -c utf8 -m max-word-length"); System.out.println("\t" + cmd + " -f e:/content.txt -c utf8 -a cjk"); System.out.println("\n若是控制台进入\"paoding>\"后:"); titlePrinted = false; printTitleIfNotPrinted("\t"); }
@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { assertTrue(targetDir1.mkdirs()); assertTrue(targetDir2.mkdirs()); if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI); rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
@Test public void verifySignedJar() throws Exception { String classpath = System.getProperty("java.class.path"); String[] entries = classpath.split(System.getProperty("path.separator")); String signedJarFile = null; for (String entry : entries) { if (entry.contains("bcprov")) { signedJarFile = entry; } } assertThat(signedJarFile).isNotNull(); java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile)); jarFile.getManifest(); Enumeration<JarEntry> jarEntries = jarFile.entries(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = jarEntries.nextElement(); InputStream inputStream = jarFile.getInputStream(jarEntry); inputStream.skip(Long.MAX_VALUE); inputStream.close(); if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.isDirectory() && !jarEntry.getName().endsWith("TigerDigest.class")) { assertThat(jarEntry.getCertificates()).isNotNull(); } } jarFile.close(); }
private static void loadBTraceLibrary(final ClassLoader loader) { boolean isSolaris = System.getProperty("os.name").equals("SunOS"); if (isSolaris) { try { System.loadLibrary("btrace"); dtraceEnabled = true; } catch (LinkageError le) { if (loader == null || loader.getResource("net/java/btrace") == null) { System.err.println("cannot load libbtrace.so, will miss DTrace probes from BTrace"); return; } String path = loader.getResource("net/java/btrace").toString(); path = path.substring(0, path.indexOf("!")); path = path.substring("jar:".length(), path.lastIndexOf('/')); String cpu = System.getProperty("os.arch"); if (cpu.equals("x86")) { cpu = "i386"; } path += "/" + cpu + "/libbtrace.so"; try { path = new File(new URI(path)).getAbsolutePath(); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new RuntimeException(e); } try { System.load(path); dtraceEnabled = true; } catch (LinkageError le1) { System.err.println("cannot load libbtrace.so, will miss DTrace probes from BTrace"); } } } }
/** @return returns a string list of all pathes */ public static Resource[] getClassPathes() { if (classPathes != null) return classPathes; ArrayList pathes = new ArrayList(); String pathSeperator = System.getProperty("path.separator"); if (pathSeperator == null) pathSeperator = ";"; // java.ext.dirs ResourceProvider frp = ResourcesImpl.getFileResourceProvider(); // pathes from system properties String strPathes = System.getProperty("java.class.path"); if (strPathes != null) { Array arr = ListUtil.listToArrayRemoveEmpty(strPathes, pathSeperator); int len = arr.size(); for (int i = 1; i <= len; i++) { Resource file = frp.getResource(Caster.toString(arr.get(i, ""), "").trim()); if (file.exists()) pathes.add(ResourceUtil.getCanonicalResourceEL(file)); } } // pathes from url class Loader (dynamic loaded classes) ClassLoader cl = new Info().getClass().getClassLoader(); if (cl instanceof URLClassLoader) getClassPathesFromClassLoader((URLClassLoader) cl, pathes); return classPathes = (Resource[]) pathes.toArray(new Resource[pathes.size()]); }
public void testBenchmark() throws Exception { if (!"false".equals(System.getProperty("benchmark.skip"))) return; String dir = System.getProperty("benchmark.output_dir"); PrintStream out = dir == null ? System.out : new PrintStream( new FileOutputStream( new File( new File(dir), "protostuff-benchmark-" + System.currentTimeMillis() + ".html"), true)); int warmups = Integer.getInteger("benchmark.warmups", 100000); int loops = Integer.getInteger("benchmark.loops", 1000000); String title = "protostuff-json ser/deser benchmark for " + loops + " runs"; out.println("<html><head><title>"); out.println(title); out.println("</title></head><body><p>"); out.println(title); out.println("</p><pre>\n\n"); generateAndParse(out); out.println("\n\n</pre><hr/><pre>"); start(out, warmups, loops); if (System.out != out) out.close(); }
private void loadSystemInformation() { lblOperatingSystem.setText(System.getProperty("os.name")); lblOperatingSystemVersion.setText(System.getProperty("os.version")); lblJavaVersion.setText(System.getProperty("java.version")); lblUser.setText(System.getProperty("user.name")); lblSystemResolution.setText(getResolutionString(Util.getScreenResolution())); }
@Test public void test() throws IOException, InterruptedException { // val client = new ImportIO(UUID.fromString("d22d14f3-6c98-44af-a301-f822288ebbe3"), // "tMFNJzytLe8sgYF9hFNhKI7akyiPLMhfu8UfomNVCVr5fqWWLyiQMfpDDyfucQKF++BAoVi6jnGnavYqRKP/9g=="); // If doing login rather than API key ImportIO client = new ImportIO(); client.login(System.getProperty("username"), System.getProperty("password")); client.connect(); final CountDownLatch latch = new CountDownLatch(3); MessageCallback messageCallback = new MessageCallback() { public void onMessage(Query query, QueryMessage message, Progress progress) { if (message.getType() == MessageType.MESSAGE) { System.err.println(message); } if (progress.isFinished()) { latch.countDown(); } } }; client.query(makeQuery("mac mini"), messageCallback); client.query(makeQuery("ibm"), messageCallback); client.query(makeQuery("handbag"), messageCallback); // wait until all 3 queryies are finished latch.await(); client.shutdown(); }
/* uses badsource and badsink */ public void bad() throws Throwable { String data; if (privateTrue) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } String osCommand; if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process process = Runtime.getRuntime().exec(osCommand + data); process.waitFor(); }
/** Constructor */ public LogisticRegression(final String apiUser, final String apiKey, final boolean devMode) { this.bigmlUser = apiUser != null ? apiUser : System.getProperty("BIGML_USERNAME"); this.bigmlApiKey = apiKey != null ? apiKey : System.getProperty("BIGML_API_KEY"); bigmlAuth = "?username="******";api_key=" + this.bigmlApiKey + ";"; this.devMode = devMode; super.init(null); }
/** Constructor */ public LogisticRegression() { this.bigmlUser = System.getProperty("BIGML_USERNAME"); this.bigmlApiKey = System.getProperty("BIGML_API_KEY"); bigmlAuth = "?username="******";api_key=" + this.bigmlApiKey + ";"; this.devMode = false; super.init(null); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getHeader("foo"); String bar = new Test().doSomething(param); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo", bar}; String[] argsEnv = {"foo=bar"}; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(args, argsEnv, new java.io.File(System.getProperty("user.dir"))); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } // end doPost
public static void main(String[] args) { String fileSeparator = System.getProperty("file.separator"); try { FileInputStream fileInput = new FileInputStream( System.getProperty("user.dir") + fileSeparator + "resources" + fileSeparator + "content.rdf.u8"); InputSource is; is = new InputSource(fileInput); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); XMLReader r; r = spf.newSAXParser().getXMLReader(); r.setContentHandler(new RDFHandler()); r.parse(is); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
public static void copyFile(String source, String targetDirectory, String filesep) throws IOException { byte[] buffer = new byte[4096]; int bytes_read; FileInputStream fis = null; FileOutputStream fos = null; File fileToCopy = null; File copiedFile = null; try { fileToCopy = new File(System.getProperty("user.dir") + filesep + source); copiedFile = new File(System.getProperty("user.dir") + filesep + targetDirectory + filesep + source); fis = new FileInputStream(fileToCopy); fos = new FileOutputStream(copiedFile); while ((bytes_read = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytes_read); } // end while fos.flush(); fos.close(); } // end try catch (java.io.IOException ioe) { System.err.println("An error has occurred while copying file:\n" + ioe); ioe.printStackTrace(); return; } }
private File getFcInfoFile() { if (fcInfoFileName == null) { // NB need security permissions to get true IP address, and // we should have those as the whole initialisation is in a // doPrivileged block. But in this case no exception is thrown, // and it returns the loop back address, and so we end up with // "localhost" String hostname; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { hostname = "localhost"; } String userDir = System.getProperty("user.home"); String version = System.getProperty("java.version"); String fs = File.separator; String dir = userDir + fs + ".java" + fs + "fonts" + fs + version; String lang = SunToolkit.getStartupLocale().getLanguage(); String name = "fcinfo-" + fileVersion + "-" + hostname + "-" + osName + "-" + osVersion + "-" + lang + ".properties"; fcInfoFileName = dir + fs + name; } return new File(fcInfoFileName); }
private void checkProxy() { if (null != System.getProperty("http.proxyHost") || null != System.getProperty("https.proxyHost")) { Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { String prot = getRequestingProtocol().toLowerCase(); String host = System.getProperty(prot + ".proxyHost", ""); String port = System.getProperty(prot + ".proxyPort", ""); String user = System.getProperty(prot + ".proxyUser", ""); String password = System.getProperty(prot + ".proxyPassword", ""); if (getRequestingHost().toLowerCase().equals(host.toLowerCase())) { if (Integer.parseInt(port) == getRequestingPort()) { return new PasswordAuthentication(user, password.toCharArray()); } } } return null; } }); } }
public java.awt.Dimension getPreferredSize(boolean savingAsApplet) { int maxX = 0, maxY = 0; java.awt.Component[] comps = getComponents(); for (int i = 0; i < comps.length; i++) { if (comps[i] == glassPane) { continue; } java.awt.Point location = comps[i].getLocation(); java.awt.Dimension size = comps[i].getSize(); int x = location.x + size.width; int y = location.y + size.height; if (!savingAsApplet && comps[i] instanceof WidgetWrapper && !((WidgetWrapper) comps[i]).selected()) { x += WidgetWrapper.BORDER_E; y += WidgetWrapper.BORDER_S; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } if (!savingAsApplet && System.getProperty("os.name").startsWith("Mac") && System.getProperty("os.version").startsWith("10.2")) { // allow for the intrusion of the window grow box into the // lower right corner maxX += 8; maxY += 8; } return new java.awt.Dimension(maxX, maxY); }
static { // Make Pax URL use the maven.repo.local setting if present if (System.getProperty("maven.repo.local") != null) { System.setProperty( "org.ops4j.pax.url.mvn.localRepository", System.getProperty("maven.repo.local")); } }
public static void main(String[] args) { try { int port = DEFAULT_SERVER_PORT; File systemDir = null; if (args.length > 0) { try { port = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Error parsing port: " + e.getMessage()); System.exit(-1); } systemDir = new File(args[1]); } final Server server = new Server( systemDir, System.getProperty(GlobalOptions.USE_MEMORY_TEMP_CACHE_OPTION) != null); initLoggers(); server.start(port); System.out.println("Server classpath: " + System.getProperty("java.class.path")); System.err.println(SERVER_SUCCESS_START_MESSAGE + port); } catch (Throwable e) { System.err.println(SERVER_ERROR_START_MESSAGE + e.getMessage()); e.printStackTrace(System.err); System.exit(-1); } }
protected Option[] configureLogLevel() { return options( when(System.getProperty(AdminConfig.TEST_LOGLEVEL_PROPERTY) != null) .useOptions( systemProperty(AdminConfig.TEST_LOGLEVEL_PROPERTY) .value(System.getProperty(AdminConfig.TEST_LOGLEVEL_PROPERTY, "")))); }
/** * <code>main</code> - pass in JFrame name * * @param args - <code>String[]</code> - */ public static void main(String[] args) { name = ""; String maxScreenValue = "false"; for (int argc = 0; argc < args.length; argc++) { // System.err.println( "argc " + argc + " " + args[argc]); if (argc == 0) { name = args[argc]; } else if (argc == 1) { maxScreenValue = args[argc]; } else { System.err.println("argument '" + args[argc] + "' not handled"); System.exit(-1); } } osType = System.getProperty("os.type"); // System.err.println( "osType " + osType); planWorksRoot = System.getProperty("planworks.root"); isMaxScreen = false; if (maxScreenValue.equals("true")) { isMaxScreen = true; } GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gs = ge.getScreenDevices(); for (int i = 0; i < gs.length; i++) { DisplayMode dm = gs[i].getDisplayMode(); System.err.println(dm.getWidth() + " " + dm.getHeight()); } planWorks = new PlanWorks(buildConstantMenus()); } // end main
private void saveSpecifiedPorts() { String filename; String javaHome = System.getProperty("java.home"); String pathSep = System.getProperty("path.separator", ":"); String fileSep = System.getProperty("file.separator", "/"); String lineSep = System.getProperty("line.separator"); String output; if (PortType == PORT_SERIAL) { filename = javaHome + fileSep + "lib" + fileSep + "gnu.io.rxtx.SerialPorts"; } else if (PortType == PORT_PARALLEL) { filename = javaHome + "gnu.io.rxtx.ParallelPorts"; } else { System.out.println("Bad Port Type!"); return; } System.out.println(filename); try { FileOutputStream out = new FileOutputStream(filename); for (int i = 0; i < 128; i++) { if (cb[i].getState()) { output = cb[i].getLabel() + pathSep; out.write(output.getBytes()); } } out.write(lineSep.getBytes()); out.close(); } catch (IOException e) { System.out.println("IOException!"); } }
@Before public void dbInit() throws Exception { String configFileName = System.getProperty("user.home"); if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { configFileName += "/.pokerth/config.xml"; } else { configFileName += "/AppData/Roaming/pokerth/config.xml"; } File file = new File(configFileName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0); Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0); String dbAddress = dbAddressNode.getAttribute("value"); Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0); String dbUser = dbUserNode.getAttribute("value"); Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0); String dbPassword = dbPasswordNode.getAttribute("value"); Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0); String dbName = dbNameNode.getAttribute("value"); final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName; Class.forName("com.mysql.jdbc.Driver").newInstance(); dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> headers = request.getHeaders("foo"); if (headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } StringBuilder sbxyz98365 = new StringBuilder(param); String bar = sbxyz98365.append("_SafeStuff").toString(); // FILE URIs are tricky because they are different between Mac and Windows because of lack of // standardization. // Mac requires an extra slash for some reason. String startURIslashes = ""; if (System.getProperty("os.name").indexOf("Windows") != -1) if (System.getProperty("os.name").indexOf("Windows") != -1) startURIslashes = "/"; else startURIslashes = "//"; try { java.net.URI fileURI = new java.net.URI( "file:" + startURIslashes + org.owasp.benchmark.helpers.Utils.testfileDir .replace('\\', '/') .replace(' ', '_') + bar); new java.io.File(fileURI); } catch (java.net.URISyntaxException e) { throw new ServletException(e); } }
/** * return the operating system architecture * * @return one of the following SystemUtil.ARCH_UNKNOW, SystemUtil.ARCH_32, SystemUtil.ARCH_64 */ public static int getOSArch() { if (osArch == -1) { osArch = toIntArch(System.getProperty("os.arch.data.model")); if (osArch == ARCH_UNKNOW) osArch = toIntArch(System.getProperty("os.arch")); } return osArch; }
public void run(String[] args) { DatabaseFactory factory = new DatabaseFactory(); if (System.getProperty("user.dir").isEmpty()) { System.out.println("user.dir is incorrect"); } if (System.getProperty("fizteh.db.dir").isEmpty()) { System.out.println("fizteh.db.dir is incorrect"); } Path pathDirection = Paths.get(System.getProperty("user.dir")).resolve(System.getProperty("fizteh.db.dir")); String dir = pathDirection.toString(); DatabaseProvider dProvider = factory.create(dir); if (args.length == 0) { interactiveMode(dProvider); } else { pocketMode(args, dProvider); } }
// Declare parameters @Parameters(name = "{index}: {0}") public static Iterable<Object[]> data() { System.out.println("Working Directory = " + System.getProperty("user.dir")); File currentDir = new File(System.getProperty("user.dir")); String rootPath = new File(currentDir, "src/test/resources/models/sbml-test-cases").getPath(); // Get all the SBML files LinkedList<String> sbmlPaths = walk(rootPath); int N = sbmlPaths.size(); System.out.println("Number of SBML test cases: " + N); Object[][] resources = new String[N][1]; for (int k = 0; k < N; k++) { String path = sbmlPaths.get(k); // create the resource String[] items = path.split("/"); int mindex = -1; for (int i = 0; i < items.length; i++) { if (items[i].equals("models")) { mindex = i; break; } } String resource = StringUtils.join(ArrayUtils.subarray(items, mindex, items.length), "/"); // System.out.println(resource); resources[k][0] = "/" + resource; // String.format("/models/BiGG/%s", fname); } return Arrays.asList(resources); }
/** * Constructor. The first time an RJavaClassLoader is created, it is cached as the primary loader. * * @param path path of the rJava package * @param libpath lib sub directory of the rJava package */ public RJavaClassLoader(String path, String libpath) { super(new URL[] {}); // respect rJava.debug level String rjd = System.getProperty("rJava.debug"); if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true; if (verbose) System.out.println("RJavaClassLoader(\"" + path + "\",\"" + libpath + "\")"); if (primaryLoader == null) { primaryLoader = this; if (verbose) System.out.println(" - primary loader"); } else { if (verbose) System.out.println(" - NOT primrary (this=" + this + ", primary=" + primaryLoader + ")"); } libMap = new HashMap /*<String,UnixFile>*/(); classPath = new Vector /*<UnixFile>*/(); classPath.add(new UnixDirectory(path + "/java")); rJavaPath = path; rJavaLibPath = libpath; /* load the rJava library */ UnixFile so = new UnixFile(rJavaLibPath + "/rJava.so"); if (!so.exists()) so = new UnixFile(rJavaLibPath + "/rJava.dll"); if (so.exists()) libMap.put("rJava", so); /* load the jri library */ UnixFile jri = new UnixFile(path + "/jri/libjri.so"); String rarch = System.getProperty("r.arch"); if (rarch != null && rarch.length() > 0) { UnixFile af = new UnixFile(path + "/jri" + rarch + "/libjri.so"); if (af.exists()) jri = af; else { af = new UnixFile(path + "/jri" + rarch + "/jri.dll"); if (af.exists()) jri = af; } } if (!jri.exists()) jri = new UnixFile(path + "/jri/libjri.jnilib"); if (!jri.exists()) jri = new UnixFile(path + "/jri/jri.dll"); if (jri.exists()) { libMap.put("jri", jri); if (verbose) System.out.println(" - registered JRI: " + jri); } /* if we are the primary loader, make us the context loader so projects that rely on the context loader pick us */ if (primaryLoader == this) Thread.currentThread().setContextClassLoader(this); if (verbose) { System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:"); for (Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) { Object key = entries.next(); System.out.println(" " + key + ": '" + libMap.get(key) + "'"); } System.out.println("\nRegistered class paths:"); for (Enumeration e = classPath.elements(); e.hasMoreElements(); ) System.out.println(" '" + e.nextElement() + "'"); System.out.println("\n-- end of class loader report --"); } }
/** * main method * * <p>This uses the system properties: * * <ul> * <li><code>rjava.path</code> : path of the rJava package * <li><code>rjava.lib</code> : lib sub directory of the rJava package * <li><code>main.class</code> : main class to "boot", assumes Main if not specified * <li><code>rjava.class.path</code> : set of paths to populate the initiate the class path * </ul> * * <p>and boots the "main" method of the specified <code>main.class</code>, passing the args down * to the booted class * * <p>This makes sure R and rJava are known by the class loader */ public static void main(String[] args) { String rJavaPath = System.getProperty("rjava.path"); if (rJavaPath == null) { System.err.println("ERROR: rjava.path is not set"); System.exit(2); } String rJavaLib = System.getProperty("rjava.lib"); if (rJavaLib == null) { // it is not really used so far, just for rJava.so, so we can guess rJavaLib = rJavaPath + File.separator + "libs"; } RJavaClassLoader cl = new RJavaClassLoader(u2w(rJavaPath), u2w(rJavaLib)); String mainClass = System.getProperty("main.class"); if (mainClass == null || mainClass.length() < 1) { System.err.println("WARNING: main.class not specified, assuming 'Main'"); mainClass = "Main"; } String classPath = System.getProperty("rjava.class.path"); if (classPath != null) { StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator); while (st.hasMoreTokens()) { String dirname = u2w(st.nextToken()); cl.addClassPath(dirname); } } try { cl.bootClass(mainClass, "main", args); } catch (Exception ex) { System.err.println("ERROR: while running main method: " + ex); ex.printStackTrace(); } }
// Velocity init public static void initVelocity() { if (velocityCatch == null) { System.out.println("init VM"); velocityCatch = new Object(); Properties props = new Properties(); props.setProperty("input.encoding", "UTF-8"); props.setProperty("output.encoding", "UTF-8"); if (getConfig().getChild("vmtemplatepath") != null) { props.setProperty("file.resource.loader.path", getConfig().getChildText("vmtemplatepath")); } if (System.getProperty("vmtemplatepath") != null) { props.setProperty("file.resource.loader.path", System.getProperty("vmtemplatepath")); // Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, // System.getProperty("vmtemplatepath"));//oder new FIle()? } System.out.println("vmtemplatepath=" + props.getProperty("vmtemplatepath")); try { Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, VeloLog.getInstance()); Velocity.init(props); } catch (Exception ex) { ex.printStackTrace(); } } }