List of usage examples for java.util List iterator
Iterator<E> iterator();
From source file:com.music.tools.ScaleTester.java
public static void main(String[] args) { System.out.println(//from w w w. j ava2 s. c o m "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>"); final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true); try { fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class); int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class); List<Double> harmonicFrequencies = new ArrayList<>(); List<String> ratios = new ArrayList<>(); Set<Double> frequencies = new HashSet<Double>(); frequencies.add(fundamentalFreq); int octaveMultiplier = 2; for (int i = 2; i < 100; i++) { // Exclude the 7th harmonic TODO exclude the 11th as well? // http://www.phy.mtu.edu/~suits/badnote.html if (i % 7 == 0) { continue; } double actualFreq = fundamentalFreq * i; double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier); if (closestTonicRatio < 1 || closestTonicRatio > 2) { octaveMultiplier *= 2; } double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier); double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic); harmonicFrequencies.add(actualFreq); frequencies.add(normalizedFreq); if (frequencies.size() == pitchesInChromaticScale) { break; } } System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies); System.out.println("Transposed harmonic frequencies: " + frequencies); List<Double> chromaticScale = new ArrayList<>(frequencies); Collections.sort(chromaticScale); // find the "perfect" interval (e.g. perfect fifth) int perfectIntervalIndex = 0; int idx = 0; for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) { Double noteFreq = it.next(); long[] fraction = findCommonFraction(noteFreq / fundamentalFreq); fractionCache.put(noteFreq, fraction); if (fraction[0] == 3 && fraction[1] == 2) { perfectIntervalIndex = idx; System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex); } idx++; ratios.add(Arrays.toString(fraction)); } System.out.println("Ratios to fundemental frequency: " + ratios); if (getBooleanArgument(args, 4, USE_ET)) { chromaticScale = temper(chromaticScale); } System.out.println(); System.out.println("Chromatic scale: " + chromaticScale); Set<Double> scaleSet = new HashSet<Double>(); scaleSet.add(chromaticScale.get(0)); idx = 0; List<Double> orderedInCircle = new ArrayList<>(); // now go around the circle of perfect intervals and put the notes // in order while (orderedInCircle.size() < chromaticScale.size()) { orderedInCircle.add(chromaticScale.get(idx)); idx += perfectIntervalIndex; idx = idx % chromaticScale.size(); } System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle); List<Double> scale = new ArrayList<Double>(scaleSet); int currentIdxInCircle = orderedInCircle.size() - 1; // start with // the last // note in the // circle int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class); while (scale.size() < scaleSize) { double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size()); if (!scale.contains(pitch)) { scale.add(pitch); } currentIdxInCircle++; } Collections.sort(scale); System.out.println("Scale: " + scale); SourceDataLine line = AudioSystem.getSourceDataLine(af); line.open(af); line.start(); Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]); // first play the whole scale WaveMelodyGenerator.playScale(line, scaleFrequencies); // then generate a random melody in the scale WaveMelodyGenerator.playMelody(line, scaleFrequencies); line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Cresendo.java
public static void main(String[] args) { String cfgFileReceiver = null; // Path to config file for eif receiver agent String cfgFileEngine = null; // Path to config file for xml event engine Options opts = null; // Command line options HelpFormatter hf = null; // Command line help formatter // Setup the message record which will contain text written to the log file ////from w w w. j a v a 2 s. c om // The message logger object is created when the "-l" is processed // as this object need to be associated with a log file // LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", ""); // Get the directory separator (defaults to "/") // dirSep = System.getProperty("file.separator", "/"); // Initialise the structure containing the event handler objects // Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10); // Process the command line arguments // try { opts = new Options(); hf = new HelpFormatter(); opts.addOption("h", "help", false, "Command line arguments help"); opts.addOption("i", "instance name", true, "Name of cresendo instance"); opts.addOption("l", "log dir", true, "Path to log file directory"); opts.addOption("c", "config dir", true, "Path to configuarion file directory"); opts.getOption("l").setRequired(true); opts.getOption("c").setRequired(true); BasicParser parser = new BasicParser(); CommandLine cl = parser.parse(opts, args); // Print out some help and exit // if (cl.hasOption('h')) { hf.printHelp("Options", opts); System.exit(0); } // Set the instance name // if (cl.hasOption('i')) { instanceName = cl.getOptionValue('i'); // Set to something other than "default" } // Setup the message and trace logging objects for the EventEngine // if (cl.hasOption('l')) { // Setup the the paths to the message, trace and status log files // logDir = cl.getOptionValue("l"); logPath = logDir + dirSep + instanceName + "-engine.log"; tracePath = logDir + dirSep + instanceName + "-engine.trace"; statusPath = logDir + dirSep + instanceName + "-engine.status"; } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'l' is a required option", opts); System.exit(1); } // Read the receiver and engine config files in the config directory // if (cl.hasOption('c')) { // Setup and check path to eif config file for TECAgent receiver object // configDir = cl.getOptionValue("c"); cfgFileReceiver = configDir + dirSep + instanceName + ".conf"; checkConfigFile(cfgFileReceiver); // Setup and check path to xml config file for the EventEngine // cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml"; checkConfigFile(cfgFileEngine); } else { // NOTE: This should be picked up by the MissingOptionException catch below // but I couldn't get this to work so I added the following code: // hf.printHelp("Option 'c' is a required option", opts); System.exit(1); } } catch (UnrecognizedOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingOptionException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (MissingArgumentException e) { hf.printHelp(e.toString(), opts); System.exit(1); } catch (ParseException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Main program // try { // ===================================================================== // Setup the message, trace and status logger objects // try { msgHandler = new FileHandler("cresendo", "message handler", logPath); msgHandler.openDevice(); msgLogger = new MessageLogger("cresendo", "message log"); msgLogger.addHandler(msgHandler); trcHandler = new FileHandler("cresendo", "trace handler", tracePath); trcHandler.openDevice(); trcLogger = new TraceLogger("cresendo", "trace log"); trcLogger.addHandler(trcHandler); statLogger = new StatusLogger(statusPath); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Add the shutdown hook // Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName)); // --------------------------------------------------------------------- // ===================================================================== // Load and parse the xml event engine configuration file // // msg.setText("Loading xml engine from: '" + cfgFileEngine + "'"); try { XMLConfiguration xmlProcessor = new XMLConfiguration(); xmlProcessor.setFileName(cfgFileEngine); // Validate the xml against a document type declaration // xmlProcessor.setValidating(true); // Don't interpolate the tag contents by splitting them on a delimiter // (ie by default a comma) // xmlProcessor.setDelimiterParsingDisabled(true); // This will throw a ConfigurationException if the xml document does not // conform to its dtd. By doing this we hopefully catch any errors left // behind after the xml configuration file has been edited. // xmlProcessor.load(); // Setup the trace flag // ConfigurationNode engine = xmlProcessor.getRootNode(); List rootAttribute = engine.getAttributes(); for (Iterator it = rootAttribute.iterator(); it.hasNext();) { ConfigurationNode attr = (ConfigurationNode) it.next(); String attrName = attr.getName(); String attrValue = (String) attr.getValue(); if (attrValue == null || attrValue == "") { System.err.println("\n Error: The value of the attribute '" + attrName + "'" + "\n in the xml file '" + cfgFileEngine + "'" + "\n is not set"); System.exit(1); } if (attrName.matches("trace")) { if (attrValue.matches("true") || attrValue.matches("on")) { trcLogger.setLogging(true); } } if (attrName.matches("status")) { if (attrValue.matches("true") || attrValue.matches("on")) { statLogger.setLogging(true); } else { statLogger.setLogging(false); } } if (attrName.matches("interval")) { if (!attrValue.matches("[0-9]+")) { System.err.println("\n Error: The value of the interval attribute in: '" + cfgFileEngine + "'" + "\n should only contain digits from 0 to 9." + "\n It currently contains: '" + attrValue + "'"); System.exit(1); } statLogger.setInterval(Integer.parseInt(attrValue)); } } // Now build and instantiate the list of classes that will process events // received by the TECAgent receiver in a chain like manner. // List classes = xmlProcessor.configurationsAt("class"); for (Iterator it = classes.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); // sub contains now all data contained in a single <class></class> tag set // String className = sub.getString("name"); // Log message // msg.setText(msg.getText() + "\n Instantiated event handler class: '" + className + "'"); // The angle brackets describing the class of object held by the // Vector are implemented by Java 1.5 and have 2 effects. // // 1. The list accepts only elements of that class and nothing else // (Of course thanks to Auto-Wrap you can also add double-values) // // 2. the get(), firstElement() ... Methods don't return a Object, but // they deliver an element of the class. // Vector<Class> optTypes = new Vector<Class>(10, 10); Vector<Object> optValues = new Vector<Object>(10, 10); for (int i = 0; i <= sub.getMaxIndex("option"); i++) { Object optValue = null; String optVarName = sub.getString("option(" + i + ")[@varname]"); String optJavaType = sub.getString("option(" + i + ")[@javatype]"); // Use the specified java type in order to make the method call // to the heirarchical sub object [painful :-((] // if (optJavaType.matches("byte")) { optTypes.addElement(byte.class); optValue = sub.getByte("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("short")) { optTypes.addElement(byte.class); optValue = sub.getShort("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("int")) { optTypes.addElement(int.class); optValue = sub.getInt("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("long")) { optTypes.addElement(long.class); optValue = sub.getLong("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0; // Set to something nullish } } else if (optJavaType.matches("float")) { optTypes.addElement(float.class); optValue = sub.getFloat("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("double")) { optTypes.addElement(double.class); optValue = sub.getDouble("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = 0.0; // Set to something nullish } } else if (optJavaType.matches("boolean")) { optTypes.addElement(boolean.class); optValue = sub.getBoolean("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = false; // Set to something nullish } } else if (optJavaType.matches("String")) { optTypes.addElement(String.class); optValue = sub.getString("option(" + i + ")"); if (optValue == null) // Catch nulls { optValue = ""; // Set it to something nullish } } else { System.err.println( "Error: Unsupported java type found in xml config: '" + optJavaType + "'"); System.exit(1); } // Add option value element // // System.out.println("Option value is: '" + optValue.toString() + "'\n"); // optValues.addElement(optValue); // Append to message text // String msgTemp = msg.getText(); msgTemp += "\n option name: '" + optVarName + "'"; msgTemp += "\n option type: '" + optJavaType + "'"; msgTemp += "\n option value: '" + optValues.lastElement().toString() + "'"; msg.setText(msgTemp); } try { // Instantiate the class with the java reflection api // Class klass = Class.forName(className); // Setup an array of paramater types in order to retrieve the matching constructor // Class[] types = optTypes.toArray(new Class[optTypes.size()]); // Get the constructor for the class which matches the parameter types // Constructor konstruct = klass.getConstructor(types); // Create an instance of the event handler // IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray()); // Add the instance to the list of event handlers // eventHandler.addElement(eventProcessor); } catch (InvocationTargetException e) { System.err.println("Error: " + e.toString()); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: class name not found: '" + className + "' \n" + e.toString()); System.exit(1); } catch (Exception e) { System.err.println( "Error: failed to instantiate class: '" + className + "' \n" + e.toString()); System.exit(1); } } } catch (ConfigurationException cex) // Something went wrong loading the xml file { System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString()); System.exit(1); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // --------------------------------------------------------------------- // ===================================================================== // Setup the TECAgent receiver // Reader cfgIn = null; try { cfgIn = new FileReader(cfgFileReceiver); } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } // Start the TECAgent receiver and register the event engine handler // TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false); EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger); receiver.registerListener(ee); // Construct message and send it to the message log // String text = "\n Cresendo instance '" + instanceName + "' listening for events on port '" + receiver.getConfigVal("ServerPort") + "'"; msg.setText(msg.getText() + text); msgLogger.log(msg); // Send message to log // --------------------------------------------------------------------- // ===================================================================== // Initiate status logging // if (statLogger.isLogging()) { int seconds = statLogger.getInterval(); while (true) { try { statLogger.log(); } catch (Exception ex) { System.err.println("\n An error occurred while writing to '" + statusPath + "'" + "\n '" + ex.toString() + "'"); } Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds } } // --------------------------------------------------------------------- } catch (Exception e) { System.err.println(e.toString()); System.exit(1); } }
From source file:io.werval.cli.DamnSmallDevShell.java
public static void main(String[] args) { Options options = declareOptions();// ww w . ja v a 2 s.co m CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); // Handle --help if (cmd.hasOption("help")) { PrintWriter out = new PrintWriter(System.out); printHelp(options, out); out.flush(); System.exit(0); } // Handle --version if (cmd.hasOption("version")) { System.out.print(String.format( "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n" + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n" + "OS name: %s, version: %s, arch: %s\n", VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home"), Locale.getDefault().toString(), System.getProperty("file.encoding"), System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"))); System.out.flush(); System.exit(0); } // Debug final boolean debug = cmd.hasOption('d'); // Temporary directory final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp")); if (debug) { System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'."); } // Handle commands @SuppressWarnings("unchecked") List<String> commands = cmd.getArgList(); if (commands.isEmpty()) { commands = Collections.singletonList("start"); } if (debug) { System.out.println("Commands to be executed: " + commands); } Iterator<String> commandsIterator = commands.iterator(); while (commandsIterator.hasNext()) { String command = commandsIterator.next(); switch (command) { case "new": System.out.println(LOGO); newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd); break; case "clean": cleanCommand(debug, tmpDir); break; case "devshell": System.out.println(LOGO); devshellCommand(debug, tmpDir, cmd); break; case "start": System.out.println(LOGO); startCommand(debug, tmpDir, cmd); break; case "secret": secretCommand(); break; default: PrintWriter out = new PrintWriter(System.err); System.err.println("Unknown command: '" + command + "'"); printHelp(options, out); out.flush(); System.exit(1); break; } } } catch (IllegalArgumentException | ParseException | IOException ex) { PrintWriter out = new PrintWriter(System.err); printHelp(options, out); out.flush(); System.exit(1); } catch (WervalException ex) { ex.printStackTrace(System.err); System.err.flush(); System.exit(1); } }
From source file:com.moss.veracity.core.Veracity.java
public static void main(String[] args) throws Exception { File log4jConfigFile = new File("log4j.xml"); if (log4jConfigFile.exists()) { DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000); }/*from w w w. j a v a 2 s .co m*/ final Log log = LogFactory.getLog(Veracity.class); File homeDir = new File(System.getProperty("user.home")); File currentDir = new File(System.getProperty("user.dir")); List<File> configLocations = new LinkedList<File>(); configLocations.addAll(Arrays.asList(new File[] { new File("/etc/veracity.config"), new File(homeDir, ".veracity.config"), new File(currentDir, "config.xml") })); String customConfigFileProperty = System.getProperty("veracity.configFile"); if (customConfigFileProperty != null) { configLocations.clear(); configLocations.add(new File(customConfigFileProperty)); } File configFile = null; Iterator<File> i = configLocations.iterator(); while ((configFile == null || !configFile.exists()) && i.hasNext()) { configFile = i.next(); } LaunchParameters parameters; if (!configFile.exists()) { if (log.isDebugEnabled()) { log.debug("Creating default config file at " + configFile.getAbsolutePath()); } parameters = new LaunchParameters(); parameters.save(configFile); } else { if (log.isDebugEnabled()) { log.debug("Loading parameters from config file at " + configFile.getAbsolutePath()); } parameters = LaunchParameters.load(configFile); } parameters.readSystemProperties(); new Veracity(parameters); }
From source file:at.gv.egiz.pdfas.cli.test.SignaturProfileTest.java
public static void main(String[] args) { String user_home = System.getProperty("user.home"); String pdfas_dir = user_home + File.separator + ".pdfas"; PdfAs pdfas = PdfAsFactory.createPdfAs(new File(pdfas_dir)); try {/*w w w .j a v a 2 s . c o m*/ Configuration config = pdfas.getConfiguration(); ISettings settings = (ISettings) config; List<String> signatureProfiles = new ArrayList<String>(); List<String> signaturePDFAProfiles = new ArrayList<String>(); Iterator<String> itKeys = settings.getFirstLevelKeys("sig_obj.types.").iterator(); while (itKeys.hasNext()) { String key = itKeys.next(); String profile = key.substring("sig_obj.types.".length()); System.out.println("[" + profile + "]: " + settings.getValue(key)); if (settings.getValue(key).equals("on")) { signatureProfiles.add(profile); if (profile.contains("PDFA")) { signaturePDFAProfiles.add(profile); } } } byte[] input = IOUtils.toByteArray(new FileInputStream(sourcePDF)); IPlainSigner signer = new PAdESSignerKeystore(KS_FILE, KS_ALIAS, KS_PASS, KS_KEY_PASS, KS_TYPE); Iterator<String> itProfiles = signatureProfiles.iterator(); while (itProfiles.hasNext()) { String profile = itProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(input); FileOutputStream fos = new FileOutputStream(targetFolder + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } byte[] inputPDFA = IOUtils.toByteArray(new FileInputStream(sourcePDFA)); Iterator<String> itPDFAProfiles = signaturePDFAProfiles.iterator(); while (itPDFAProfiles.hasNext()) { String profile = itPDFAProfiles.next(); System.out.println("Testing " + profile); DataSource source = new ByteArrayDataSource(inputPDFA); FileOutputStream fos = new FileOutputStream(targetFolder + "PDFA_" + profile + ".pdf"); SignParameter signParameter = PdfAsFactory.createSignParameter(config, source, fos); signParameter.setPlainSigner(signer); signParameter.setSignatureProfileId(profile); SignResult result = pdfas.sign(signParameter); fos.close(); } } catch (Throwable e) { e.printStackTrace(); } }
From source file:ClassFileUtilities.java
/** * Program that computes the dependencies between the Batik jars. * <p>//from www . ja v a 2s. co m * Run this from the main Batik distribution directory, after building * the jars. For every jar file in the batik-xxx/ build directory, * it will determine which other jar files it directly depends on. * The output is lines of the form: * </p> * <pre> <i>number</i>,<i>from</i>,<i>to</i></pre> * <p> * where mean that the <i>from</i> jar has <i>number</i> class files * that depend on class files in the <i>to</i> jar. * </p> */ public static void main(String[] args) { boolean showFiles = false; if (args.length == 1 && args[0].equals("-f")) { showFiles = true; } else if (args.length != 0) { System.err.println("usage: ClassFileUtilities [-f]"); System.err.println(); System.err.println(" -f list files that cause each jar file dependency"); System.exit(1); } File cwd = new File("."); File buildDir = null; String[] cwdFiles = cwd.list(); for (int i = 0; i < cwdFiles.length; i++) { if (cwdFiles[i].startsWith("batik-")) { buildDir = new File(cwdFiles[i]); if (!buildDir.isDirectory()) { buildDir = null; } else { break; } } } if (buildDir == null || !buildDir.isDirectory()) { System.out.println("Directory 'batik-xxx' not found in current directory!"); return; } try { Map cs = new HashMap(); Map js = new HashMap(); collectJars(buildDir, js, cs); Set classpath = new HashSet(); Iterator i = js.values().iterator(); while (i.hasNext()) { classpath.add(((Jar) i.next()).jarFile); } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); // System.out.println(fromFile.name); Set result = getClassDependencies(fromFile.getInputStream(), classpath, false); Iterator j = result.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) cs.get(j.next()); if (fromFile != toFile && toFile != null) { fromFile.deps.add(toFile); } } } i = cs.values().iterator(); while (i.hasNext()) { ClassFile fromFile = (ClassFile) i.next(); Iterator j = fromFile.deps.iterator(); while (j.hasNext()) { ClassFile toFile = (ClassFile) j.next(); Jar fromJar = fromFile.jar; Jar toJar = toFile.jar; if (fromFile.name.equals(toFile.name) || toJar == fromJar || fromJar.files.contains(toFile.name)) { continue; } Integer n = (Integer) fromJar.deps.get(toJar); if (n == null) { fromJar.deps.put(toJar, new Integer(1)); } else { fromJar.deps.put(toJar, new Integer(n.intValue() + 1)); } } } List triples = new ArrayList(10); i = js.values().iterator(); while (i.hasNext()) { Jar fromJar = (Jar) i.next(); Iterator j = fromJar.deps.keySet().iterator(); while (j.hasNext()) { Jar toJar = (Jar) j.next(); Triple t = new Triple(); t.from = fromJar; t.to = toJar; t.count = ((Integer) fromJar.deps.get(toJar)).intValue(); triples.add(t); } } Collections.sort(triples); i = triples.iterator(); while (i.hasNext()) { Triple t = (Triple) i.next(); System.out.println(t.count + "," + t.from.name + "," + t.to.name); if (showFiles) { Iterator j = t.from.files.iterator(); while (j.hasNext()) { ClassFile fromFile = (ClassFile) j.next(); Iterator k = fromFile.deps.iterator(); while (k.hasNext()) { ClassFile toFile = (ClassFile) k.next(); if (toFile.jar == t.to && !t.from.files.contains(toFile.name)) { System.out.println("\t" + fromFile.name + " --> " + toFile.name); } } } } } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java
/** * @param args// w w w . ja va 2s . co m */ @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER"); File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); // File dryrunDir = new File(projectDir, "dryrun"); File licenceFile = new File(licenceHeaderURL.toURI()); List<String> licenceLines = readLines(licenceFile); // for (int i = 0; i < licenceLines.size(); i++) { // String licenceLine = licenceLines.get(i); // licenceLines.set(i, " * " + licenceLine); // } // licenceLines.add(0, "/**"); // licenceLines.add(" */"); List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir, new String[] { "java" }, true); for (File javaFile : javaFiles) { if (isValidPackage(javaFile)) { List<String> javaFileLines = readLines(javaFile); if (!javaFileLines.isEmpty()) { boolean modified = false; String firstLineTrim = javaFileLines.get(0).trim(); if (firstLineTrim.startsWith("package")) { modified = true; javaFileLines.addAll(0, licenceLines); } else if (firstLineTrim.startsWith("/**")) { int indexOfEndCommentLine = -1; loop2: for (int i = 0; i < javaFileLines.size(); i++) { String javaFileLine = javaFileLines.get(i); if (javaFileLine.indexOf("*/") != -1) { indexOfEndCommentLine = i; break loop2; } } if (indexOfEndCommentLine != -1) { modified = true; int i = 0; loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) { it.next(); if (i <= indexOfEndCommentLine) { it.remove(); } else { break loop3; } i++; } javaFileLines.addAll(0, licenceLines); } else { throw new RuntimeException( "Missing end comment for file " + javaFile.getAbsolutePath()); } } if (modified) { // String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length()); // File outputFile = new File(dryrunDir, outputFilePath); // outputFile.getParentFile().mkdirs(); // System.out.println(outputFile.getPath()); // FileOutputStream fos = new FileOutputStream(outputFile); System.out.println(javaFile.getPath()); FileOutputStream fos = new FileOutputStream(javaFile); IOUtils.writeLines(javaFileLines, "\n", fos); IOUtils.closeQuietly(fos); } } } } }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyTuple.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*ww w.j av a 2 s.c o m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<Tuple, FloatWritable>> pairs = SequenceFileUtils.readDirectory(new Path(inputPath)); List<PairOfWritables<Tuple, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<Tuple, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<Tuple, FloatWritable> p : pairs) { Tuple bigram = p.getLeftElement(); if (bigram.get(0).equals("light")) { list1.add(p); } if (bigram.get(0).equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter1.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<Tuple, FloatWritable>>() { @SuppressWarnings("unchecked") public int compare(PairOfWritables<Tuple, FloatWritable> e1, PairOfWritables<Tuple, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<Tuple, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<Tuple, FloatWritable> p = iter2.next(); Tuple bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:com.netscape.cms.servlet.test.ConfigurationTest.java
public static void main(String args[]) throws Exception { String host = null;//w w w.j a v a 2s . c om String port = null; String cstype = null; String token_pwd = null; String db_dir = "./"; String protocol = "https"; String pin = null; String extCertFile = null; int testnum = 1; // parse command line arguments Options options = new Options(); options.addOption("t", true, "Subsystem type"); options.addOption("h", true, "Hostname of the CS subsystem"); options.addOption("p", true, "Port of the CS subsystem"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("s", true, "preop pin"); options.addOption("e", true, "File for externally signed signing cert"); options.addOption("x", true, "Test number"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("t")) { cstype = cmd.getOptionValue("t"); } else { System.err.println("Error: no subsystem type provided."); usage(options); } if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { System.err.println("Error: no token password provided"); usage(options); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { pin = cmd.getOptionValue("s"); } if (cmd.hasOption("e")) { extCertFile = cmd.getOptionValue("e"); } if (cmd.hasOption("x")) { testnum = Integer.parseInt(cmd.getOptionValue("x")); } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { System.out.println("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // log into token CryptoManager manager = null; CryptoToken token = null; try { manager = CryptoManager.getInstance(); token = manager.getInternalKeyStorageToken(); Password password = new Password(token_pwd.toCharArray()); try { token.login(password); } catch (Exception e) { System.out.println("login Exception: " + e.toString()); if (!token.isLoggedIn()) { token.initPassword(password, password); } } } catch (Exception e) { System.out.println("Exception in logging into token:" + e.toString()); } SystemConfigClient client = null; try { ClientConfig config = new ClientConfig(); config.setServerURL(protocol + "://" + host + ":" + port); client = new SystemConfigClient(new PKIClient(config, null), cstype); } catch (URISyntaxException e1) { e1.printStackTrace(); System.exit(1); } ConfigurationRequest data = null; switch (testnum) { case 1: data = constructCAData(host, port, pin, db_dir, token_pwd, token); break; case 2: data = constructCloneCAData(host, port, pin, db_dir, token_pwd, token); break; case 3: data = constructKRAData(host, port, pin, db_dir, token_pwd, token); break; case 4: data = constructOCSPData(host, port, pin, db_dir, token_pwd, token); break; case 5: data = constructTKSData(host, port, pin, db_dir, token_pwd, token); break; case 6: data = constructSubCAData(host, port, pin, db_dir, token_pwd, token); break; case 7: data = constructExternalCADataPart1(host, port, pin, db_dir, token_pwd, token); break; case 8: data = constructExternalCADataPart2(host, port, pin, db_dir, token_pwd, token, extCertFile); break; default: System.out.println("Invalid test"); System.exit(1); } ConfigurationResponse response = client.configure(data); System.out.println("adminCert: " + response.getAdminCert().getCert()); List<SystemCertData> certs = response.getSystemCerts(); Iterator<SystemCertData> iterator = certs.iterator(); while (iterator.hasNext()) { SystemCertData cdata = iterator.next(); System.out.println("tag: " + cdata.getTag()); System.out.println("cert: " + cdata.getCert()); System.out.println("request: " + cdata.getRequest()); } }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequency.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*w w w.j a v a 2s . co m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequency.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<PairOfStrings, FloatWritable>> pairs = SequenceFileUtils .readDirectory(new Path(inputPath)); List<PairOfWritables<PairOfStrings, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<PairOfStrings, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<PairOfStrings, FloatWritable> p : pairs) { PairOfStrings bigram = p.getLeftElement(); if (bigram.getLeftElement().equals("light")) { list1.add(p); } if (bigram.getLeftElement().equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter1.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter2.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }