List of usage examples for java.lang StringBuilder StringBuilder
public StringBuilder(CharSequence seq)
From source file:StringBuilderDemo.java
public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; StringBuilder sb = new StringBuilder(palindrome); sb.reverse(); // reverse it System.out.println(sb);//from w ww . ja v a2s . c om }
From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java
public static void main(String[] args) { ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class, true);/* w w w . jav a2 s .c o m*/ Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR); StringBuilder sbIndex = new StringBuilder(runnables.size() * 50); StringBuilder sbDetails = new StringBuilder(runnables.size() * 200); sbIndex.append("\n<table border=\"0\">\n"); Type lastType = null; for (Class<? extends SOMToolboxApp> c : runnables) { try { // Ignore abstract classes and interfaces if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { continue; } Type type = Type.getType(c); if (type != lastType) { sbIndex.append(" <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n"); sbDetails.append("<h2> " + type + " Applications </h2>\n"); lastType = type; } String descr = "N/A"; try { descr = (String) c.getDeclaredField("DESCRIPTION").get(null); } catch (Exception e) { } String longDescr = "descr"; try { longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null); } catch (Exception e) { } sbIndex.append(" <tr>\n"); sbIndex.append(" <td> <a href=\"#").append(c.getSimpleName()).append("\">") .append(c.getSimpleName()).append("</a> </td>\n"); sbIndex.append(" <td> ").append(descr).append(" </td>\n"); sbIndex.append(" </tr>\n"); sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName()) .append("</h3>\n"); sbDetails.append("<p>").append(longDescr).append("</p>\n"); try { Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null); JSAP jsap = AbstractOptionFactory.registerOptions(options); final ByteArrayOutputStream os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); AbstractOptionFactory.printHelp(jsap, c.getName(), ps); sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>"); } catch (Exception e1) { // we didn't find the options => let the class be invoked ... } } catch (SecurityException e) { // Should not happen - no Security } catch (IllegalArgumentException e) { e.printStackTrace(); } } sbIndex.append("</table>\n\n"); System.out.println(sbIndex); System.out.println(sbDetails); }
From source file:com.cloudhopper.sxmp.PostUTF8MO.java
static public void main(String[] args) throws Exception { String URL = "https://sms-staging.twitter.com/receive/cloudhopper"; // this is a Euro currency symbol //String text = "\u20AC"; // shorter arabic //String text = "\u0623\u0647\u0644\u0627"; // even longer arabic //String text = "\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649"; String text = ""; for (int i = 0; i < 140; i++) { text += "\u0623"; }// ww w . j a v a 2 s . c o m String srcAddr = "+14159129228"; String ticketId = System.currentTimeMillis() + ""; String operatorId = "23"; //text += " " + ticketId; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n") .append("<operation type=\"deliver\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n") .append(" <ticketId>" + ticketId + "</ticketId>\n") .append(" <operatorId>" + operatorId + "</operatorId>\n") .append(" <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n") .append(" <destinationAddress type=\"network\">40404</destinationAddress>\n") .append(" <text encoding=\"UTF-8\">" + HexUtil.toHexString(text.getBytes("UTF-8")) + "</text>\n") .append(" </deliverRequest>\n").append("</operation>\n").append(""); HttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(URL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); logger.debug("----------------------------------------"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } long end = System.currentTimeMillis(); logger.debug("Response took " + (end - start) + " ms"); }
From source file:it.unibas.spicybenchmark.Main.java
public static void main(String[] args) { try {//from w ww . j a v a 2 s .c o m String propertiesFile = args[0]; StringBuilder executionTimes = new StringBuilder("--- Execution times: ---\n"); Configuration configuration = DAOConfiguration.loadConfigurationFile(propertiesFile); IDataSourceProxy dataSource = new DAOXsd().loadSchema(configuration.getSchemaAbsolutePath()); LoadXMLFile xmlLoader = new LoadXMLFile(); Date beforeLoadingExpected = new Date(); INode expectedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getExpectedInstanceAbsolutePath()); Date afterLoadingExpected = new Date(); long loadingExpected = afterLoadingExpected.getTime() - beforeLoadingExpected.getTime(); executionTimes.append("Expected Instance loaded: ").append(loadingExpected).append(" ms\n"); INode translatedInstanceNode = xmlLoader.loadInstance(dataSource, configuration.getTranslatedInstanceAbsolutePath()); Date afterLoadingTranslated = new Date(); long loadingTranslated = afterLoadingTranslated.getTime() - afterLoadingExpected.getTime(); executionTimes.append("Translated Instance loaded: ").append(loadingTranslated).append(" ms\n"); List<String> exclusionList = new DAOExclusionList().loadExclusionList(dataSource, configuration.getExclusionsFileAbsolutePath()); Date startSpicyTime = new Date(); FeatureCollectionGenerator featureCollectionGenerator = new FeatureCollectionGenerator(); FeatureCollection featureCollection = featureCollectionGenerator.generate(expectedInstanceNode, translatedInstanceNode, exclusionList, dataSource, configuration); EvaluateSimilarity evaluator = new EvaluateSimilarity(); SimilarityResult similarityResult = evaluator.getSimilarityResult(featureCollection); similarityResult .setNumberOfNodesInExpectedInstance(new CalculateSize().getNumberOfNodes(expectedInstanceNode)); similarityResult.setNumberOfNodesInTranslatedInstance( new CalculateSize().getNumberOfNodes(translatedInstanceNode)); Date endSpicyTime = new Date(); long spicyExecTime = endSpicyTime.getTime() - startSpicyTime.getTime(); executionTimes.append("Spicy execution time: ").append(spicyExecTime).append(" ms\n"); if (configuration.isTreeEditDistanceValiente()) { Date startValiente = new Date(); similarityResult .setTreeEditDistanceValiente(new TreeEditDistanceGeneratorSimPack().compute(configuration)); Date stopValiente = new Date(); long valienteExecTime = stopValiente.getTime() - startValiente.getTime(); executionTimes.append("Valiente execution time: ").append(valienteExecTime).append(" ms\n"); } if (configuration.isTreeEditDistanceShasha()) { Date startShasha = new Date(); similarityResult.setTreeEditDistanceShasha( new TreeEditDistanceGenerator().computeTreeEditDistance(featureCollection)); Date stopShasha = new Date(); long shashaExecTime = stopShasha.getTime() - startShasha.getTime(); executionTimes.append("Shasha execution time: ").append(shashaExecTime).append(" ms\n"); } // similarityResult.setTopDownOrderedMaximumSubtree(new TopDownOrderedMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setBottomUpMaximumSubtree(new BottomUpMaximumSubtreeGenerator().compute(configuration)); // similarityResult.setJaccard(new JaccardGenerator().compute(expectedInstanceNode, translatedInstanceNode)); Utility.printFinalLog(similarityResult, configuration, executionTimes.toString()); } catch (DAOException ex) { logger.error(ex); } }
From source file:com.seleniumtests.util.helper.AppTestDocumentation.java
public static void main(String[] args) throws IOException { File srcDir = Paths.get(args[0].replace(File.separator, "/"), "src", "test", "java").toFile(); javadoc = new StringBuilder( "Cette page rfrence l'ensemble des tests et des opration disponible pour l'application\n"); javadoc.append("\n{toc}\n\n"); javadoc.append("${project.summary}\n"); javadoc.append("h1. Tests\n"); try {/*from ww w.j av a 2 s.c o m*/ Path testsFolders = Files.walk(Paths.get(srcDir.getAbsolutePath())).filter(Files::isDirectory) .filter(p -> p.getFileName().toString().equals("tests")).collect(Collectors.toList()).get(0); exploreTests(testsFolders.toFile()); } catch (IndexOutOfBoundsException e) { throw new ConfigurationException("no 'tests' sub-package found"); } javadoc.append("----"); javadoc.append("h1. Pages\n"); try { Path pagesFolders = Files.walk(Paths.get(srcDir.getAbsolutePath())).filter(Files::isDirectory) .filter(p -> p.getFileName().toString().equals("webpage")).collect(Collectors.toList()).get(0); explorePages(pagesFolders.toFile()); } catch (IndexOutOfBoundsException e) { throw new ConfigurationException("no 'webpage' sub-package found"); } javadoc.append("${project.scmManager}\n"); FileUtils.write(Paths.get(args[0], "src/site/confluence/template.confluence").toFile(), javadoc, Charset.forName("UTF-8")); }
From source file:com.mattbolt.javaray.JavaRay.java
public static void main(String[] args) { logger.info("Starting JavaRay Ray-Tracer by: Matt Bolt [mbolt35@gmail.com]"); ApplicationContext appContext = new ClassPathXmlApplicationContext("/JavaRayApplicationContext.xml"); JavaRayConfiguration configuration = (JavaRayConfiguration) appContext.getBean("javaRayConfiguration"); View view = new View(configuration); logger.debug(new StringBuilder("Configuration: [View: ").append(configuration.getViewWidth()).append("x") .append(configuration.getViewHeight()).append("], [Anti-Alias: ") .append(configuration.getAntiAlias()).append("]").toString()); Camera camera = new Camera(new Vector3(4, 3, 3)); Scene scene = getSceneThree(configuration); long t = new Date().getTime(); //new RayTracer(configuration).synchronousRender(scene, view, camera); final ImageTarget image = new ImageTarget("test", ImageTarget.ImageType.PNG, view.getWidth(), view.getHeight());/* w ww . j a v a 2 s . co m*/ final WindowTarget window = new WindowTarget(1900, 0, view.getWidth(), view.getHeight()); new RayTracer(configuration).render(scene, view, camera, window); long totalTime = ((new Date().getTime() - t) / 1000); logger.debug("Complete! Took: " + totalTime + "seconds"); }
From source file:org.eclipse.swt.snippets.Snippet196.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("Snippet 196"); 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);// w w w. j a v 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; @Override public void handleEvent(Event e) { if (ignore) return; e.doit = false; if (e.start > 13 || e.end > 14) return; StringBuilder buffer = new StringBuilder(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; } StringBuilder newText = new StringBuilder(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:com.jslsolucoes.tagria.doc.generator.DocGenerator.java
public static void main(String[] args) throws IOException { String workspace = args[0];//from w ww .ja v a 2s . co m Map<String, List<Tag>> groupments = new HashMap<>(); String html = FileUtils.readFileToString( new File(workspace + "/tagria-lib/src/main/resources/META-INF/html.tld"), CHARSET); String ajax = FileUtils.readFileToString( new File(workspace + "/tagria-lib/src/main/resources/META-INF/ajax.tld"), CHARSET); XStream xStream = new XStream(); xStream.processAnnotations(Taglib.class); Taglib taglibForHtml = (Taglib) xStream.fromXML(html); Taglib taglibForAjax = (Taglib) xStream.fromXML(ajax); List<Tag> tags = new ArrayList<Tag>(); tags.addAll(taglibForHtml.getTags()); tags.addAll(taglibForAjax.getTags()); for (Tag tag : tags) { List<Tag> groups = groupments.get(tag.getGroup()); if (groups == null) { groupments.put(tag.getGroup(), new ArrayList<>()); } groupments.get(tag.getGroup()).add(tag); StringBuilder template = new StringBuilder( "<%@include file=\"../app/taglibs.jsp\"%> " + "<html:view title=\"{title}\"> " + " <html:panel> " + " <html:panelHead label=\"" + tag.getName() + "\"></html:panelHead> " + " <html:panelBody> " + " <html:tabPanel> " + " <html:tab label=\"{about}\" active=\"true\"> " + " <html:alert state=\"warning\"> " + " " + tag.getDescription() + " " + " </html:alert> " + " </html:tab> " + " <html:tab label=\"{attributes}\"> "); if (CollectionUtils.isEmpty(tag.getAttributes())) { template.append("<html:alert state=\"info\" label=\"{tag.empty.attributes}\"></html:alert>"); } else { template.append("<html:table><html:tableLine>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.attribute\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.required\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.type\"/></html:tableColumn>" + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.description\"/></html:tableColumn>" + "</html:tableLine>"); for (Attribute attribute : tag.getAttributes()) { template.append("<html:tableLine>" + "<html:tableColumn>" + attribute.getName() + "</html:tableColumn>" + "<html:tableColumn>" + (attribute.getRequired() == null ? false : true) + "</html:tableColumn>" + "<html:tableColumn>" + attribute.getType() + "</html:tableColumn>" + "<html:tableColumn>" + attribute.getDescription() + "</html:tableColumn>" + "</html:tableLine>"); } template.append("</html:table>"); } template.append(" " + " </html:tab> " + " <html:tab label=\"{demo}\"> " + " " + tag.getExample() + " " + " </html:tab> " + " <html:tab label=\"{source}\"> " + " <html:code> " + " <html:view>" + tag.getExampleEscaped() + "</html:view> " + " </html:code> " + " </html:tab> " + " </html:tabPanel> " + " </html:panelBody> " + " </html:panel> " + " </html:view> "); FileUtils.writeStringToFile(new File( workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/component/" + tag.getName() + ".jsp"), template.toString(), CHARSET); } for (List<Tag> values : groupments.values()) { Collections.sort(values, new Comparator<Tag>() { @Override public int compare(Tag o1, Tag o2) { return o1.getName().compareTo(o2.getName()); } }); } StringBuilder menu = new StringBuilder("<html:div cssClass=\"menu\"><html:listGroup>"); for (String key : new TreeSet<String>(groupments.keySet())) { menu.append("<html:listGroupItem><html:collapsable label=\"" + key + "\"><html:listGroup>"); for (Tag tag : groupments.get(key)) { menu.append("<html:listGroupItem><html:link label=\"" + StringUtils.capitalize(tag.getName()) + "\" target=\"conteudo\" url=\"/component/" + tag.getName() + "\"></html:link></html:listGroupItem>"); } menu.append("</html:listGroup></html:collapsable></html:listGroupItem>"); } menu.append("</html:listGroup></html:div>"); File home = new File(workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/app/index.jsp"); FileUtils.writeStringToFile(home, FileUtils.readFileToString(home, CHARSET) .replaceAll("<html:div cssClass=\"menu\">[\\s\\S]*?</html:div>", menu.toString()), CHARSET); }
From source file:com.fortmoon.utils.SymmetricCypher.java
public static void main(String args[]) throws Exception { SymmetricCypher cypher = new SymmetricCypher(); String str = "ThisIsAPasswordString"; String encryptedStr = cypher.encypher(str); System.out.println((new StringBuilder("encrypted string = ")).append(encryptedStr).toString()); String decryptedStr = cypher.decypher(encryptedStr); System.out.println((new StringBuilder("Decrypted str = ")).append(decryptedStr).toString()); }
From source file:net.sfr.tv.mom.mgt.HornetqConsole.java
/** * @param args the command line arguments *///from www. ja v a2 s. co m public static void main(String[] args) { try { String jmxHost = "127.0.0.1"; String jmxPort = "6001"; // Process command line arguments String arg; for (int i = 0; i < args.length; i++) { arg = args[i]; switch (arg) { case "-h": jmxHost = args[++i]; break; case "-p": jmxPort = args[++i]; break; default: break; } } // Check for arguments consistency if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) { LOGGER.info("Usage : "); LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n"); System.exit(1); } System.out.println( SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN))); final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':') .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort) .append("/jmxrmi"); final String jmxServiceUrl = _url.toString(); JMXConnector jmxc = null; final CommandRouter router = new CommandRouter(); try { jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null); assert jmxc != null; // jmxc must be not null } catch (final MalformedURLException e) { System.out.println(SystemUtils.LINE_SEPARATOR .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED))); } catch (Throwable t) { System.out.println(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED))); System.out.print(SystemUtils.LINE_SEPARATOR.concat( Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA))); System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format( "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?", Color.MAGENTA))); System.exit(-1); } System.out.println("\n".concat(Ansi .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW))); final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); // PRINT SERVER STATUS REPORT System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null)); System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null)); printHelp(router); // START COMMAND LINE Scanner scanner = new Scanner(System.in); System.out.print("> "); String input; while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) { String[] cliArgs = input.split("\\ "); CommandHandler handler; if (cliArgs.length < 1) { System.out.print("> "); continue; } Command cmd = Command.fromString(cliArgs[0]); if (cmd == null) { System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n")); cmd = Command.HELP; } switch (cmd) { case STATUS: case LIST: case DROP: Set<Option> options = router.get(cmd); for (Option opt : options) { if (cliArgs[1].equals(opt.toString())) { handler = router.get(cmd, opt); String[] cmdOpts = null; if (cliArgs.length > 2) { cmdOpts = new String[cliArgs.length - 2]; for (int i = 0; i < cmdOpts.length; i++) { cmdOpts[i] = cliArgs[2 + i]; } } Object result = handler.execute(mbsc, cmdOpts); if (result != null && String.class.isAssignableFrom(result.getClass())) { System.out.print((String) result); } System.out.print("> "); } } break; case FORK: // EXECUTE SYSTEM COMMAND ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length)); pb.inheritIO(); pb.start(); break; case HELP: printHelp(router); break; } } } catch (MalformedURLException ex) { LOGGER.log(Level.SEVERE, null, ex); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN))); }