public void bootOptionsReceived(BootEvent bootEvent) { log.info(" boot options received " + bootEvent.getNewSessionOptions()); // reload setting, to ensure correct bootstraps ConfigureFactory.getInstance().reloadSettings(); // If the options are not equal to the string 'null' then we have boot options if (!bootEvent.getNewSessionOptions().equals("null")) { // check if a session parameter is specified on the command line String[] args = new String[TN5250jConstants.NUM_PARMS]; parseArgs(bootEvent.getNewSessionOptions(), args); if (isSpecified("-s", args)) { String sd = getParm("-s", args); if (sessions.containsKey(sd)) { parseArgs(sessions.getProperty(sd), args); final String[] args2 = args; final String sd2 = sd; SwingUtilities.invokeLater(() -> newSession(sd2, args2)); } } else { if (args[0].startsWith("-")) { SwingUtilities.invokeLater(() -> startNewSession()); } else { final String[] args2 = args; final String sd2 = args[0]; SwingUtilities.invokeLater(() -> newSession(sd2, args2)); } } } else { SwingUtilities.invokeLater(() -> startNewSession()); } }
public boolean shouldSign(File input, List<Properties> containers) { Properties inf = null; // 1: Are we excluded from signing by our parents? // innermost jar is first on the list, it overrides outer jars for (Iterator<Properties> iterator = containers.iterator(); iterator.hasNext(); ) { inf = iterator.next(); if (inf.containsKey(Utils.MARK_EXCLUDE_CHILDREN_SIGN)) { if (Boolean.valueOf(inf.getProperty(Utils.MARK_EXCLUDE_CHILDREN_SIGN)).booleanValue()) { if (verbose) System.out.println( input.getName() + "is excluded from signing by its containers."); // $NON-NLS-1$ return false; } break; } } // 2: Is this jar itself marked as exclude? inf = Utils.getEclipseInf(input, verbose); if (inf != null && inf.containsKey(Utils.MARK_EXCLUDE_SIGN) && Boolean.valueOf(inf.getProperty(Utils.MARK_EXCLUDE_SIGN)).booleanValue()) { if (verbose) System.out.println( "Excluding " + input.getName() + " from signing."); // $NON-NLS-1$ //$NON-NLS-2$ return false; } return true; }
public void configure(final Properties configuration) throws ConfigurationException { if (!configuration.containsKey("project")) { throw new ConfigurationException("project is required"); } project = configuration.getProperty("project"); if (!configuration.containsKey(CONFIG_FILE)) { throw new ConfigurationException(CONFIG_FILE + " is required"); } scriptFile = new File(configuration.getProperty(CONFIG_FILE)); if (!scriptFile.isFile()) { throw new ConfigurationException( CONFIG_FILE + " does not exist or is not a file: " + scriptFile.getAbsolutePath()); } interpreter = configuration.getProperty(CONFIG_INTERPRETER); args = configuration.getProperty(CONFIG_ARGS); if (!configuration.containsKey(CONFIG_FORMAT)) { throw new ConfigurationException(CONFIG_FORMAT + " is required"); } format = configuration.getProperty(CONFIG_FORMAT); interpreterArgsQuoted = Boolean.parseBoolean(configuration.getProperty(CONFIG_INTERPRETER_ARGS_QUOTED)); configDataContext = new HashMap<String, Map<String, String>>(); final HashMap<String, String> configdata = new HashMap<String, String>(); configdata.put("project", project); configDataContext.put("context", configdata); executionDataContext = ScriptDataContextUtil.createScriptDataContextForProject(framework, project); executionDataContext.putAll(configDataContext); }
private void setBaseProps() { if (!properties.containsKey("slac.log.dir")) { properties.setProperty( "slac.log.dir", SlacUtil.ensureDir(SlacUtil.path(homeDir, "log")).getPath()); } if (!properties.containsKey("slac.data.dir")) { properties.setProperty( "slac.data.dir", SlacUtil.ensureDir(SlacUtil.path(homeDir, "data")).getPath()); } if (!properties.containsKey("slac.conf.dir")) { properties.setProperty( "slac.conf.dir", SlacUtil.ensureDir(SlacUtil.path(homeDir, "conf")).getPath()); } if (!properties.containsKey("slac.backup.dir")) { properties.setProperty("slac.backup.dir", SlacUtil.path(homeDir, "backup")); } if (!properties.containsKey("phantom.binary")) { for (String path : new String[] { SlacUtil.path(homeDir, "phantomjs"), "/usr/local/bin/phantomjs", "/usr/bin/phantomjs" }) { if (new File(path).canExecute()) { properties.setProperty("phantom.binary", path); break; } } } }
public static void main(String[] args) { final Properties options = StringUtils.argsToProperties(args, argOptionDefs()); if (args.length < 1 || options.containsKey("help")) { System.err.println(usage()); return; } final Pattern posPattern = options.containsKey("searchPos") ? Pattern.compile(options.getProperty("searchPos")) : null; final Pattern wordPattern = options.containsKey("searchWord") ? Pattern.compile(options.getProperty("searchWord")) : null; final boolean plainPrint = PropertiesUtils.getBool(options, "plain", false); final boolean ner = PropertiesUtils.getBool(options, "ner", false); final boolean detailedAnnotations = PropertiesUtils.getBool(options, "detailedAnnotations", false); String[] remainingArgs = options.getProperty("").split(" "); List<File> fileList = new ArrayList<>(); for (int i = 0; i < remainingArgs.length; i++) fileList.add(new File(remainingArgs[i])); final SpanishXMLTreeReaderFactory trf = new SpanishXMLTreeReaderFactory(true, true, ner, detailedAnnotations); ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (final File file : fileList) { pool.execute( new Runnable() { public void run() { try { Reader in = new BufferedReader( new InputStreamReader(new FileInputStream(file), "ISO-8859-1")); TreeReader tr = trf.newTreeReader(file.getPath(), in); process(file, tr, posPattern, wordPattern, plainPrint); tr.close(); } catch (IOException e) { e.printStackTrace(); } } }); } pool.shutdown(); try { pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * Return a list of resource model configuration * * @param props properties * @return List of Maps, each map containing "type": String, "props":Properties */ public static List<Map<String, Object>> listResourceModelConfigurations(final Properties props) { final ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int i = 1; boolean done = false; while (!done) { final String prefix = RESOURCES_SOURCE_PROP_PREFIX + "." + i; if (props.containsKey(prefix + ".type")) { final String providerType = props.getProperty(prefix + ".type"); final Properties configProps = new Properties(); final int len = (prefix + ".config.").length(); for (final Object o : props.keySet()) { final String key = (String) o; if (key.startsWith(prefix + ".config.")) { configProps.setProperty(key.substring(len), props.getProperty(key)); } } final HashMap<String, Object> map = new HashMap<String, Object>(); map.put("type", providerType); map.put("props", configProps); list.add(map); } else { done = true; } i++; } return list; }
private boolean testExecutionMode() { executionMode = false; JarFile file = null; try { file = new JarFile(getTangaraPath()); ZipEntry entry = file.getEntry(EXECUTION_PROPERTIES_FILENAME); if (entry != null) { executionMode = true; System.out.println("execution mode detected"); Properties executionProperties = new Properties(); InputStream ips = ClassLoader.getSystemResourceAsStream(EXECUTION_PROPERTIES_FILENAME); executionProperties.load(ips); if (executionProperties.containsKey("main-program")) { String mainTangaraFile = executionProperties.getProperty("main-program"); System.out.println("main tangara file: " + mainTangaraFile); properties.setProperty("main-program", mainTangaraFile); } else { System.err.println("error : main program not specified"); } if (executionProperties.containsKey("language")) { String language = executionProperties.getProperty("language"); properties.setProperty("language", language); System.out.println("language: " + language); } else { System.err.println("error : language not specified"); } if (executionProperties.containsKey("resources")) { String resources = executionProperties.getProperty("resources"); properties.setProperty("program.resources", resources); System.out.println("resources: " + resources); } else { System.err.println("error : resources not specified"); } } } catch (IOException e) { e.printStackTrace(); } finally { if (file != null) { try { file.close(); } catch (IOException e) { System.err.println("error while closing tangara JAR file"); } } } return executionMode; }
private void populateWorldAutoLoadList() { if (worldlyProperties.containsKey(HGStatics.WORLDS_AUTOLOAD_KEY)) { String worldsToLoad = worldlyProperties.getProperty(HGStatics.WORLDS_AUTOLOAD_KEY); worldLoadArray = worldsToLoad.split("/"); worldLoadSet.addAll(Arrays.asList(worldLoadArray)); worldLoadSet.remove(""); } }
private void load(File jarFile) { ClassLoader loader; try { loader = URLClassLoader.newInstance( new URL[] {jarFile.toURI().toURL()}, getClass().getClassLoader()); } catch (MalformedURLException e) { Application.LOGGER.error( "Error while loading plugin file - " + jarFile.getAbsolutePath(), e); return; } InputStream stream = loader.getResourceAsStream(MANIFEST_FILE); Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { Application.LOGGER.error( "Manifest file - " + MANIFEST_FILE + " not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } String pluginClassName = properties.getProperty("plugin.class"); if (!properties.containsKey("plugin.class")) { Application.LOGGER.error( "plugin.class not defined in the manifest file in the plugin jar - " + jarFile.getAbsolutePath()); return; } Class<?> clazz; try { clazz = Class.forName(pluginClassName, true, loader); } catch (ClassNotFoundException e) { Application.LOGGER.error( "Plugin main class - " + pluginClassName + " defined in manifest not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } if (!Plugin.class.isAssignableFrom(clazz)) { Application.LOGGER.error( "Plugin class - " + clazz + " is not a Plugin, in the plugin jar - " + jarFile.getAbsolutePath()); } load((Class<? extends Plugin>) clazz, properties); }
private void laden(Path saveName) throws IOException { Properties prop = new Properties(); FileInputStream in = new FileInputStream(saveName.toString()); prop.load(in); for (int i = 0; prop.containsKey(String.format("quellMenu%d", i)); i++) quellListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("quellMenu%d", i))), Paths.get(prop.getProperty(String.format("quellMenu%d", i))))); for (int i = 0; prop.containsKey(String.format("zielMenu%d", i)); i++) zielListModel.addElement( new ListItem( Paths.get(prop.getProperty(String.format("zielMenu%d", i))), Paths.get(prop.getProperty(String.format("zielMenu%d", i))))); in.close(); }
private void target(Info info) { if (raidTarget.containsKey(info.getChannel())) { info.sendMessage( COLOR + "The raid target is " + raidTarget.get(info.getChannel()) + " located at " + raidLocation.get(info.getChannel())); } else info.sendMessage("No target is set."); }
public boolean removeWorldlyProperty(String key) throws IOException { if (worldlyProperties.containsKey(key)) { if (worldlyProperties.remove(key) != null) { saveConfigFileProperties(); return true; } else { return false; } } else { return false; } }
/** * Establishes a connection to the database from the properties. You will need to specify a "file" * property to point to the location of the on-disk instance. If the property "quote" is set to a * true value, LFNs and PFNs are always quoted. By default, and if false, LFNs and PFNs are only * quoted as necessary. * * @param props is the property table with sufficient settings to establish a link with the * database. * @return true if connected, false if failed to connect. * @throws Error subclasses for runtime errors in the class loader. */ public boolean connect(Properties props) { // update the m_writeable flag if specified if (props.containsKey(Directory.FLAT_LFN_PROPERTY_KEY)) { mConstructFlatLFN = Boolean.parse(props.getProperty(Directory.FLAT_LFN_PROPERTY_KEY), false); } String value = props.getProperty(Directory.SITE_PROPERTY_KEY); if (value != null) { this.mSiteHandle = value; } value = props.getProperty(Directory.URL_PRFIX_PROPERTY_KEY); if (value != null) { this.mURLPrefix = value; } if (props.containsKey(Directory.DIRECTORY_PROPERTY_KEY)) { return connect(props.getProperty("directory")); } return false; }
@SuppressWarnings({"unchecked", "rawtypes"}) private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) { List<File> potentialScripts; List<File> allScripts = getAvailableScripts(); GantBinding binding = new GantBinding(); binding.setVariable("scriptName", scriptName); setDefaultInputStream(binding); // Now find what scripts match the one requested by the user. potentialScripts = getPotentialScripts(scriptName, allScripts); if (potentialScripts.size() == 0) { try { File aliasFile = new File(settings.getUserHome(), ".grails/.aliases"); if (aliasFile.exists()) { Properties aliasProperties = new Properties(); aliasProperties.load(new FileReader(aliasFile)); if (aliasProperties.containsKey(commandLine.getCommandName())) { String aliasValue = (String) aliasProperties.get(commandLine.getCommandName()); String[] aliasPieces = aliasValue.split(" "); String commandName = aliasPieces[0]; String correspondingScriptName = GrailsNameUtils.getNameFromScript(commandName); potentialScripts = getPotentialScripts(correspondingScriptName, allScripts); if (potentialScripts.size() > 0) { String[] additionalArgs = new String[aliasPieces.length - 1]; System.arraycopy(aliasPieces, 1, additionalArgs, 0, additionalArgs.length); insertArgumentsInFrontOfExistingArguments(commandLine, additionalArgs); } } } } catch (Exception e) { console.error(e); } } // First try to load the script from its file. If there is no // file, then attempt to load it as a pre-compiled script. If // that fails, then let the user know and then exit. if (potentialScripts.size() > 0) { potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts); final File scriptFile = potentialScripts.get(0); if (!isGrailsProject() && !isExternalScript(scriptFile)) { return handleScriptExecutedOutsideProjectError(); } return executeScriptFile(commandLine, scriptName, env, binding, scriptFile); } return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts); }
protected Engine extendStoreAppend() { final File file = props.containsKey(Keys.file) ? new File(props.getProperty(Keys.file)) : null; boolean compressionEnabled = Keys.compression_lzf.equals(props.getProperty(Keys.compression)); return new StoreAppend( file, propsGetRafMode() > 0, propsGetBool(Keys.readOnly), propsGetBool(Keys.transactionDisable), propsGetBool(Keys.deleteFilesAfterClose), propsGetBool(Keys.syncOnCommitDisable), propsGetBool(Keys.checksum), compressionEnabled, propsGetXteaEncKey()); }
public SessionPanel startNewSession() { String sel = ""; if (containsNotOnlyNullValues(sessionArgs) && !sessionArgs[0].startsWith("-")) { sel = sessionArgs[0]; } else { sel = getDefaultSession(); } Sessions sess = manager.getSessions(); if (sel != null && sess.getCount() == 0 && sessions.containsKey(sel)) { sessionArgs = new String[TN5250jConstants.NUM_PARMS]; parseArgs(sessions.getProperty(sel), sessionArgs); } return newSession(sel, sessionArgs); }
private File getRedirectionPath(File redirectFile) { File path = null; if (redirectFile.exists()) { InputStream redirectStream = null; try { Properties redirectProperties = new Properties(); redirectStream = new FileInputStream(redirectFile); redirectProperties.load(redirectStream); if (redirectProperties.containsKey(REDIRECT_PATH_P)) { path = new File(redirectProperties.getProperty(REDIRECT_PATH_P)); } } catch (Exception e) { System.err.println( "Error while reading redirect file '" + redirectFile.getAbsolutePath() + "'\n" + e); } finally { IOUtils.closeQuietly(redirectStream); } } return path; }
public static List<String> loadLastSessionViewNames() { List<String> sessionNames = new ArrayList<String>(); if (sessions.containsKey("emul.startLastView")) { String emulview = sessions.getProperty("emul.view", ""); int idxstart = 0; int idxend = emulview.indexOf(PARAM_START_SESSION, idxstart); for (; idxend > -1; idxend = emulview.indexOf(PARAM_START_SESSION, idxstart)) { String sessname = emulview.substring(idxstart, idxend).trim(); if (sessname.length() > 0) { sessionNames.add(sessname); } idxstart = idxend + PARAM_START_SESSION.length(); } if (idxstart + PARAM_START_SESSION.length() < emulview.length()) { String sessname = emulview.substring(idxstart + PARAM_START_SESSION.length() - 1).trim(); if (sessname.length() > 0) { sessionNames.add(sessname); } } } return sessionNames; }
/** * Starts Grid instance. Note that if grid is already started, then it will be looked up and * returned from this method. * * @return Started grid. */ private Grid startGrid() { Properties props = System.getProperties(); gridName = props.getProperty(GRIDGAIN_NAME.name()); if (!props.containsKey(GRIDGAIN_NAME.name()) || G.state(gridName) != GridFactoryState.STARTED) { selfStarted = true; // Set class loader for the spring. ClassLoader curCl = Thread.currentThread().getContextClassLoader(); // Add no-op logger to remove no-appender warning. Appender app = new NullAppender(); Logger.getRootLogger().addAppender(app); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Grid grid = G.start(cfgPath); gridName = grid.name(); System.setProperty(GRIDGAIN_NAME.name(), grid.name()); return grid; } catch (GridException e) { throw new GridRuntimeException("Failed to start grid: " + cfgPath, e); } finally { Logger.getRootLogger().removeAppender(app); Thread.currentThread().setContextClassLoader(curCl); } } return G.grid(gridName); }
public boolean hasPropertyKey(String key) { return fProperties.containsKey(key); }
private void setDefaultLocale() { if (sessions.containsKey("emul.locale")) { Locale.setDefault(parseLocal(sessions.getProperty("emul.locale"))); } }
/** * Gets the value of a property * * @param name name of the property * @return the property value or <code>null</code> if the property does not exist */ public String getProperty(String name) { if (properties.containsKey(name)) return properties.getProperty(name); else if (fixedProperties.containsKey(name)) return fixedProperties.getProperty(name); displayError("Could not find property " + name); return null; }
/** constructs Engine using current settings */ public Engine makeEngine() { final boolean readOnly = propsGetBool(Keys.readOnly); final File file = props.containsKey(Keys.file) ? new File(props.getProperty(Keys.file)) : null; final String volume = props.getProperty(Keys.volume); final String store = props.getProperty(Keys.store); if (readOnly && file == null) throw new UnsupportedOperationException("Can not open in-memory DB in read-only mode."); if (readOnly && !file.exists() && !Keys.store_append.equals(store)) { throw new UnsupportedOperationException("Can not open non-existing file in read-only mode."); } if (propsGetLong(Keys.sizeLimit, 0) > 0 && Keys.store_append.equals(store)) throw new UnsupportedOperationException("Append-Only store does not support Size Limit"); extendArgumentCheck(); Engine engine; if (!Keys.store_append.equals(store)) { Volume.Factory folFac = extendStoreVolumeFactory(); engine = propsGetBool(Keys.transactionDisable) ? extendStoreDirect(folFac) : extendStoreWAL(folFac); } else { if (Keys.volume_heap.equals(volume) || Keys.volume_offheap.equals(volume)) throw new UnsupportedOperationException( "Append Storage format is not supported with in-memory dbs"); engine = extendStoreAppend(); } engine = extendWrapStore(engine); if (propsGetBool(Keys.asyncWrite) && !readOnly) { engine = extendAsyncWriteEngine(engine); } final String cache = props.getProperty(Keys.cache, CC.DEFAULT_CACHE); if (Keys.cache_disable.equals(cache)) { // do not wrap engine in cache } else if (Keys.cache_hashTable.equals(cache)) { engine = extendCacheHashTable(engine); } else if (Keys.cache_hardRef.equals(cache)) { engine = extendCacheHardRef(engine); } else if (Keys.cache_weakRef.equals(cache)) { engine = extendCacheWeakRef(engine); } else if (Keys.cache_softRef.equals(cache)) { engine = extendCacheSoftRef(engine); } else if (Keys.cache_lru.equals(cache)) { engine = extendCacheLRU(engine); } else { throw new IllegalArgumentException("unknown cache type: " + cache); } engine = extendWrapCache(engine); if (propsGetBool(Keys.snapshots)) engine = extendSnapshotEngine(engine); engine = extendWrapSnapshotEngine(engine); if (readOnly) engine = new ReadOnlyEngine(engine); if (propsGetBool(Keys.closeOnJvmShutdown)) { engine = new EngineWrapper.CloseOnJVMShutdown(engine); } // try to read one record from DB, to make sure encryption and compression are correctly set. Fun.Tuple2<Integer, byte[]> check = null; try { check = (Fun.Tuple2<Integer, byte[]>) engine.get(Engine.CHECK_RECORD, Serializer.BASIC); if (check != null) { if (check.a.intValue() != Arrays.hashCode(check.b)) throw new RuntimeException("invalid checksum"); } } catch (Throwable e) { throw new IllegalArgumentException( "Error while opening store. Make sure you have right password, compression or encryption is well configured.", e); } if (check == null && !engine.isReadOnly()) { // new db, so insert testing record byte[] b = new byte[127]; new Random().nextBytes(b); check = Fun.t2(Arrays.hashCode(b), b); engine.update(Engine.CHECK_RECORD, check, Serializer.BASIC); engine.commit(); } return engine; }
private boolean isPropertySet(String key) { return properties.containsKey(key); }
public HashMap<String, Properties> generateResourceBundle(String baseName) throws GenerationException { // be sure to have at least the default URI constant settings if (uriGeneration == null) { uriGeneration = GenerationSetting.createDefault(caseFormat, "", ""); } Pattern pattern = Pattern.compile(Pattern.quote(getPrefix()) + "(.+)"); HashMap<String, URI> splitUris = new HashMap<>(); for (Resource nextSubject : model.subjects()) { if (nextSubject instanceof URI) { Matcher matcher = pattern.matcher(nextSubject.stringValue()); if (matcher.find()) { String k = matcher.group(1); splitUris.put(k, (URI) nextSubject); } } } List<String> keys = new ArrayList<>(); keys.addAll(splitUris.keySet()); Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); HashMap<String, Properties> bundles = new HashMap<>(); // Default we have for sure bundles.put(baseName, new Properties()); for (String key : keys) { final URI resource = splitUris.get(key); // String nextKey = cleanKey(doCaseFormatting(key, uriGeneration.getCaseFormat())); for (URI p : LABEL_PROPERTIES) { for (Value v : GraphUtil.getObjects(model, resource, p)) { if (v instanceof Literal) { final Literal lit = (Literal) v; final String lang = lit.getLanguage(); final Properties bundle; if (lang == null) { bundle = bundles.get(baseName); } else if (bundles.containsKey(baseName + "_" + lang)) { bundle = bundles.get(baseName + "_" + lang); } else { bundle = new Properties(); bundles.put(baseName + "_" + lang, bundle); } if (!bundle.containsKey(nextKey + ".label")) { bundle.put(nextKey + ".label", lit.getLabel().replaceAll("\\s+", " ")); } } } } for (URI p : COMMENT_PROPERTIES) { for (Value v : GraphUtil.getObjects(model, resource, p)) { if (v instanceof Literal) { final Literal lit = (Literal) v; final String lang = lit.getLanguage(); final Properties bundle; if (lang == null) { bundle = bundles.get(baseName); } else if (bundles.containsKey(baseName + "_" + lang)) { bundle = bundles.get(baseName + "_" + lang); } else { bundle = new Properties(); bundles.put(baseName + "_" + lang, bundle); } if (!bundle.containsKey(nextKey + ".comment")) { bundle.put(nextKey + ".comment", lit.getLabel().replaceAll("\\s+", " ")); } } } } } if (getPreferredLanguage() != null) { log.debug("completing default Bundle with preferred language {}", getPreferredLanguage()); final Properties defaultBundle = bundles.get(baseName); final Properties prefBundle = bundles.get(baseName + "_" + getPreferredLanguage()); if (prefBundle != null) { for (Entry<Object, Object> key : prefBundle.entrySet()) { String nextKey = (String) key.getKey(); if (!defaultBundle.containsKey(nextKey)) { log.trace("copying {} from {} to default Bundle", nextKey, getPreferredLanguage()); defaultBundle.setProperty(nextKey, (String) key.getValue()); } } } else { log.warn("No Bundle data found for preferred language {}", getPreferredLanguage()); } } return bundles; }
private void path(Info info) { if (raidPath.containsKey(info.getChannel())) { info.sendMessage(COLOR + raidPath.get(info.getChannel())); } else info.sendMessage("No path to the target is set."); }
@SuppressWarnings("unchecked") public static void main(String[] args) { String dbname; Properties props = new Properties(); Properties fileprops = new Properties(); boolean dotransactions = true; int threadcount = 1; int target = 0; boolean status = false; String label = ""; // parse arguments int argindex = 0; if (args.length == 0) { usageMessage(); System.exit(0); } while (args[argindex].startsWith("-")) { if (args[argindex].compareTo("-threads") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } int tcount = Integer.parseInt(args[argindex]); props.setProperty("threadcount", tcount + ""); argindex++; } else if (args[argindex].compareTo("-target") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } int ttarget = Integer.parseInt(args[argindex]); props.setProperty("target", ttarget + ""); argindex++; } else if (args[argindex].compareTo("-load") == 0) { dotransactions = false; argindex++; } else if (args[argindex].compareTo("-t") == 0) { dotransactions = true; argindex++; } else if (args[argindex].compareTo("-s") == 0) { status = true; argindex++; } else if (args[argindex].compareTo("-db") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } props.setProperty("db", args[argindex]); argindex++; } else if (args[argindex].compareTo("-l") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } label = args[argindex]; argindex++; } else if (args[argindex].compareTo("-P") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } String propfile = args[argindex]; argindex++; Properties myfileprops = new Properties(); try { myfileprops.load(new FileInputStream(propfile)); } catch (IOException e) { System.out.println(e.getMessage()); System.exit(0); } // Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e = myfileprops.propertyNames(); e.hasMoreElements(); ) { String prop = (String) e.nextElement(); fileprops.setProperty(prop, myfileprops.getProperty(prop)); } } else if (args[argindex].compareTo("-p") == 0) { argindex++; if (argindex >= args.length) { usageMessage(); System.exit(0); } int eq = args[argindex].indexOf('='); if (eq < 0) { usageMessage(); System.exit(0); } String name = args[argindex].substring(0, eq); String value = args[argindex].substring(eq + 1); props.put(name, value); // System.out.println("["+name+"]=["+value+"]"); argindex++; } else { System.out.println("Unknown option " + args[argindex]); usageMessage(); System.exit(0); } if (argindex >= args.length) { break; } } if (argindex != args.length) { usageMessage(); System.exit(0); } // set up logging // BasicConfigurator.configure(); // overwrite file properties with properties from the command line // Issue #5 - remove call to stringPropertyNames to make compilable under Java 1.5 for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String prop = (String) e.nextElement(); fileprops.setProperty(prop, props.getProperty(prop)); } props = fileprops; if (!checkRequiredProperties(props)) { System.exit(0); } long maxExecutionTime = Integer.parseInt(props.getProperty(MAX_EXECUTION_TIME, "0")); // get number of threads, target and db threadcount = Integer.parseInt(props.getProperty("threadcount", "1")); dbname = props.getProperty("db", "com.yahoo.ycsb.BasicDB"); target = Integer.parseInt(props.getProperty("target", "0")); // compute the target throughput double targetperthreadperms = -1; if (target > 0) { double targetperthread = ((double) target) / ((double) threadcount); targetperthreadperms = targetperthread / 1000.0; } System.out.println("YCSB Client 0.1"); System.out.print("Command line:"); for (int i = 0; i < args.length; i++) { System.out.print(" " + args[i]); } System.out.println(); System.err.println("Loading workload..."); // show a warning message that creating the workload is taking a while // but only do so if it is taking longer than 2 seconds // (showing the message right away if the setup wasn't taking very long was confusing people) Thread warningthread = new Thread() { public void run() { try { sleep(2000); } catch (InterruptedException e) { return; } System.err.println(" (might take a few minutes for large data sets)"); } }; warningthread.start(); // set up measurements Measurements.setProperties(props); // load the workload ClassLoader classLoader = Client.class.getClassLoader(); Workload workload = null; try { Class workloadclass = classLoader.loadClass(props.getProperty(WORKLOAD_PROPERTY)); workload = (Workload) workloadclass.newInstance(); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { workload.init(props); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } warningthread.interrupt(); // run the workload System.err.println("Starting test."); int opcount; if (dotransactions) { opcount = Integer.parseInt(props.getProperty(OPERATION_COUNT_PROPERTY, "0")); } else { if (props.containsKey(INSERT_COUNT_PROPERTY)) { opcount = Integer.parseInt(props.getProperty(INSERT_COUNT_PROPERTY, "0")); } else { opcount = Integer.parseInt(props.getProperty(RECORD_COUNT_PROPERTY, "0")); } } Vector<Thread> threads = new Vector<Thread>(); for (int threadid = 0; threadid < threadcount; threadid++) { DB db = null; try { db = DBFactory.newDB(dbname, props); } catch (UnknownDBException e) { System.out.println("Unknown DB " + dbname); System.exit(0); } Thread t = new ClientThread( db, dotransactions, workload, threadid, threadcount, props, opcount / threadcount, targetperthreadperms); threads.add(t); // t.start(); } StatusThread statusthread = null; if (status) { boolean standardstatus = false; if (props.getProperty("measurementtype", "").compareTo("timeseries") == 0) { standardstatus = true; } statusthread = new StatusThread(threads, label, standardstatus); statusthread.start(); } long st = System.currentTimeMillis(); for (Thread t : threads) { t.start(); } Thread terminator = null; if (maxExecutionTime > 0) { terminator = new TerminatorThread(maxExecutionTime, threads, workload); terminator.start(); } int opsDone = 0; for (Thread t : threads) { try { t.join(); opsDone += ((ClientThread) t).getOpsDone(); } catch (InterruptedException e) { } } long en = System.currentTimeMillis(); if (terminator != null && !terminator.isInterrupted()) { terminator.interrupt(); } if (status) { statusthread.interrupt(); } try { workload.cleanup(); } catch (WorkloadException e) { e.printStackTrace(); e.printStackTrace(System.out); System.exit(0); } try { exportMeasurements(props, opsDone, en - st); } catch (IOException e) { System.err.println("Could not export measurements, error: " + e.getMessage()); e.printStackTrace(); System.exit(-1); } System.exit(0); }