List of usage examples for java.lang StringBuffer toString
@Override @HotSpotIntrinsicCandidate public synchronized String toString()
From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(new Option("h", "help", false, "Prints this message and exits.")); StringBuffer defaultExtractors = new StringBuffer(); for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) { if (i > 0) { defaultExtractors.append(", "); }//w w w. ja v a 2s . c om defaultExtractors.append(DEFAULT_EXTRACTORS[i]); } options.addOption(new Option("e", "extractor", true, "List of comma-separated extractor class names. " + "Run in order listed. " + "If no extractors listed, runs following: " + defaultExtractors.toString() + ".")); options.addOption( new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'.")); PosixParser parser = new PosixParser(); CommandLine cmdline = parser.parse(options, args, false); List cmdlineArgs = cmdline.getArgList(); Option[] cmdlineOptions = cmdline.getOptions(); HelpFormatter formatter = new HelpFormatter(); // If no args, print help. if (cmdlineArgs.size() <= 0) { usage(formatter, options, 0); } // Now look at options passed. String[] extractors = DEFAULT_EXTRACTORS; String scratch = null; for (int i = 0; i < cmdlineOptions.length; i++) { switch (cmdlineOptions[i].getId()) { case 'h': usage(formatter, options, 0); break; case 'e': String value = cmdlineOptions[i].getValue(); if (value == null || value.length() <= 0) { // Allow saying NO extractors so we can see // how much it costs just reading through // ARCs. extractors = new String[0]; } else { extractors = value.split(","); } break; case 's': scratch = cmdlineOptions[i].getValue(); break; default: throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId()); } } ExtractorTool tool = new ExtractorTool(extractors, scratch); for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) { tool.extract((String) i.next()); } }
From source file:MainClass.java
public static void main(String args[]) throws Exception { URL url = new URL("http://www.java2s.com"); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HTMLEditorKit htmlKit = new HTMLEditorKit(); HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument(); HTMLEditorKit.Parser parser = new ParserDelegator(); HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0); parser.parse(br, callback, true);// www.j a v a 2s . co m ElementIterator iterator = new ElementIterator(htmlDoc); Element element; while ((element = iterator.next()) != null) { AttributeSet attributes = element.getAttributes(); Object name = attributes.getAttribute(StyleConstants.NameAttribute); if ((name instanceof HTML.Tag) && (name == HTML.Tag.H1)) { StringBuffer text = new StringBuffer(); int count = element.getElementCount(); for (int i = 0; i < count; i++) { Element child = element.getElement(i); AttributeSet childAttributes = child.getAttributes(); if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) { int startOffset = child.getStartOffset(); int endOffset = child.getEndOffset(); int length = endOffset - startOffset; text.append(htmlDoc.getText(startOffset, length)); } } System.out.println(name + ": " + text.toString()); } } }
From source file:HelloPeopleJDOM.java
public static void main(String[] args) throws Exception { SAXBuilder builder = new SAXBuilder(); Document doc = builder.build("./src/data.xml"); StringBuffer output = new StringBuffer(); // create the basic HTML output output.append("<html>\n").append("<head>\n<title>\nPerson List</title>\n</head>\n").append("<body>\n") .append("<ul>\n"); Iterator itr = doc.getRootElement().getChildren().iterator(); while (itr.hasNext()) { Element elem = (Element) itr.next(); output.append("<li>"); output.append(elem.getAttribute("lastName").getValue()); output.append(", "); output.append(elem.getAttribute("firstName").getValue()); output.append("</li>\n"); }// w ww.j av a2s .c o m // create the end of the HTML output output.append("</ul>\n</body>\n</html>"); System.out.println(output.toString()); }
From source file:bluevia.examples.MODemo.java
/** * @param args//from w ww . ja v a2 s . co m */ public static void main(String[] args) throws IOException { BufferedReader iReader = null; String apiDataFile = "API-AccessToken.ini"; String consumer_key; String consumer_secret; String registrationId; OAuthConsumer apiConsumer = null; HttpURLConnection request = null; URL moAPIurl = null; Logger logger = Logger.getLogger("moSMSDemo.class"); int i = 0; int rc = 0; Thread mThread = Thread.currentThread(); try { System.setProperty("debug", "1"); iReader = new BufferedReader(new FileReader(apiDataFile)); // Private data: consumer info + access token info + phone info consumer_key = iReader.readLine(); consumer_secret = iReader.readLine(); registrationId = iReader.readLine(); // Set up the oAuthConsumer while (true) { try { logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages...")); apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret); apiConsumer.setMessageSigner(new HmacSha1MessageSigner()); moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId + "/messages?version=v1&alt=json"); request = (HttpURLConnection) moAPIurl.openConnection(); request.setRequestMethod("GET"); apiConsumer.sign(request); StringBuffer doc = new StringBuffer(); BufferedReader br = null; rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = br.readLine(); while (line != null) { doc.append(line); line = br.readLine(); } System.out.printf("Output message: %s\n", doc.toString()); try { JSONObject apiResponse1 = new JSONObject(doc.toString()); String aux = apiResponse1.getString("receivedSMS"); if (aux != null) { String szMessage; String szOrigin; String szDate; JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS"); JSONArray smsInfo = smsPool.optJSONArray("receivedSMS"); if (smsInfo != null) { for (i = 0; i < smsInfo.length(); i++) { szMessage = smsInfo.getJSONObject(i).getString("message"); szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress") .getString("phoneNumber"); szDate = smsInfo.getJSONObject(i).getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } else { JSONObject sms = smsPool.getJSONObject("receivedSMS"); szMessage = sms.getString("message"); szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber"); szDate = sms.getString("dateTime"); System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin, szMessage); } } } catch (JSONException e) { System.err.println("JSON error: " + e.getMessage()); } } else if (rc == HttpURLConnection.HTTP_NO_CONTENT) System.out.printf("No content\n"); else System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage()); request.disconnect(); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } mThread.sleep(15000); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } }
From source file:Main.java
public static void main(String args[]) { Object objectRef = "hello"; String string = "goodbye"; char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean booleanValue = true; char characterValue = 'K'; int integerValue = 7; long longValue = 10000000; float floatValue = 2.5f; double doubleValue = 33.3; StringBuffer buffer = new StringBuffer(); buffer.insert(0, objectRef);/*from w ww. j av a 2s . c om*/ buffer.insert(0, " "); buffer.insert(0, string); buffer.insert(0, " "); buffer.insert(0, charArray); buffer.insert(0, " "); buffer.insert(0, charArray, 3, 3); buffer.insert(0, " "); buffer.insert(0, booleanValue); buffer.insert(0, " "); buffer.insert(0, characterValue); buffer.insert(0, " "); buffer.insert(0, integerValue); buffer.insert(0, " "); buffer.insert(0, longValue); buffer.insert(0, " "); buffer.insert(0, floatValue); buffer.insert(0, " "); buffer.insert(0, doubleValue); System.out.printf("buffer after inserts:\n%s\n\n", buffer.toString()); }
From source file:StyledTextBulletedList.java
public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setText("StyledText Bullet Example"); shell.setLayout(new FillLayout()); final StyledText styledText = new StyledText(shell, SWT.FULL_SELECTION | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL); StringBuffer text = new StringBuffer(); text.append("Here is StyledText with some bulleted lists:\n\n"); for (int i = 0; i < 4; i++) text.append("Red Bullet List Item " + i + "\n"); text.append("\n"); for (int i = 0; i < 2; i++) text.append("Numbered List Item " + i + "\n"); for (int i = 0; i < 4; i++) text.append("Sub List Item " + i + "\n"); for (int i = 0; i < 2; i++) text.append("Numbered List Item " + (2 + i) + "\n"); text.append("\n"); for (int i = 0; i < 4; i++) text.append("Custom Draw List Item " + i + "\n"); styledText.setText(text.toString()); StyleRange style0 = new StyleRange(); style0.metrics = new GlyphMetrics(0, 0, 40); style0.foreground = display.getSystemColor(SWT.COLOR_RED); Bullet bullet0 = new Bullet(style0); StyleRange style1 = new StyleRange(); style1.metrics = new GlyphMetrics(0, 0, 50); style1.foreground = display.getSystemColor(SWT.COLOR_BLUE); Bullet bullet1 = new Bullet(ST.BULLET_NUMBER | ST.BULLET_TEXT, style1); bullet1.text = "."; StyleRange style2 = new StyleRange(); style2.metrics = new GlyphMetrics(0, 0, 80); style2.foreground = display.getSystemColor(SWT.COLOR_GREEN); Bullet bullet2 = new Bullet(ST.BULLET_TEXT, style2); bullet2.text = "\u2713"; StyleRange style3 = new StyleRange(); style3.metrics = new GlyphMetrics(0, 0, 50); Bullet bullet3 = new Bullet(ST.BULLET_CUSTOM, style2); styledText.setLineBullet(2, 4, bullet0); styledText.setLineBullet(7, 2, bullet1); styledText.setLineBullet(9, 4, bullet2); styledText.setLineBullet(13, 2, bullet1); styledText.setLineBullet(16, 4, bullet3); styledText.addPaintObjectListener(new PaintObjectListener() { public void paintObject(PaintObjectEvent event) { Display display = event.display; StyleRange style = event.style; Font font = style.font; if (font == null) font = styledText.getFont(); TextLayout layout = new TextLayout(display); layout.setAscent(event.ascent); layout.setDescent(event.descent); layout.setFont(font);//w ww .ja v a 2 s. co m layout.setText("\u2023 1." + event.bulletIndex + ")"); layout.draw(event.gc, event.x + 10, event.y); layout.dispose(); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:ElementIteratorExample.java
public static void main(String args[]) throws Exception { if (args.length != 1) { System.err.println("Usage: java ElementIteratorExample input-URL"); }/*from w w w . j ava 2 s .com*/ // Load HTML file synchronously URL url = new URL(args[0]); URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); HTMLEditorKit htmlKit = new HTMLEditorKit(); HTMLDocument htmlDoc = (HTMLDocument) htmlKit.createDefaultDocument(); HTMLEditorKit.Parser parser = new ParserDelegator(); HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0); parser.parse(br, callback, true); // Parse ElementIterator iterator = new ElementIterator(htmlDoc); Element element; while ((element = iterator.next()) != null) { AttributeSet attributes = element.getAttributes(); Object name = attributes.getAttribute(StyleConstants.NameAttribute); if ((name instanceof HTML.Tag) && ((name == HTML.Tag.H1) || (name == HTML.Tag.H2) || (name == HTML.Tag.H3))) { // Build up content text as it may be within multiple elements StringBuffer text = new StringBuffer(); int count = element.getElementCount(); for (int i = 0; i < count; i++) { Element child = element.getElement(i); AttributeSet childAttributes = child.getAttributes(); if (childAttributes.getAttribute(StyleConstants.NameAttribute) == HTML.Tag.CONTENT) { int startOffset = child.getStartOffset(); int endOffset = child.getEndOffset(); int length = endOffset - startOffset; text.append(htmlDoc.getText(startOffset, length)); } } System.out.println(name + ": " + text.toString()); } } System.exit(0); }
From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java
/** * The main method./*from w w w .j a v a 2s . co m*/ * * @param args the command line arguments */ public static void main(String[] args) { GnuParser parser = new GnuParser(); Options opts = FluxbusterCLI.initializeOptions(); CommandLine cli; try { cli = parser.parse(opts, args); if (cli.hasOption('?')) { throw new ParseException(null); } if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) { if (log.isInfoEnabled()) { StringBuffer arginfo = new StringBuffer("\n"); arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n"); arginfo.append("calc-features: " + cli.hasOption('f') + "\n"); arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n"); arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n"); arginfo.append("start-date: " + cli.getOptionValue('d') + "\n"); arginfo.append("end-date: " + cli.getOptionValue('e') + "\n"); log.info(arginfo.toString()); } try { boolean clus = true, feat = true, simil = true, clas = true; if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) { if (!cli.hasOption('g')) { clus = false; } if (!cli.hasOption('f')) { feat = false; } if (!cli.hasOption('s')) { simil = false; } if (!cli.hasOption('c')) { clas = false; } } DBInterfaceFactory.init(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); Date logdate = df.parse(cli.getOptionValue('d')); long startTime = logdate.getTime() / 1000; long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000; if (clus) { ClusterGenerator cg = new ClusterGenerator(); List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true); cg.storeClusters(clusters, logdate); } if (feat) { FeatureCalculator calc = new FeatureCalculator(); calc.updateFeatures(logdate); } if (simil) { ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator(); calc2.updateClusterSimilarities(logdate); } if (clas) { Classifier calc3 = new Classifier(); calc3.updateClusterClasses(logdate, 30); } } catch (Exception e) { if (log.isFatalEnabled()) { log.fatal("", e); } } finally { DBInterfaceFactory.shutdown(); } } else { throw new ParseException(null); } } catch (ParseException e1) { PrintWriter writer = new PrintWriter(System.out); HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified " + "then the program will execute as if all of them " + "have been specified. Otherwise, the program will " + "only execute the options specified.", opts, 0, 2, ""); writer.close(); } }
From source file:MainClass.java
public static void main(String args[]) { Object objectRef = "hello"; String string = "goodbye"; char charArray[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; boolean booleanValue = true; char characterValue = 'K'; int integerValue = 7; long longValue = 10000000; float floatValue = 2.5f; double doubleValue = 33.3; StringBuffer buffer = new StringBuffer(); buffer.insert(0, objectRef);//from www .ja va2 s . c om buffer.insert(0, " "); buffer.insert(0, string); buffer.insert(0, " "); buffer.insert(0, charArray); buffer.insert(0, " "); buffer.insert(0, charArray, 3, 3); buffer.insert(0, " "); buffer.insert(0, booleanValue); buffer.insert(0, " "); buffer.insert(0, characterValue); buffer.insert(0, " "); buffer.insert(0, integerValue); buffer.insert(0, " "); buffer.insert(0, longValue); buffer.insert(0, " "); buffer.insert(0, floatValue); buffer.insert(0, " "); buffer.insert(0, doubleValue); System.out.printf("buffer after inserts:\n%s\n\n", buffer.toString()); buffer.deleteCharAt(10); buffer.delete(2, 6); System.out.printf("buffer after deletes:\n%s\n", buffer.toString()); }
From source file:grnet.validation.XMLValidation.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }//w w w. ja v a 2 s.c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }