List of usage examples for java.lang StringBuilder StringBuilder
@HotSpotIntrinsicCandidate
public StringBuilder()
From source file:microbiosima.SelectiveMicrobiosima.java
/** * @param args//from w ww . j a v a 2 s . co m * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { int populationSize = 500;//Integer.parseInt(parameters[1]); int microSize = 1000;//Integer.parseInt(parameters[2]); int numberOfSpecies = 150;//Integer.parseInt(parameters[3]); int numberOfGeneration = 10000; int Ngene = 10; int numberOfObservation = 100; int numberOfReplication = 10; double Ngenepm = 5; double pctEnv = 0; double pctPool = 0; double msCoeff = 1; double hsCoeff = 1; boolean HMS_or_TMS = true; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe" + " [default: 500 1000 150 10000 10 5]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + " msCoeff Parameter related to microbe selection strength\n" + " hsCoeff Parameter related to host selection strength\n" + " HMS_or_TMS String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 5) { System.out.println( "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); msCoeff = Double.parseDouble(pct_config[2]); hsCoeff = Double.parseDouble(pct_config[3]); if (pct_config[4].equals("HMS")) HMS_or_TMS = true; if (pct_config[4].equals("TMS")) HMS_or_TMS = false; if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } if (msCoeff < 1) { System.out.println( "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff=" + msCoeff + ")! EXIT"); System.exit(3); } if (hsCoeff < 1) { System.out.println( "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff=" + hsCoeff + ")! EXIT"); System.exit(3); } if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) { System.out.println( "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS=" + pct_config[4] + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); Ngene = Integer.parseInt(configs[4]); Ngenepm = Double.parseDouble(configs[5]); if (Ngenepm > Ngene) { System.out.println( "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT"); System.exit(3); } } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication) .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ") .append(Ngenepm).append("\n"); System.out.println(sb.toString()); double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } int[] fitnessToHost = new int[Ngene]; int[] fitnessToMicrobe = new int[Ngene]; for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix; if (HMS_or_TMS) sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt"; else sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); PrintWriter file7 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix))); PrintWriter file8 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix))); PrintWriter file9 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix))); PrintWriter file10 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix))); PrintWriter file11 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix))); PrintWriter file12 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix))); for (int i = 0; i < Ngene; i++) { fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1; fitnessToHost[i] = MathUtil.getNextInt(2) - 1; } MathUtil.setSeed(rep % numberOfReplication); SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm, msCoeff, fitnessToHost, fitnessToMicrobe); MathUtil.setSeed(); SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize, pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { //file1.print(population.gammaDiversity(false)); //file2.print(population.alphaDiversity(false)); //file1.print("\t"); //file2.print("\t"); file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); //file3.print(population.betaDiversity(true)); //file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); file7.print(population.averageHostFitness()); file7.print("\t"); file7.println(population.varianceHostFitness()); file8.println(population.cosOfMH()); file9.println(population.printOutHFitness()); file10.println(population.printOutMFitness()); file11.println(population.printBacteriaContents()); } population.getNextGen(); } for (SelectiveIndividual host : population.getIndividuals()) { file12.println(host.printBacteriaContents()); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); file7.close(); file8.close(); file9.close(); file10.close(); file11.close(); file12.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.eclipse.swt.snippets.Snippet373.java
@SuppressWarnings("restriction") public static void main(String[] args) { System.setProperty("swt.autoScale", "quarter"); Display display = new Display(); final Image eclipse = new Image(display, filenameProvider); final Image eclipseToolBar1 = new Image(display, filenameProvider); final Image eclipseToolBar2 = new Image(display, filenameProvider); final Image eclipseTableHeader = new Image(display, filenameProvider); final Image eclipseTableItem = new Image(display, filenameProvider); final Image eclipseTree1 = new Image(display, filenameProvider); final Image eclipseTree2 = new Image(display, filenameProvider); final Image eclipseCTab1 = new Image(display, filenameProvider); final Image eclipseCTab2 = new Image(display, filenameProvider); Shell shell = new Shell(display); shell.setText("Snippet 373"); shell.setImage(eclipse);/*from w w w.j a v a 2s . c o m*/ shell.setText("DynamicDPI @ " + DPIUtil.getDeviceZoom()); shell.setLayout(new RowLayout(SWT.VERTICAL)); shell.setLocation(100, 100); shell.setSize(500, 600); shell.addListener(SWT.ZoomChanged, new Listener() { @Override public void handleEvent(Event e) { if (display.getPrimaryMonitor().equals(shell.getMonitor())) { MessageBox box = new MessageBox(shell, SWT.PRIMARY_MODAL | SWT.OK | SWT.CANCEL); box.setText(shell.getText()); box.setMessage("DPI changed, do you want to exit & restart ?"); e.doit = (box.open() == SWT.OK); if (e.doit) { shell.close(); System.out.println("Program exit."); } } } }); // Menu Menu bar = new Menu(shell, SWT.BAR); shell.setMenuBar(bar); MenuItem fileItem = new MenuItem(bar, SWT.CASCADE); fileItem.setText("&File"); fileItem.setImage(eclipse); Menu submenu = new Menu(shell, SWT.DROP_DOWN); fileItem.setMenu(submenu); MenuItem subItem = new MenuItem(submenu, SWT.PUSH); subItem.addListener(SWT.Selection, e -> System.out.println("Select All")); subItem.setText("Select &All\tCtrl+A"); subItem.setAccelerator(SWT.MOD1 + 'A'); subItem.setImage(eclipse); // CTabFolder CTabFolder folder = new CTabFolder(shell, SWT.BORDER); for (int i = 0; i < 2; i++) { CTabItem cTabItem = new CTabItem(folder, i % 2 == 0 ? SWT.CLOSE : SWT.NONE); cTabItem.setText("Item " + i); Text textMsg = new Text(folder, SWT.MULTI); textMsg.setText("Content for Item " + i); cTabItem.setControl(textMsg); cTabItem.setImage((i % 2 == 1) ? eclipseCTab1 : eclipseCTab2); } // PerMonitorV2 setting // Label label = new Label (shell, SWT.BORDER); // label.setText("PerMonitorV2 value before:after:Error"); // Text text = new Text(shell, SWT.BORDER); // text.setText(DPIUtil.BEFORE + ":" + DPIUtil.AFTER + ":" + DPIUtil.RESULT); // Composite for Label, Button, Tool-bar Composite composite = new Composite(shell, SWT.BORDER); composite.setLayout(new RowLayout(SWT.HORIZONTAL)); // Label with Image Label label1 = new Label(composite, SWT.BORDER); label1.setImage(eclipse); // Label with text only Label label2 = new Label(composite, SWT.BORDER); label2.setText("No Image"); // Button with text + Old Image Constructor Button oldButton1 = new Button(composite, SWT.PUSH); oldButton1.setText("Old Img"); oldButton1.setImage(new Image(display, IMAGE_PATH_100)); // Button with Old Image Constructor // Button oldButton2 = new Button(composite, SWT.PUSH); // oldButton2.setImage(new Image(display, filenameProvider.getImagePath(100))); // Button with Image Button createDialog = new Button(composite, SWT.PUSH); createDialog.setText("Child Dialog"); createDialog.setImage(eclipse); createDialog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.RESIZE); dialog.setText("Child Dialog"); RowLayout rowLayout = new RowLayout(SWT.VERTICAL); dialog.setLayout(rowLayout); Label label = new Label(dialog, SWT.BORDER); label.setImage(eclipse); Point location = shell.getLocation(); dialog.setLocation(location.x + 250, location.y + 50); dialog.pack(); dialog.open(); } }); // Toolbar with Image ToolBar toolBar = new ToolBar(composite, SWT.FLAT | SWT.BORDER); Rectangle clientArea = shell.getClientArea(); toolBar.setLocation(clientArea.x, clientArea.y); for (int i = 0; i < 2; i++) { int style = i % 2 == 1 ? SWT.DROP_DOWN : SWT.PUSH; ToolItem toolItem = new ToolItem(toolBar, style); toolItem.setImage((i % 2 == 0) ? eclipseToolBar1 : eclipseToolBar2); toolItem.setEnabled(i % 2 == 0); } toolBar.pack(); Button button = new Button(shell, SWT.PUSH); button.setText("Refresh-Current Monitor : Zoom"); Text text1 = new Text(shell, SWT.BORDER); Monitor monitor = button.getMonitor(); text1.setText("" + monitor.getZoom()); button.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { Monitor monitor = button.getMonitor(); text1.setText("" + monitor.getZoom()); } }); Button button2 = new Button(shell, SWT.PUSH); button2.setText("Refresh-Both Monitors : Zoom"); Text text2 = new Text(shell, SWT.BORDER); Monitor[] monitors = display.getMonitors(); StringBuilder text2String = new StringBuilder(); for (int i = 0; i < monitors.length; i++) { text2String.append(monitors[i].getZoom() + (i < (monitors.length - 1) ? " - " : "")); } text2.setText(text2String.toString()); button2.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { Monitor[] monitors = display.getMonitors(); StringBuilder text2String = new StringBuilder(); for (int i = 0; i < monitors.length; i++) { text2String.append(monitors[i].getZoom() + (i < (monitors.length - 1) ? " - " : "")); } text2.setText(text2String.toString()); } }); // Table Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); String titles[] = { "Title 1" }; for (int i = 0; i < titles.length; i++) { TableColumn column = new TableColumn(table, SWT.NONE); column.setText(titles[i]); column.setImage(eclipseTableHeader); } for (int i = 0; i < 1; i++) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, "Data " + i); item.setImage(0, eclipseTableItem); } for (int i = 0; i < titles.length; i++) { table.getColumn(i).pack(); } // Tree final Tree tree = new Tree(shell, SWT.BORDER); for (int i = 0; i < 1; i++) { TreeItem iItem = new TreeItem(tree, 0); iItem.setText("TreeItem (0) -" + i); iItem.setImage(eclipseTree1); TreeItem jItem = null; for (int j = 0; j < 1; j++) { jItem = new TreeItem(iItem, 0); jItem.setText("TreeItem (1) -" + j); jItem.setImage(eclipseTree2); jItem.setExpanded(true); } tree.select(jItem); } // Shell Location Monitor primary = display.getPrimaryMonitor(); Rectangle bounds = primary.getBounds(); Rectangle rect = shell.getBounds(); int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y + (bounds.height - rect.height) / 2; shell.setLocation(x, y); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
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 w ww .j a va 2 s . com 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:de.huxhorn.lilith.Lilith.java
public static void main(String[] args) { {//from w ww.jav a 2s . co m // initialize java.util.logging to use slf4j... Handler handler = new Slf4JHandler(); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); rootLogger.addHandler(handler); rootLogger.setLevel(java.util.logging.Level.WARNING); } StringBuilder appTitle = new StringBuilder(); appTitle.append(APP_NAME).append(" V").append(APP_VERSION); if (APP_SNAPSHOT) { // always append timestamp for SNAPSHOT appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } CommandLineArgs cl = new CommandLineArgs(); JCommander commander = new JCommander(cl); Cat cat = new Cat(); commander.addCommand(Cat.NAME, cat); Tail tail = new Tail(); commander.addCommand(Tail.NAME, tail); Filter filter = new Filter(); commander.addCommand(Filter.NAME, filter); Index index = new Index(); commander.addCommand(Index.NAME, index); Md5 md5 = new Md5(); commander.addCommand(Md5.NAME, md5); Help help = new Help(); commander.addCommand(Help.NAME, help); try { commander.parse(args); } catch (ParameterException ex) { printAppInfo(appTitle.toString(), false); System.out.println(ex.getMessage() + "\n"); printHelp(commander); System.exit(-1); } if (cl.verbose) { if (!APP_SNAPSHOT) { // timestamp is always appended for SNAPSHOT // don't append it twice appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } appTitle.append(" - ").append(APP_REVISION); } String appTitleString = appTitle.toString(); if (cl.showHelp) { printAppInfo(appTitleString, false); printHelp(commander); System.exit(0); } String command = commander.getParsedCommand(); if (!Tail.NAME.equals(command) && !Cat.NAME.equals(command) && !Filter.NAME.equals(command)) // don't print info in case of cat, tail or filter { printAppInfo(appTitleString, true); } if (cl.logbackConfig != null) { File logbackFile = new File(cl.logbackConfig); if (!logbackFile.isFile()) { System.out.println(logbackFile.getAbsolutePath() + " is not a valid file."); System.exit(-1); } try { initLogbackConfig(logbackFile.toURI().toURL()); } catch (MalformedURLException e) { System.out.println("Failed to convert " + logbackFile.getAbsolutePath() + " to URL. " + e); System.exit(-1); } } else if (cl.verbose) { initVerboseLogging(); } if (cl.printBuildTimestamp) { System.out.println("Build-Date : " + APP_TIMESTAMP_DATE); System.out.println("Build-Revision : " + APP_REVISION); System.out.println("Build-Timestamp: " + APP_TIMESTAMP); System.exit(0); } if (Help.NAME.equals(command)) { commander.usage(); if (help.commands == null || help.commands.size() == 0) { commander.usage(Help.NAME); } else { Map<String, JCommander> commands = commander.getCommands(); for (String current : help.commands) { if (commands.containsKey(current)) { commander.usage(current); } else { System.out.println("Unknown command '" + current + "'!"); } } } System.exit(0); } if (Md5.NAME.equals(command)) { List<String> files = md5.files; if (files == null || files.isEmpty()) { printHelp(commander); System.out.println("Missing files!"); System.exit(-1); } boolean error = false; for (String current : files) { if (!CreateMd5Command.createMd5(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Index.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = index.files; if (files == null || files.size() == 0) { printHelp(commander); System.exit(-1); } boolean error = false; for (String current : files) { if (!IndexCommand.indexLogFile(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Cat.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = cat.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (CatCommand.catFile(new File(files.get(0)), cat.pattern, cat.numberOfLines)) { System.exit(0); } System.exit(-1); } if (Tail.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = tail.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (TailCommand.tailFile(new File(files.get(0)), tail.pattern, tail.numberOfLines, tail.keepRunning)) { System.exit(0); } System.exit(-1); } if (Filter.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } if (FilterCommand.filterFile(new File(filter.input), new File(filter.output), new File(filter.condition), filter.searchString, filter.pattern, filter.overwrite, filter.keepRunning, filter.exclusive)) { System.exit(0); } System.exit(-1); } if (cl.flushPreferences) { flushPreferences(); } if (cl.exportPreferencesFile != null) { exportPreferences(cl.exportPreferencesFile); } if (cl.importPreferencesFile != null) { importPreferences(cl.importPreferencesFile); } if (cl.exportPreferencesFile != null || cl.importPreferencesFile != null) { System.exit(0); } if (cl.flushLicensed) { flushLicensed(); } startLilith(appTitleString); }
From source file:com.joliciel.frenchTreebank.FrenchTreebank.java
/** * @param args// w w w.j a v a 2s . c o m */ public static void main(String[] args) throws Exception { String command = args[0]; String outFilePath = ""; String outDirPath = ""; String treebankPath = ""; String ftbFileName = ""; String rawTextDir = ""; String queryPath = ""; String sentenceNumber = null; boolean firstArg = true; for (String arg : args) { if (firstArg) { firstArg = false; continue; } int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); if (argName.equals("outfile")) outFilePath = argValue; else if (argName.equals("outdir")) outDirPath = argValue; else if (argName.equals("ftbFileName")) ftbFileName = argValue; else if (argName.equals("treebank")) treebankPath = argValue; else if (argName.equals("sentence")) sentenceNumber = argValue; else if (argName.equals("query")) queryPath = argValue; else if (argName.equals("rawTextDir")) rawTextDir = argValue; else throw new RuntimeException("Unknown argument: " + argName); } TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance(); TreebankServiceLocator locator = TreebankServiceLocator.getInstance(talismaneServiceLocator); if (treebankPath.length() == 0) locator.setDataSourcePropertiesFile("jdbc-live.properties"); if (command.equals("search")) { final SearchService searchService = locator.getSearchService(); final XmlPatternSearch search = searchService.newXmlPatternSearch(); search.setXmlPatternFile(queryPath); List<SearchResult> searchResults = search.perform(); FileWriter fileWriter = new FileWriter(outFilePath); for (SearchResult searchResult : searchResults) { String lineToWrite = ""; Sentence sentence = searchResult.getSentence(); Phrase phrase = searchResult.getPhrase(); lineToWrite += sentence.getFile().getFileName() + "|"; lineToWrite += sentence.getSentenceNumber() + "|"; List<PhraseUnit> phraseUnits = searchResult.getPhraseUnits(); LOG.debug("Phrase: " + phrase.getId()); for (PhraseUnit phraseUnit : phraseUnits) lineToWrite += phraseUnit.getLemma().getText() + "|"; lineToWrite += phrase.getText(); fileWriter.write(lineToWrite + "\n"); } fileWriter.flush(); fileWriter.close(); } else if (command.equals("load")) { final TreebankService treebankService = locator.getTreebankService(); final TreebankSAXParser parser = new TreebankSAXParser(); parser.setTreebankService(treebankService); parser.parseDocument(treebankPath); } else if (command.equals("loadAll")) { final TreebankService treebankService = locator.getTreebankService(); File dir = new File(treebankPath); String firstFile = null; if (args.length > 2) firstFile = args[2]; String[] files = dir.list(); if (files == null) { throw new RuntimeException("Not a directory or no children: " + treebankPath); } else { boolean startProcessing = true; if (firstFile != null) startProcessing = false; for (int i = 0; i < files.length; i++) { if (!startProcessing && files[i].equals(firstFile)) startProcessing = true; if (startProcessing) { String filePath = args[1] + "/" + files[i]; LOG.debug(filePath); final TreebankSAXParser parser = new TreebankSAXParser(); parser.setTreebankService(treebankService); parser.parseDocument(filePath); } } } } else if (command.equals("loadRawText")) { final TreebankService treebankService = locator.getTreebankService(); final TreebankRawTextAssigner assigner = new TreebankRawTextAssigner(); assigner.setTreebankService(treebankService); assigner.setRawTextDirectory(rawTextDir); assigner.loadRawText(); } else if (command.equals("tokenize")) { Writer csvFileWriter = null; if (outFilePath != null && outFilePath.length() > 0) { if (outFilePath.lastIndexOf("/") > 0) { String outputDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outputDir = new File(outputDirPath); outputDir.mkdirs(); } File csvFile = new File(outFilePath); csvFile.delete(); csvFile.createNewFile(); csvFileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(csvFile, false), "UTF8")); } try { final TreebankService treebankService = locator.getTreebankService(); TreebankExportService treebankExportService = locator.getTreebankExportServiceLocator() .getTreebankExportService(); TreebankUploadService treebankUploadService = locator.getTreebankUploadServiceLocator() .getTreebankUploadService(); TreebankReader treebankReader = null; if (treebankPath.length() > 0) { File treebankFile = new File(treebankPath); if (sentenceNumber != null) treebankReader = treebankUploadService.getXmlReader(treebankFile, sentenceNumber); else treebankReader = treebankUploadService.getXmlReader(treebankFile); } else { treebankReader = treebankService.getDatabaseReader(TreebankSubSet.ALL, 0); } TokeniserAnnotatedCorpusReader reader = treebankExportService .getTokeniserAnnotatedCorpusReader(treebankReader, csvFileWriter); while (reader.hasNextTokenSequence()) { TokenSequence tokenSequence = reader.nextTokenSequence(); List<Integer> tokenSplits = tokenSequence.getTokenSplits(); String sentence = tokenSequence.getText(); LOG.debug(sentence); int currentPos = 0; StringBuilder sb = new StringBuilder(); for (int split : tokenSplits) { if (split == 0) continue; String token = sentence.substring(currentPos, split); sb.append('|'); sb.append(token); currentPos = split; } LOG.debug(sb.toString()); } } finally { csvFileWriter.flush(); csvFileWriter.close(); } } else if (command.equals("export")) { if (outDirPath.length() == 0) throw new RuntimeException("Parameter required: outdir"); File outDir = new File(outDirPath); outDir.mkdirs(); final TreebankService treebankService = locator.getTreebankService(); FrenchTreebankXmlWriter xmlWriter = new FrenchTreebankXmlWriter(); xmlWriter.setTreebankService(treebankService); if (ftbFileName.length() == 0) { xmlWriter.write(outDir); } else { TreebankFile ftbFile = treebankService.loadTreebankFile(ftbFileName); String fileName = ftbFileName.substring(ftbFileName.lastIndexOf('/') + 1); File xmlFile = new File(outDir, fileName); xmlFile.delete(); xmlFile.createNewFile(); Writer xmlFileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(xmlFile, false), "UTF8")); xmlWriter.write(xmlFileWriter, ftbFile); xmlFileWriter.flush(); xmlFileWriter.close(); } } else { throw new RuntimeException("Unknown command: " + command); } LOG.debug("========== END ============"); }
From source file:esg.gateway.client.ESGAccessLogClient.java
public static void main(String[] args) { String serviceHost = null;//w ww .j a v a2 s . c o m long startTime = 0; long endTime = Long.MAX_VALUE; try { serviceHost = args[0]; startTime = Long.parseLong(args[1]); endTime = Long.parseLong(args[2]); } catch (Throwable t) { log.error(t.getMessage()); } try { ESGAccessLogClient client = new ESGAccessLogClient(); if (client.setEndpoint(serviceHost).ping()) { List<String[]> results = null; results = client.fetchAccessLogData(startTime, endTime); System.out.println("---results:[" + (results.size() - 1) + "]---"); for (String[] record : results) { StringBuilder sb = new StringBuilder(); for (String column : record) { sb.append("[" + column + "] "); } System.out.println(sb.toString()); } } System.out.println("-----------------"); } catch (Throwable t) { log.error(t); t.printStackTrace(); } }
From source file:Main.java
private static StringBuilder getStringBuilder() { return new StringBuilder(); }
From source file:Main.java
public static String iCalFooter() { StringBuilder sb = new StringBuilder(); sb.append("END:VCALENDAR").append("\n"); return sb.toString(); }
From source file:Main.java
public static String iCalHeader() { StringBuilder sb = new StringBuilder(); sb.append("BEGIN:VCALENDAR").append("\n"); sb.append("VERSION:2.0").append("\n"); sb.append("PRODID:-//bobbin v0.1//NONSGML iCal Writer//EN").append("\n"); sb.append("CALSCALE:GREGORIAN").append("\n"); sb.append("METHOD:PUBLISH").append("\n"); return sb.toString(); }
From source file:Main.java
private static String int2ip(int ipInt) { StringBuilder sb = new StringBuilder(); sb.append(ipInt & 0xFF).append("."); sb.append((ipInt >> 8) & 0xFF).append("."); sb.append((ipInt >> 16) & 0xFF).append("."); sb.append((ipInt >> 24) & 0xFF); return sb.toString(); }