List of usage examples for java.lang StringBuilder toString
@Override
@HotSpotIntrinsicCandidate
public String toString()
From source file:com.liferay.mobile.sdk.BuilderAntTask.java
public static void main(String[] args) { Map<String, String> arguments = parseArguments(args); String url = arguments.get("url"); String context = arguments.get("context"); String filter = arguments.get("filter"); StringBuilder sb = new StringBuilder(); sb.append(url);//www.j a v a 2 s. c o m if (Validator.isNotNull(context)) { sb.append("/"); sb.append(context); } sb.append("/api/jsonws?discover"); if (Validator.isNull(filter)) { sb.append("=/*"); } else { sb.append("=/"); sb.append(filter); sb.append("/*"); } HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(sb.toString()); DiscoveryResponseHandler handler = new DiscoveryResponseHandler(); try { String builderType = arguments.get("builder"); Builder builder = null; if (builderType.equals("android")) { builder = new AndroidBuilder(); } Discovery discovery = client.execute(get, handler); PortalVersion version = HttpUtil.getPortalVersion(url); if (Validator.isNull(filter)) { builder.buildAll(version, discovery); } else { builder.build(filter, version, discovery); } } catch (Exception e) { e.printStackTrace(); } }
From source file:aldenjava.opticalmapping.Cigar.java
public static void main(String[] args) throws IOException { System.out.println("Please enter the cigar string to convert:"); StringBuilder cigar = new StringBuilder(); int c = System.in.read(); while (c != -1) { cigar.append((char) c); if (System.in.available() == 0) break; c = System.in.read();/* w w w. j a v a 2 s . co m*/ } String precigar = Cigar.convertpreCIGAR(cigar.toString().trim()); System.out.println("The precigar is:"); System.out.println(precigar); }
From source file:com.mycompany.test.Jaroop.java
/** * This is the main program which will receive the request, calls required methods * and processes the response./* ww w . j a v a2 s .co m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scannedInput = new Scanner(System.in); String in = ""; if (args.length == 0) { System.out.println("Enter the query"); in = scannedInput.nextLine(); } else { in = args[0]; } in = in.toLowerCase().replaceAll("\\s+", "_"); int httpStatus = checkInvalidInput(in); if (httpStatus == 0) { System.out.print("Not found"); System.exit(0); } String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + in; HttpURLConnection connection = getConnection(url); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String request = ""; StringBuilder response = new StringBuilder(); while ((request = input.readLine()) != null) { //only appending what ever is required for JSON parsing and ignoring the rest response.append("{"); //appending the key "extract" to the string so that the JSON parser can parse it's value, //also we don't need last 3 paranthesis in the response, excluding them as well. response.append(request.substring(request.indexOf("\"extract"), request.length() - 3)); } parseJSON(response.toString()); }
From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.BncCheckDocuments.java
public static void main(String[] args) throws IOException { boolean enabled = false; for (File f : FileUtils.listFiles(new File(BASE), new String[] { "xml" }, true)) { BufferedInputStream bis = null; try {/*from w w w .j a v a 2 s . co m*/ bis = new BufferedInputStream(new FileInputStream(f)); int c; StringBuilder sb = new StringBuilder(); while ((c = bis.read()) != '>') { if (enabled) { if (c == '"') { enabled = false; break; } else { sb.append((char) c); } } if (c == '"') { enabled = true; } } String name = f.getName().substring(0, 3); String id = sb.toString(); if (!name.equals(id)) { System.out.println("Name is [" + name + "], but ID is [" + id + "]."); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(bis); } } }
From source file:com.alibaba.jstorm.daemon.worker.Worker.java
/** * worker entrance/*from www .ja v a2s . com*/ * * @param args */ @SuppressWarnings("rawtypes") public static void main(String[] args) { if (args.length < 5) { StringBuilder sb = new StringBuilder(); sb.append("The length of args is less than 5 "); for (String arg : args) { sb.append(arg + " "); } LOG.error(sb.toString()); System.exit(-1); } StringBuilder sb = new StringBuilder(); try { String topology_id = args[0]; String supervisor_id = args[1]; String port_str = args[2]; String worker_id = args[3]; String jar_path = args[4]; killOldWorker(port_str); Map conf = Utils.readStormConfig(); StormConfig.validate_distributed_mode(conf); JStormServerUtils.startTaobaoJvmMonitor(); sb.append("topologyId:" + topology_id + ", "); sb.append("port:" + port_str + ", "); sb.append("workerId:" + worker_id + ", "); sb.append("jar_path:" + jar_path + "\n"); WorkerShutdown sd = mk_worker(conf, null, topology_id, supervisor_id, Integer.parseInt(port_str), worker_id, jar_path); sd.join(); LOG.info("Successfully shutdown worker " + sb.toString()); } catch (Throwable e) { String errMsg = "Failed to create worker, " + sb.toString(); LOG.error(errMsg, e); JStormUtils.halt_process(-1, errMsg); } }
From source file:JSON.JasonJSON.java
public static void main(String[] args) throws Exception { URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json"); //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground //writes a perfectly formatted JSON file that is easy to read with Java. // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201"); try {/*w ww . j av a 2s .c o m*/ HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection(); // This part will read the data returned thru HTTP and load it into memory // I have this code left over from my CIT260 project. InputStream stream = urlCon.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // The next lines read certain parts of the JSON data and print it out on the screen //Creates the JSONObject object and loads the JSON file from the URLConnection //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something JSONObject json = new JSONObject(result.toString()); JSONObject coloradoInfo = (JSONObject) json.get("current_observation"); StringWriter out = new StringWriter(); json.write(out); String jsonTxt = json.toString(); System.out.print(jsonTxt); List<String> list = new ArrayList<>(); JSONArray array = json.getJSONArray(jsonTxt); System.out.print(jsonTxt); // for (int i =0;i<array.length();i++){ //list.add(array.getJSONObject(i).getString("current_observation")); //} String wunderGround = "Data downloaded from: " + coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: " + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: " + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: " + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: " + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: " + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: " + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: " + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string") + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: " + coloradoInfo.get("pressure_in"); System.out.println("\nColorado Springs Weather:"); System.out.println("____________________________________"); System.out.println(wunderGround); } catch (IOException e) { System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString() + "\nERROR: " + e.toString()); } }
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 a2 s .co 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:ca.uqac.lif.bullwinkle.BullwinkleCli.java
/** * @param args//www. ja v a2 s.c o m */ public static void main(String[] args) { // Setup parameters int verbosity = 1; String output_format = "xml", grammar_filename = null, filename_to_parse = null; // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("f")) { output_format = c_line.getOptionValue("f"); } // Get grammar file @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no grammar file specified"); System.exit(ERR_ARGUMENTS); } grammar_filename = remaining_args.get(0); // Get file to parse, if any if (remaining_args.size() >= 2) { filename_to_parse = remaining_args.get(1); } // Read grammar file BnfParser parser = null; try { parser = new BnfParser(new File(grammar_filename)); } catch (InvalidGrammarException e) { System.err.println("ERROR: invalid grammar"); System.exit(ERR_GRAMMAR); } catch (IOException e) { System.err.println("ERROR reading grammar " + grammar_filename); System.exit(ERR_IO); } assert parser != null; // Read input file BufferedReader bis = null; if (filename_to_parse == null) { // Read from stdin bis = new BufferedReader(new InputStreamReader(System.in)); } else { // Read from file try { bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse)))); } catch (FileNotFoundException e) { System.err.println("ERROR: file not found " + filename_to_parse); System.exit(ERR_IO); } } assert bis != null; String str; StringBuilder input_file = new StringBuilder(); try { while ((str = bis.readLine()) != null) { input_file.append(str).append("\n"); } } catch (IOException e) { System.err.println("ERROR reading input"); System.exit(ERR_IO); } String file_contents = input_file.toString(); // Parse contents of file ParseNode p_node = null; try { p_node = parser.parse(file_contents); } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) { System.err.println("ERROR parsing input\n"); e.printStackTrace(); System.exit(ERR_PARSE); } if (p_node == null) { System.err.println("ERROR parsing input\n"); System.exit(ERR_PARSE); } assert p_node != null; // Output parse node to desired format PrintStream output = System.out; OutputFormatVisitor out_vis = null; if (output_format.compareToIgnoreCase("xml") == 0) { // Output to XML out_vis = new XmlVisitor(); } else if (output_format.compareToIgnoreCase("dot") == 0) { // Output to DOT out_vis = new GraphvizVisitor(); } else if (output_format.compareToIgnoreCase("txt") == 0) { // Output to indented plain text out_vis = new IndentedTextVisitor(); } else if (output_format.compareToIgnoreCase("json") == 0) { // Output to JSON } if (out_vis == null) { System.err.println("ERROR: unknown output format " + output_format); System.exit(ERR_ARGUMENTS); } assert out_vis != null; p_node.prefixAccept(out_vis); output.print(out_vis.toOutputString()); // Terminate without error System.exit(ERR_OK); }
From source file:net.modelbased.proasense.storage.registry.StorageRegistrySensorDataTestClient.java
public static void main(String[] args) { // Get client properties from properties file // StorageRegistrySensorDataTestClient client = new StorageRegistrySensorDataTestClient(); // client.loadClientProperties(); // Hardcoded client properties (simple test client) String STORAGE_REGISTRY_SERVICE_URL = "http://192.168.84.34:8080/storage-registry"; // Default HTTP client and common properties for requests HttpClient client = new DefaultHttpClient(); StringBuilder requestUrl = null; List<NameValuePair> params = null; String queryString = null;/* w w w. j a v a 2 s. c om*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for sensor list requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/list"); try { HttpGet query21 = new HttpGet(requestUrl.toString()); query21.setHeader("Content-type", "application/json"); response = client.execute(query21); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR LIST: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } // Query for sensor properties requestUrl = new StringBuilder(STORAGE_REGISTRY_SERVICE_URL); requestUrl.append("/query/sensor/properties"); params = new LinkedList<NameValuePair>(); params.add(new BasicNameValuePair("sensorId", "visualInspection")); queryString = URLEncodedUtils.format(params, "utf-8"); requestUrl.append("?"); requestUrl.append(queryString); try { HttpGet query22 = new HttpGet(requestUrl.toString()); query22.setHeader("Content-type", "application/json"); response = client.execute(query22); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); System.out.println("SENSOR PROPERTIES: " + body); } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.github.xbn.examples.regexutil.non_xbn.BetweenLineMarkersButSkipFirstXmpl.java
public static final void main(String[] as_1RqdTxtFilePath) { Iterator<String> lineItr = null; try {/*from w ww . java2s. co m*/ lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null } catch (IOException iox) { throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox); } catch (RuntimeException rx) { throw new RuntimeException("One required parameter: The path to the text file.", rx); } String LINE_SEP = System.getProperty("line.separator", "\n"); ArrayList<String> alsItems = new ArrayList<String>(); boolean bStartMark = false; boolean bLine1Skipped = false; StringBuilder sdCurrentItem = new StringBuilder(); while (lineItr.hasNext()) { String sLine = lineItr.next().trim(); if (!bStartMark) { if (sLine.startsWith(".START_SEQUENCE")) { bStartMark = true; continue; } throw new IllegalStateException("Start mark not found."); } if (!bLine1Skipped) { bLine1Skipped = true; continue; } else if (!sLine.equals(".END_SEQUENCE")) { sdCurrentItem.append(sLine).append(LINE_SEP); } else { alsItems.add(sdCurrentItem.toString()); sdCurrentItem.setLength(0); bStartMark = false; bLine1Skipped = false; continue; } } for (String s : alsItems) { System.out.println("----------"); System.out.print(s); } }