List of usage examples for java.lang StringBuilder length
int length();
From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java
public static void main(String[] args) { Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }//from w ww . j av a 2 s . c o m commandList.append(cmd.toString()); } options.addOption(Option // .builder() // .longOpt("base-url") // .desc("Sets the base URL of the web service") // .hasArg() // .build()); options.addOption(Option // .builder("u") // .longOpt("username") // .desc("The username for authentication (usually mail address)") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("p") // .longOpt("password") // .desc("The password for authentication") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("c") // .longOpt("command") // .desc(String.format("The command, which should be sent to the device (%s)", commandList)) // .hasArg() // .build()); options.addOption(Option // .builder("q") // .longOpt("query-status") // .desc("Queries the status of the device") // .build()); options.addOption(Option // .builder() // .longOpt("query-calendar") // .desc("Queries the calendar of the device") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } String baseUrl = cmds.getOptionValue("base-url"); String username = cmds.getOptionValue('u'); String password = cmds.getOptionValue('p'); String commandStr = cmds.getOptionValue('c'); boolean doQueryState = cmds.hasOption('q'); boolean doQueryCalendar = cmds.hasOption("query-calendar"); DeviceCommand command = null; if (commandStr != null) { try { command = DeviceCommand.valueOf(commandStr.toUpperCase()); } catch (IllegalArgumentException ex) { System.err.println("Unknown command: " + commandStr); System.exit(1); } } IndegoController controller = new IndegoController(baseUrl, username, password); try { System.out.println("Connecting to device"); controller.connect(); System.out.println(String.format("...Connection established. Device serial number is: %s", controller.getDeviceSerialNumber())); if (command != null) { System.out.println(String.format("Sending command (%s)...", command)); controller.sendCommand(command); System.out.println("...Command sent successfully!"); } if (doQueryState) { System.out.println("Querying device state"); DeviceStateInformation state = controller.getState(); printState(System.out, state); } if (doQueryCalendar) { System.out.println("Querying device calendar"); DeviceCalendar calendar = controller.getCalendar(); printCalendar(System.out, calendar); } } catch (IndegoException ex) { ex.printStackTrace(); System.exit(2); } finally { controller.disconnect(); } }
From source file:com.heliosapm.opentsdb.client.boot.JavaAgentInstaller.java
public static void main(final String[] args) { if (args.length == 0) { loge("Usage: java com.heliosapm.opentsdb.client.boot.JavaAgentInstaller \n\t<PID | Name to match> \n\t[-list | -listjson] \n\t[-p k=v] \n\t[-config URL|File]"); }// w w w .j av a2s. c om final long pid; if (isPid(args[0])) { pid = Long.parseLong(args[0].trim()); } else if ("-list".equalsIgnoreCase(args[0])) { printJVMs(myId); return; } else if ("-listjson".equalsIgnoreCase(args[0])) { printJVMsInJSON(myId); return; } else { pid = findPid(args[0]); } if (pid < 1) { System.exit(-1); } log("Installing JavaAgent to PID: %s from JAR: %s", pid, JavaAgentInstaller.class.getProtectionDomain().getCodeSource().getLocation()); VirtualMachine vm = null; try { final String loc = new File( JavaAgentInstaller.class.getProtectionDomain().getCodeSource().getLocation().getFile()) .getAbsolutePath(); vm = VirtualMachine.attach("" + pid); log("Connected to process %s, loading Agent from %s", vm.id(), loc); if (args.length > 1) { StringBuilder b = new StringBuilder(); for (int i = 1; i < args.length; i++) { b.append(args[i]).append("|~"); if ("-config".equalsIgnoreCase(args[i])) { i++; final URL url = URLHelper.toURL(args[i]); b.append(url).append("|~"); } } b.deleteCharAt(b.length() - 1); b.deleteCharAt(b.length() - 1); log("Loading with options [%s]", b); vm.loadAgent(loc, b.toString()); } else { log("Loading with no options"); vm.loadAgent(loc); } log("Agent loaded to process %s", vm.id()); System.exit((int) pid); } catch (Exception ex) { loge("Failed to attach to process %s. Stack trace follows...", pid); ex.printStackTrace(System.err); } finally { if (vm != null) { try { vm.detach(); log("Detached from process %s", pid); } catch (Exception ex) { } } } }
From source file:com.mijecu25.sqlplus.SQLPlus.java
public static void main(String[] args) throws IOException { // Create and load the properties from the application properties file Properties properties = new Properties(); properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE)); SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); // Check if the user is using a valid console (i.e. not from Eclipse) if (System.console() == null) { // The Console object for the JVM could not be found. Alert the user SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running " + SQLPlus.PROGRAM_NAME + "from the command line"); System.out.println(/*from ww w.jav a2 s . co m*/ Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. " + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line."); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME)); return; } // UI intro System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME + "! This program has a DSL to add alerts to various SQL DML events."); System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line."); System.out.println(); // Get the version System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION)); System.out.println(); // Read the license file BufferedReader bufferedReader; bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE)); // Read a line String line = bufferedReader.readLine(); // While the line is not null while (line != null) { System.out.println(line); // Read a new lines line = bufferedReader.readLine(); } // Close the buffer bufferedReader.close(); System.out.println(); // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions // from the user SQLPlus.console = new ConsoleReader(); SQLPlus.console.setHandleUserInterrupt(true); try { // Get credentials from the user SQLPlus.logger.info("Create SQLPlusConnection"); SQLPlus.createSQLPlusConnection(); } catch (NullPointerException | SQLException | IllegalArgumentException e) { // NPE: This exception can occur if the user is running the program where the JVM Console // object cannot be found. // SQLE: TODO should I add here the error code? // This exception can occur when trying to establish a connection // IAE: This exception can occur when trying to establish a connection SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName())); System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); return; } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); return; } System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND); System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application "); try { // Execute the input scanner while (true) { // Get a line from the user until the hit enter (carriage return, line feed/ new line). System.out.print(SQLPlus.PROMPT); try { line = SQLPlus.console.readLine().trim(); } catch (NullPointerException npe) { // TODO test this behavior // If this exception is catch, it is very likely that the user entered the end of line command. // This means that the program should quit. SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that" + "the user entered the end of line command and they want to quit."); SQLPlus.exitSQLPlus(); return; } // If the user did not enter anything if (line.isEmpty()) { // Continue to the next iteration continue; } if (line.equals(".")) { line = "use courses;"; } if (line.equals("-")) { line = "select created_at from classes;"; } if (line.equals("--")) { line = "select name, year from classes;"; } if (line.equals("*")) { line = "select * from classes;"; } if (line.equals("x")) { line = "select name from classes, classes;"; } if (line.equals("e")) { line = "select * feom classes;"; } // Logic to quit if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) { SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME); SQLPlus.exitSQLPlus(); break; } // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each // time jline reads a new line, the variable is empty StringBuilder query = new StringBuilder(); query.append(line); // While the user does not finish the command with the SQLPlus.END_OF_COMMAND while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) { // Print the wait for command prompt and get the next line for the user System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND); query.append(" "); line = StringUtils.stripEnd(SQLPlus.console.readLine(), null); query.append(line); } SQLPlus.logger.info("Raw input from the user: " + query); try { Statement statement; try { // Execute the antlr code to parse the user input SQLPlus.logger.info("Will parse the user input to determine what to execute"); ANTLRStringStream input = new ANTLRStringStream(query.toString()); SQLPlusLex lexer = new SQLPlusLex(input); CommonTokenStream tokens = new CommonTokenStream(lexer); SQLPlusParser parser = new SQLPlusParser(tokens); statement = parser.sqlplus(); } catch (RecognitionException re) { // TODO move this to somehwere else // String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual" // + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase() // + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax"; // SQLPlus.logger.warn(message); // System.out.println(message); statement = new StatementDefault(); } statement.setStatement(query.toString()); SQLPlus.sqlPlusConnection.execute(statement); } catch (UnsupportedOperationException uoe) { // This exception can occur when the user entered a command allowed by the parsers, but not currently // supported by SQLPlus. This can occur because the parser is written in such a way that supports // the addition of features. SQLPlus.logger.warn(Messages.WARNING + uoe); System.out.println( Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " " + Messages.CHECK_LOG_FILES); SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported."); } } } catch (IllegalArgumentException iae) { // This exception can occur when a command is executed but it had illegal arguments. Most likely // it is a programmer's error and should be addressed by the developer. SQLPlus.logger .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName())); SQLPlus.exitSQLPlus(); SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME)); } catch (UserInterruptException uie) { SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction."); SQLPlus.exitSQLPlus(); } }
From source file:fi.iki.elonen.SimpleWebServer.java
/** * Starts as a standalone file server and waits for Enter. *//* w w w.j a va2s . c o m*/ public static void main(String[] args) { // Defaults int port = 8080; String host = null; // bind to all interfaces by default List<File> rootDirs = new ArrayList<File>(); boolean quiet = false; String cors = null; Map<String, String> options = new HashMap<String, String>(); // Parse command-line, with short and long versions of the options. for (int i = 0; i < args.length; ++i) { if ("-h".equalsIgnoreCase(args[i]) || "--host".equalsIgnoreCase(args[i])) { host = args[i + 1]; } else if ("-p".equalsIgnoreCase(args[i]) || "--port".equalsIgnoreCase(args[i])) { if (args[i + 1].equals("public")) { port = PUBLIC; } else if (args[i + 1].equals("private")) { port = PRIVATE; } else { port = Integer.parseInt(args[i + 1]); } } else if ("-q".equalsIgnoreCase(args[i]) || "--quiet".equalsIgnoreCase(args[i])) { quiet = true; } else if ("-d".equalsIgnoreCase(args[i]) || "--dir".equalsIgnoreCase(args[i])) { rootDirs.add(new File(args[i + 1]).getAbsoluteFile()); } else if (args[i].startsWith("--cors")) { cors = "*"; int equalIdx = args[i].indexOf('='); if (equalIdx > 0) { cors = args[i].substring(equalIdx + 1); } } else if ("--licence".equalsIgnoreCase(args[i])) { System.out.println(SimpleWebServer.LICENCE + "\n"); } else if (args[i].startsWith("-X:")) { int dot = args[i].indexOf('='); if (dot > 0) { String name = args[i].substring(0, dot); String value = args[i].substring(dot + 1, args[i].length()); options.put(name, value); } } } if (rootDirs.isEmpty()) { rootDirs.add(new File(".").getAbsoluteFile()); } options.put("host", host); options.put("port", "" + port); options.put("quiet", String.valueOf(quiet)); StringBuilder sb = new StringBuilder(); for (File dir : rootDirs) { if (sb.length() > 0) { sb.append(":"); } try { sb.append(dir.getCanonicalPath()); } catch (IOException ignored) { } } options.put("home", sb.toString()); ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class); for (WebServerPluginInfo info : serviceLoader) { String[] mimeTypes = info.getMimeTypes(); for (String mime : mimeTypes) { String[] indexFiles = info.getIndexFilesForMimeType(mime); if (!quiet) { System.out.print("# Found plugin for Mime type: \"" + mime + "\""); if (indexFiles != null) { System.out.print(" (serving index files: "); for (String indexFile : indexFiles) { System.out.print(indexFile + " "); } } System.out.println(")."); } registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options); } } ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet, cors)); }
From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); options.addOption(OptionBuilder.withLongOpt("report").withDescription( "Prints a report at the end of the execution that can be parsed for reporting to other tools") .create("report")); final String cmdLineSyntax = RestLiResourceModelCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*ww w.j a v a 2 s.c o m*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(255); return; } final StringBuilder allSummaries = new StringBuilder(); final RestLiResourceModelCompatibilityChecker checker = new RestLiResourceModelCompatibilityChecker(); for (int i = 1; i < targets.length; i += 2) { checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH)); String prevTarget = targets[i - 1]; String currTarget = targets[i]; checker.check(prevTarget, currTarget, compat); } allSummaries.append(checker.getInfoMap().createSummary()); if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } if (cmd.hasOption("report")) { System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport()); System.exit(0); } System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1); }
From source file:com.ctriposs.rest4j.tools.idlcheck.Rest4JResourceModelCompatibilityChecker.java
@SuppressWarnings({ "static" }) public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); final String cmdLineSyntax = Rest4JResourceModelCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {//w ww .j a va 2 s.com cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; } final StringBuilder allSummaries = new StringBuilder(); boolean result = true; for (int i = 1; i < targets.length; i += 2) { final Rest4JResourceModelCompatibilityChecker checker = new Rest4JResourceModelCompatibilityChecker(); checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH)); String prevTarget = targets[i - 1]; String currTarget = targets[i]; result &= checker.check(prevTarget, currTarget, compat); allSummaries.append(checker.getInfoMap().createSummary(prevTarget, currTarget)); } if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } System.exit(result ? 0 : 1); }
From source file:fr.eo.util.dumper.Dumper.java
/** * @param args/*from w w w . j a v a 2 s .c o m*/ */ public static void main(String[] args) { String appName = args[0]; System.out.println("Starting dumper ..."); Statement stmt = null; try { System.out.println("Getting database connection ..."); Connection conn = getJtdsConnection(); List<RequestDefinitionBean> requests = RequestDefinitionParser.getRequests(appName); assetFolder = RequestDefinitionParser.getAppBaseDir(appName) + "assets/"; for (RequestDefinitionBean request : requests) { int currentFileSize = 0, cpt = 1; stmt = conn.createStatement(); System.out.println("Dumping " + request.name + "..."); ResultSet rs = stmt.executeQuery(request.sql); BufferedWriter bw = getWriter(request.name, cpt); bw.append(COPYRIGHTS); currentFileSize += COPYRIGHTS.length(); bw.append("--" + request.name + "\n"); while (rs.next()) { StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO "); sb.append(request.table).append(" VALUES ("); int pos = 0; for (String fieldName : request.fields) { String str = getFieldValue(request, pos, rs, fieldName); sb.append(str); pos++; if (pos < request.fields.size()) { sb.append(","); } } sb.append(");\n"); currentFileSize += sb.length(); bw.append(sb.toString()); bw.flush(); if (currentFileSize > MAX_FILE_SIZE) { bw.close(); bw = getWriter(request.name, ++cpt); bw.append(COPYRIGHTS); bw.append("--" + request.name + "\n"); currentFileSize = COPYRIGHTS.length(); } } bw.flush(); bw.close(); } System.out.println("done."); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } DumpFilesDescriptor descriptor = new DumpFilesDescriptor(); descriptor.lineNumbers = getDumpLinesNumber(); descriptor.dumpFileNames = dumpFileNames; writeDescriptorFile(descriptor); System.out.println("nb :" + descriptor.lineNumbers); }
From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java
public static void main(String[] args) { final Options options = new Options(); options.addOption("h", "help", false, "Print help"); options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg() .withDescription("Compatibility level " + listCompatLevelOptions()).create('c')); final String cmdLineSyntax = Rest4JSnapshotCompatibilityChecker.class.getCanonicalName() + " [pairs of <prevRestspecPath currRestspecPath>]"; final CommandLineParser parser = new PosixParser(); final CommandLine cmd; try {/*from ww w . jav a2 s . c o m*/ cmd = parser.parse(options, args); } catch (ParseException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; // to suppress IDE warning } final String[] targets = cmd.getArgs(); if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); } final String compatValue; if (cmd.hasOption('c')) { compatValue = cmd.getOptionValue('c'); } else { compatValue = CompatibilityLevel.DEFAULT.name(); } final CompatibilityLevel compat; try { compat = CompatibilityLevel.valueOf(compatValue.toUpperCase()); } catch (IllegalArgumentException e) { new HelpFormatter().printHelp(cmdLineSyntax, options, true); System.exit(1); return; } final StringBuilder allSummaries = new StringBuilder(); boolean result = true; final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH); final Rest4JSnapshotCompatibilityChecker checker = new Rest4JSnapshotCompatibilityChecker(); checker.setResolverPath(resolverPath); for (int i = 1; i < targets.length; i += 2) { String prevTarget = targets[i - 1]; String currTarget = targets[i]; CompatibilityInfoMap infoMap = checker.check(prevTarget, currTarget, compat); result &= infoMap.isCompatible(compat); allSummaries.append(infoMap.createSummary(prevTarget, currTarget)); } if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) { System.out.println(allSummaries); } System.exit(result ? 0 : 1); }
From source file:marytts.tools.analysis.CopySynthesis.java
/** * @param args/*from w w w . j ava 2 s. c o m*/ */ public static void main(String[] args) throws Exception { String wavFilename = null; String labFilename = null; String pitchFilename = null; String textFilename = null; String locale = System.getProperty("locale"); if (locale == null) { throw new IllegalArgumentException("No locale given (-Dlocale=...)"); } for (String arg : args) { if (arg.endsWith(".txt")) textFilename = arg; else if (arg.endsWith(".wav")) wavFilename = arg; else if (arg.endsWith(".ptc")) pitchFilename = arg; else if (arg.endsWith(".lab")) labFilename = arg; else throw new IllegalArgumentException("Don't know how to treat argument: " + arg); } // The intonation contour double[] contour = null; double frameShiftTime = -1; if (pitchFilename == null) { // need to create pitch contour from wav file if (wavFilename == null) { throw new IllegalArgumentException("Need either a pitch file or a wav file"); } AudioInputStream ais = AudioSystem.getAudioInputStream(new File(wavFilename)); AudioDoubleDataSource audio = new AudioDoubleDataSource(ais); PitchFileHeader params = new PitchFileHeader(); params.fs = (int) ais.getFormat().getSampleRate(); F0TrackerAutocorrelationHeuristic tracker = new F0TrackerAutocorrelationHeuristic(params); tracker.pitchAnalyze(audio); frameShiftTime = tracker.getSkipSizeInSeconds(); contour = tracker.getF0Contour(); } else { // have a pitch file -- ignore any wav file PitchReaderWriter f0rw = new PitchReaderWriter(pitchFilename); if (f0rw.contour == null) { throw new NullPointerException("Cannot read f0 contour from " + pitchFilename); } contour = f0rw.contour; frameShiftTime = f0rw.header.skipSizeInSeconds; } assert contour != null; assert frameShiftTime > 0; // The ALLOPHONES data and labels if (labFilename == null) { throw new IllegalArgumentException("No label file given"); } if (textFilename == null) { throw new IllegalArgumentException("No text file given"); } MaryTranscriptionAligner aligner = new MaryTranscriptionAligner(); aligner.SetEnsureInitialBoundary(false); String labels = MaryTranscriptionAligner.readLabelFile(aligner.getEntrySeparator(), aligner.getEnsureInitialBoundary(), labFilename); MaryHttpClient mary = new MaryHttpClient(); String text = FileUtils.readFileToString(new File(textFilename), "ASCII"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mary.process(text, "TEXT", "ALLOPHONES", locale, null, null, baos); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(bais); aligner.alignXmlTranscriptions(doc, labels); assert doc != null; // durations double[] endTimes = new LabelfileDoubleDataSource(new File(labFilename)).getAllData(); assert endTimes.length == labels.split(Pattern.quote(aligner.getEntrySeparator())).length; // Now add durations and f0 targets to document double prevEnd = 0; NodeIterator ni = MaryDomUtils.createNodeIterator(doc, MaryXML.PHONE, MaryXML.BOUNDARY); for (int i = 0; i < endTimes.length; i++) { Element e = (Element) ni.nextNode(); if (e == null) throw new IllegalStateException("More durations than elements -- this should not happen!"); double durInSeconds = endTimes[i] - prevEnd; int durInMillis = (int) (1000 * durInSeconds); if (e.getTagName().equals(MaryXML.PHONE)) { e.setAttribute("d", String.valueOf(durInMillis)); e.setAttribute("end", new Formatter(Locale.US).format("%.3f", endTimes[i]).toString()); // f0 targets at beginning, mid, and end of phone StringBuilder f0String = new StringBuilder(); double startF0 = getF0(contour, frameShiftTime, prevEnd); if (startF0 != 0 && !Double.isNaN(startF0)) { f0String.append("(0,").append((int) startF0).append(")"); } double midF0 = getF0(contour, frameShiftTime, prevEnd + 0.5 * durInSeconds); if (midF0 != 0 && !Double.isNaN(midF0)) { f0String.append("(50,").append((int) midF0).append(")"); } double endF0 = getF0(contour, frameShiftTime, endTimes[i]); if (endF0 != 0 && !Double.isNaN(endF0)) { f0String.append("(100,").append((int) endF0).append(")"); } if (f0String.length() > 0) { e.setAttribute("f0", f0String.toString()); } } else { // boundary e.setAttribute("duration", String.valueOf(durInMillis)); } prevEnd = endTimes[i]; } if (ni.nextNode() != null) { throw new IllegalStateException("More elements than durations -- this should not happen!"); } // TODO: add pitch values String acoustparams = DomUtils.document2String(doc); System.out.println("ACOUSTPARAMS:"); System.out.println(acoustparams); }
From source file:com.admc.jcreole.JCreole.java
/** * Run this method with no parameters to see syntax requirements and the * available parameters./* w w w.j a v a2 s. com*/ * * N.b. do not call this method from a persistent program, because it * may call System.exit! * <p> * Any long-running program should use the lower-level methods in this * class instead (or directly use CreoleParser and CreoleScanner * instances). * </p> <p> * This method executes with all JCreole privileges. * </p> <p> * This method sets up the following htmlExpander mappings (therefore you * can reference these in both Creole and boilerplate text).<p> * <ul> * <li>sys|*: mappings for Java system properties * <li>isoDateTime * <li>isoDate * <li>pageTitle: Value derived from the specified Creole file name. * </ul> * * @throws IOException for any I/O problem that makes it impossible to * satisfy the request. * @throws CreoleParseException * if can not generate output, or if the run generates 0 output. * If the problem is due to input formatting, in most cases you * will get a CreoleParseException, which is a RuntimException, and * CreoleParseException has getters for locations in the source * data (though they will be offset for \r's in the provided * Creole source, if any). */ public static void main(String[] sa) throws IOException { String bpResPath = null; String bpFsPath = null; String outPath = null; String inPath = null; boolean debugs = false; boolean troubleshoot = false; boolean noBp = false; int param = -1; try { while (++param < sa.length) { if (sa[param].equals("-d")) { debugs = true; continue; } if (sa[param].equals("-t")) { troubleshoot = true; continue; } if (sa[param].equals("-r") && param + 1 < sa.length) { if (bpFsPath != null || bpResPath != null || noBp) throw new IllegalArgumentException(); bpResPath = sa[++param]; continue; } if (sa[param].equals("-f") && param + 1 < sa.length) { if (bpResPath != null || bpFsPath != null || noBp) throw new IllegalArgumentException(); bpFsPath = sa[++param]; continue; } if (sa[param].equals("-")) { if (noBp || bpFsPath != null || bpResPath != null) throw new IllegalArgumentException(); noBp = true; continue; } if (sa[param].equals("-o") && param + 1 < sa.length) { if (outPath != null) throw new IllegalArgumentException(); outPath = sa[++param]; continue; } if (inPath != null) throw new IllegalArgumentException(); inPath = sa[param]; } if (inPath == null) throw new IllegalArgumentException(); } catch (IllegalArgumentException iae) { System.err.println(SYNTAX_MSG); System.exit(1); } if (!noBp && bpResPath == null && bpFsPath == null) bpResPath = DEFAULT_BP_RES_PATH; String rawBoilerPlate = null; if (bpResPath != null) { if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/') // Classloader lookups are ALWAYS relative to CLASSPATH roots, // and will abort if you specify a beginning "/". bpResPath = bpResPath.substring(1); InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath); if (iStream == null) throw new IOException("Boilerplate inaccessible: " + bpResPath); rawBoilerPlate = IOUtil.toString(iStream); } else if (bpFsPath != null) { rawBoilerPlate = IOUtil.toString(new File(bpFsPath)); } String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath; // Classloader lookups are ALWAYS relative to CLASSPATH roots, // and will abort if you specify a beginning "/". InputStream creoleStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(creoleResPath); File inFile = (creoleStream == null) ? new File(inPath) : null; JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate)); if (debugs) { jCreole.setInterWikiMapper(new InterWikiMapper() { // This InterWikiMapper is just for prototyping. // Use wiki name of "nil" to force lookup failure for path. // Use wiki page of "nil" to force lookup failure for label. public String toPath(String wikiName, String wikiPage) { if (wikiName != null && wikiName.equals("nil")) return null; return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}'; } public String toLabel(String wikiName, String wikiPage) { if (wikiPage == null) throw new RuntimeException("Null page name sent to InterWikiMapper"); if (wikiPage.equals("nil")) return null; return "{LABEL for: " + wikiName + '|' + wikiPage + '}'; } }); Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR); creoleExpander.put("testMacro", "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n"); jCreole.setCreoleExpander(creoleExpander); } jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class)); Expander exp = jCreole.getHtmlExpander(); Date now = new Date(); exp.putAll("sys", System.getProperties(), false); exp.put("isoDateTime", isoDateTimeFormatter.format(now), false); exp.put("isoDate", isoDateFormatter.format(now), false); exp.put("pageTitle", (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "") : inFile.getName().replaceFirst("[.][^.]*$", "")); if (troubleshoot) { // We don't write any HMTL output here. // Goal is just to output diagnostics. StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile) : IOUtil.toStringBuilder(creoleStream); int newlineCount = 0; int lastOffset = -1; int offset = builder.indexOf("\n"); for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) { lastOffset = offset; newlineCount++; } // Accommodate input files with no terminating newline: if (builder.length() > lastOffset + 1) newlineCount++; System.out.println("Input lines: " + newlineCount); Exception lastException = null; while (true) { try { jCreole.parseCreole(builder); break; } catch (Exception e) { lastException = e; } if (builder.charAt(builder.length() - 1) == '\n') builder.setLength(builder.length() - 1); offset = builder.lastIndexOf("\n"); if (offset < 1) break; newlineCount--; builder.setLength(builder.lastIndexOf("\n")); } System.out.println((lastException == null) ? "Input validates" : String.format("Error around input line %d: %s", newlineCount, lastException.getMessage())); return; } String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile) : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream)); String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR); if (outPath == null) { System.out.print(html); } else { FileUtils.writeStringToFile(new File(outPath), html, "UTF-8"); } }