List of usage examples for java.lang StringBuilder charAt
char charAt(int index);
From source file:Main.java
public static void main(String args[]) { StringBuilder buffer = new StringBuilder("hello java2s.com"); System.out.println(buffer.charAt(0)); System.out.println(buffer.charAt(4)); }
From source file:Main.java
public static void main(String args[]) { StringBuilder sb = new StringBuilder("java2s.com"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); }
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 w w . j a va2s.c o 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:com.admc.jcreole.JCreole.java
/** * Run this method with no parameters to see syntax requirements and the * available parameters.//w w w . java2s. c o m * * 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"); } }
From source file:org.eclipse.swt.snippets.Snippet179.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Snippet 179"); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); text.setText("YYYY/MM/DD"); final Calendar calendar = Calendar.getInstance(); text.addListener(SWT.Verify, new Listener() { boolean ignore; @Override//from ww w.j av a2s. c o m public void handleEvent(Event e) { if (ignore) return; e.doit = false; StringBuilder buffer = new StringBuilder(e.text); char[] chars = new char[buffer.length()]; buffer.getChars(0, chars.length, chars, 0); if (e.character == '\b') { for (int i = e.start; i < e.end; i++) { switch (i) { case 0: /* [Y]YYY */ case 1: /* Y[Y]YY */ case 2: /* YY[Y]Y */ case 3: /* YYY[Y] */ { buffer.append('Y'); break; } case 5: /* [M]M*/ case 6: /* M[M] */ { buffer.append('M'); break; } case 8: /* [D]D */ case 9: /* D[D] */ { buffer.append('D'); break; } case 4: /* YYYY[/]MM */ case 7: /* MM[/]DD */ { buffer.append('/'); break; } default: return; } } text.setSelection(e.start, e.start + buffer.length()); ignore = true; text.insert(buffer.toString()); ignore = false; text.setSelection(e.start, e.start); return; } int start = e.start; if (start > 9) return; int index = 0; for (int i = 0; i < chars.length; i++) { if (start + index == 4 || start + index == 7) { if (chars[i] == '/') { index++; continue; } buffer.insert(index++, '/'); } if (chars[i] < '0' || '9' < chars[i]) return; if (start + index == 5 && '1' < chars[i]) return; /* [M]M */ if (start + index == 8 && '3' < chars[i]) return; /* [D]D */ index++; } String newText = buffer.toString(); int length = newText.length(); StringBuilder date = new StringBuilder(text.getText()); date.replace(e.start, e.start + length, newText); calendar.set(Calendar.YEAR, 1901); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DATE, 1); String yyyy = date.substring(0, 4); if (yyyy.indexOf('Y') == -1) { int year = Integer.parseInt(yyyy); calendar.set(Calendar.YEAR, year); } String mm = date.substring(5, 7); if (mm.indexOf('M') == -1) { int month = Integer.parseInt(mm) - 1; int maxMonth = calendar.getActualMaximum(Calendar.MONTH); if (0 > month || month > maxMonth) return; calendar.set(Calendar.MONTH, month); } String dd = date.substring(8, 10); if (dd.indexOf('D') == -1) { int day = Integer.parseInt(dd); int maxDay = calendar.getActualMaximum(Calendar.DATE); if (1 > day || day > maxDay) return; calendar.set(Calendar.DATE, day); } else { if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) { char firstChar = date.charAt(8); if (firstChar != 'D' && '2' < firstChar) return; } } text.setSelection(e.start, e.start + length); ignore = true; text.insert(newText); ignore = false; } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:Main.java
private static String swapChars(String str, int lIdx, int rIdx) { StringBuilder sb = new StringBuilder(str); char l = sb.charAt(lIdx), r = sb.charAt(rIdx); sb.setCharAt(lIdx, r);//from w w w .j a va 2 s. co m sb.setCharAt(rIdx, l); return sb.toString(); }
From source file:Main.java
private static boolean lastCharIsWhitespace(StringBuilder sb) { return sb.length() != 0 && sb.charAt(sb.length() - 1) == ' '; }
From source file:Main.java
public static String capitalizeFirstChar(String target) { StringBuilder capitalized = new StringBuilder(target); capitalized.setCharAt(0, Character.toUpperCase(capitalized.charAt(0))); return capitalized.toString(); }
From source file:Main.java
/** * Trim all occurrences of the supplied trailing character from the given String. * @param str the String to check/*from ww w . j ava 2s . c o m*/ * @param trailingCharacter the trailing character to be trimmed * @return the trimmed String */ public static String trimTrailingCharacter(String str, char trailingCharacter) { if (!hasLength(str)) { return str; } StringBuilder sb = new StringBuilder(str); while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); }
From source file:Main.java
public static String getHex(byte[] raw) { if (raw == null) { return null; }/*from w ww . j a va2 s . co m*/ final StringBuilder hex = new StringBuilder(2 * raw.length); for (final byte b : raw) { hex.append(HEX.charAt((b & 0xF0) >> 4)).append(HEX.charAt((b & 0x0F))); } return hex.toString(); }