List of usage examples for java.lang StringBuffer substring
@Override public synchronized String substring(int start, int end)
From source file:Main.java
public static void main(String[] argv) { StringBuffer sb = new StringBuffer(); sb.append("java2s.com"); String sub = sb.substring(1, 2); System.out.println(sub);/*from w ww. j a v a2s.c o m*/ }
From source file:TextVerifyInputFormatDate.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); text.setText("YYYY/MM/DD"); ;//from w ww . ja va 2 s . c o m final Calendar calendar = Calendar.getInstance(); text.addListener(SWT.Verify, new Listener() { boolean ignore; public void handleEvent(Event e) { if (ignore) return; e.doit = false; StringBuffer buffer = new StringBuffer(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(); StringBuffer date = new StringBuffer(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:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * /* w ww . java2s. c o m*/ * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }
From source file:thrift.Client.java
public static void main(String args[]) throws IOException { Options opt = new Options(); Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC); o.setRequired(true);/*from w w w .j a va 2s. co m*/ opt.addOption(o); o = new Option(INPUT_SHORT_PARAM, INPUT_LONG_PARAM, true, INPUT_DESC); o.setRequired(true); opt.addOption(o); o = new Option(OUTPUT_SHORT_PARAM, OUTPUT_LONG_PARAM, true, OUTPUT_DESC); o.setRequired(true); opt.addOption(o); o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC); o.setRequired(true); opt.addOption(o); opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC); opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC); opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC); opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC); opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try { CommandLine cmd = parser.parse(opt, args); String host = cmd.getOptionValue(HOST_SHORT_PARAM); String inputFile = cmd.getOptionValue(INPUT_SHORT_PARAM); BufferedReader inp = new BufferedReader(new FileReader(inputFile)); // read the user mapping Map<Integer, Long> userMapping = new HashMap<>(); BufferedReader in = new BufferedReader(new FileReader(inputFile + "_users")); String line = null; int index = 0; while ((line = in.readLine()) != null) { long id = Long.parseLong(line); userMapping.put(index, id); index++; } in.close(); String tmp = null; tmp = cmd.getOptionValue(PORT_SHORT_PARAM); int port = -1; try { port = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("Port should be integer!"); } boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM); boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM); String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM); if (null == queryTimeParams) queryTimeParams = ""; SearchType searchType = SearchType.kKNNSearch; int k = 0; double r = 0; if (cmd.hasOption(K_SHORT_PARAM)) { if (cmd.hasOption(R_SHORT_PARAM)) { Usage("Range search is not allowed if the KNN search is specified!"); } tmp = cmd.getOptionValue(K_SHORT_PARAM); try { k = Integer.parseInt(tmp); } catch (NumberFormatException e) { Usage("K should be integer!"); } searchType = SearchType.kKNNSearch; } else if (cmd.hasOption(R_SHORT_PARAM)) { if (cmd.hasOption(K_SHORT_PARAM)) { Usage("KNN search is not allowed if the range search is specified!"); } searchType = SearchType.kRangeSearch; tmp = cmd.getOptionValue(R_SHORT_PARAM); try { r = Double.parseDouble(tmp); } catch (NumberFormatException e) { Usage("The range value should be numeric!"); } } else { Usage("One has to specify either range or KNN-search parameter"); } /*------------------------------------------ Exporting ------------------------------------------------------*/ boolean printSim = true; String outfile = cmd.getOptionValue(OUTPUT_SHORT_PARAM);//"NMSLIB-neighbours.txt"; PrintStream out = new PrintStream(new File(outfile)); String separator = System.getProperty("line.separator"); try { TTransport transport = new TSocket(host, port); transport.open(); TProtocol protocol = new TBinaryProtocol(transport); QueryService.Client client = new QueryService.Client(protocol); int nLine = 0; while ((line = inp.readLine()) != null) { StringBuffer sb = new StringBuffer(); sb.append(line); sb.append(separator); String queryObj = sb.toString(); if (!queryTimeParams.isEmpty()) client.setQueryTimeParams(queryTimeParams); List<ReplyEntry> res = null; // long t1 = System.nanoTime(); if (searchType == SearchType.kKNNSearch) { // System.out.println(String.format("Running a %d-NN // search", k)); res = client.knnQuery(k + 1, queryObj, retExternId, retObj); } else { // System.out.println(String.format("Running a range // search (r=%g)", r)); res = client.rangeQuery(r, queryObj, retExternId, retObj); } //res = res.stream().filter(v -> v.getDist() > 0.0).collect(Collectors.toList()); res = res.stream().collect(Collectors.toList()); final Long userId = userMapping.get(nLine); StringBuffer sbBuffer = new StringBuffer(); res.forEach(elem -> { // the returned ids start in zero by default, so we need to transform that value to a proper id Long id = userMapping.get(elem.getId()); if (id != userId) { sbBuffer.append(id + (printSim ? ":" + elem.dist : "") + ","); } }); out.println(userId + "\t" + sbBuffer.substring(0, sbBuffer.length() - 1)); nLine++; } inp.close(); out.close(); System.out.println("Done! Neighborhood files created succesfuly. Closing connection"); transport.close(); // Close transport/socket ! } catch (TException te) { System.err.println("Apache Thrift exception: " + te); te.printStackTrace(); } } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:TextVerifyInputRegularExpression.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$ text.setFont(font);//www. jav a 2 s .c om text.setText(template); text.addListener(SWT.Verify, new Listener() { // create the pattern for verification Pattern pattern = Pattern.compile(REGEX); // ignore event when caused by inserting text inside event handler boolean ignore; public void handleEvent(Event e) { if (ignore) return; e.doit = false; if (e.start > 13 || e.end > 14) return; StringBuffer buffer = new StringBuffer(e.text); // handle backspace if (e.character == '\b') { for (int i = e.start; i < e.end; i++) { // skip over separators switch (i) { case 0: if (e.start + 1 == e.end) { return; } else { buffer.append('('); } break; case 4: if (e.start + 1 == e.end) { buffer.append(new char[] { '#', ')' }); e.start--; } else { buffer.append(')'); } break; case 8: if (e.start + 1 == e.end) { buffer.append(new char[] { '#', '-' }); e.start--; } else { buffer.append('-'); } break; default: buffer.append('#'); } } text.setSelection(e.start, e.start + buffer.length()); ignore = true; text.insert(buffer.toString()); ignore = false; // move cursor backwards over separators if (e.start == 5 || e.start == 9) e.start--; text.setSelection(e.start, e.start); return; } StringBuffer newText = new StringBuffer(defaultText); char[] chars = e.text.toCharArray(); int index = e.start - 1; for (int i = 0; i < e.text.length(); i++) { index++; switch (index) { case 0: if (chars[i] == '(') continue; index++; break; case 4: if (chars[i] == ')') continue; index++; break; case 8: if (chars[i] == '-') continue; index++; break; } if (index >= newText.length()) return; newText.setCharAt(index, chars[i]); } // if text is selected, do not paste beyond range of selection if (e.start < e.end && index + 1 != e.end) return; Matcher matcher = pattern.matcher(newText); if (matcher.lookingAt()) { text.setSelection(e.start, index + 1); ignore = true; text.insert(newText.substring(e.start, index + 1)); ignore = false; } } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } font.dispose(); display.dispose(); }
From source file:Main.java
private static boolean isDelSingleQuotes(StringBuffer tempBuffer, int beginIndex, int endIndex) { if (isWrongIndex(beginIndex, endIndex)) { return false; }/*from ww w. j a va2s . co m*/ if (!"?".equals(tempBuffer.substring(beginIndex + 1, endIndex).trim())) { return false; } return true; }
From source file:Main.java
/** * Forms an hex-encoded String of the specified byte array. * * @param byteArray The byte array to be hex-encoded. * * @return An hex-encoded String of the specified byte array. *//*from w ww.ja v a2s . c om*/ public static String byteArrayToHexString(byte[] byteArray) { if (byteArray == null) { return ""; } StringBuffer sb = new StringBuffer(); for (byte b : byteArray) { sb.append(String.format("%02X ", b & 0xFF)); } return sb.substring(0, sb.length() - 1).toString(); }
From source file:Main.java
/** * /* w ww .ja va 2 s . c o m*/ * @param array * @return String */ public static String toString(double[][] array) { final StringBuffer buffer = new StringBuffer(ARRAY_OPEN_TAG); for (int i = 0; i < array.length; i++) { final StringBuffer tempBuffer = new StringBuffer(Arrays.toString(array[i])); buffer.append(tempBuffer.substring(1, tempBuffer.length() - 1)); buffer.append(ARRAY_SEPARATOR); } buffer.append(ARRAY_CLOSE_TAG); return buffer.toString(); }
From source file:Main.java
public static String join(String[] array, String delim) { if (array == null || array.length == 0) { return ""; }/* w ww . ja v a2s .c o m*/ StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { sb.append(array[i]); sb.append(delim); } return sb.substring(0, sb.length() - delim.length()); }
From source file:Main.java
public static String join(Number[] numbers, String delim) { if (numbers == null || numbers.length == 0) { return ""; }/* www. j av a2s . com*/ StringBuffer sb = new StringBuffer(); for (int i = 0; i < numbers.length; i++) { sb.append(numbers[i]); sb.append(delim); } return sb.substring(0, sb.length() - delim.length()); }