List of usage examples for java.lang StringBuilder append
@Override public StringBuilder append(double d)
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);//from w w w .j ava 2s . co 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.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 va 2s . c o 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:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;/*from w w w. ja v a 2s . c om*/ String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:edu.cmu.sv.modelinference.runner.Main.java
public static void main(String[] args) { Options cmdOpts = createCmdOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;/*from w ww . jav a 2s .co m*/ try { cmd = parser.parse(cmdOpts, args, true); } catch (ParseException exp) { logger.error(exp.getMessage()); System.err.println(exp.getMessage()); Util.printHelpAndExit(Main.class, cmdOpts); } String inputType = cmd.getOptionValue(INPUT_TYPE_ARG); String tool = cmd.getOptionValue(TOOL_TYPE_ARG); String logFile = cmd.getOptionValue(LOG_FILE_ARG).replaceFirst("^~", System.getProperty("user.home")); LogHandler<?> logHandler = null; boolean found = false; for (LogHandler<?> lh : logHandlers) { if (lh.getHandlerName().equals(tool)) { logHandler = lh; found = true; break; } } if (!found) { StringBuilder sb = new StringBuilder(); Iterator<LogHandler<?>> logIter = logHandlers.iterator(); while (logIter.hasNext()) { sb.append(logIter.next().getHandlerName()); if (logIter.hasNext()) sb.append(", "); } logger.error("Did not find tool for arg " + tool); System.err.println("Supported tools: " + Util.getSupportedHandlersString(logHandlers)); Util.printHelpAndExit(Main.class, cmdOpts); } logger.info("Using loghandler for logtype: " + logHandler.getHandlerName()); logHandler.process(logFile, inputType, cmd.getArgs()); }
From source file:com.sdw.dream.spark.examples.ml.JavaOneVsRestExample.java
public static void main(String[] args) { // parse the arguments Params params = parse(args);//from w ww . j a va 2s.c o m SparkConf conf = new SparkConf().setAppName("JavaOneVsRestExample"); JavaSparkContext jsc = new JavaSparkContext(conf); SQLContext jsql = new SQLContext(jsc); // $example on$ // configure the base classifier LogisticRegression classifier = new LogisticRegression().setMaxIter(params.maxIter).setTol(params.tol) .setFitIntercept(params.fitIntercept); if (params.regParam != null) { classifier.setRegParam(params.regParam); } if (params.elasticNetParam != null) { classifier.setElasticNetParam(params.elasticNetParam); } // instantiate the One Vs Rest Classifier OneVsRest ovr = new OneVsRest().setClassifier(classifier); String input = params.input; DataFrame inputData = jsql.read().format("libsvm").load(input); DataFrame train; DataFrame test; // compute the train/ test split: if testInput is not provided use part of input String testInput = params.testInput; if (testInput != null) { train = inputData; // compute the number of features in the training set. int numFeatures = inputData.first().<Vector>getAs(1).size(); test = jsql.read().format("libsvm").option("numFeatures", String.valueOf(numFeatures)).load(testInput); } else { double f = params.fracTest; DataFrame[] tmp = inputData.randomSplit(new double[] { 1 - f, f }, 12345); train = tmp[0]; test = tmp[1]; } // train the multiclass model OneVsRestModel ovrModel = ovr.fit(train.cache()); // score the model on test data DataFrame predictions = ovrModel.transform(test.cache()).select("prediction", "label"); // obtain metrics MulticlassMetrics metrics = new MulticlassMetrics(predictions); StructField predictionColSchema = predictions.schema().apply("prediction"); Integer numClasses = (Integer) MetadataUtils.getNumClasses(predictionColSchema).get(); // compute the false positive rate per label StringBuilder results = new StringBuilder(); results.append("label\tfpr\n"); for (int label = 0; label < numClasses; label++) { results.append(label); results.append("\t"); results.append(metrics.falsePositiveRate((double) label)); results.append("\n"); } Matrix confusionMatrix = metrics.confusionMatrix(); // output the Confusion Matrix System.out.println("Confusion Matrix"); System.out.println(confusionMatrix); System.out.println(); System.out.println(results); // $example off$ jsc.stop(); }
From source file:client.Client.java
/** * @param args the command line arguments *//* w ww. j av a 2 s.c om*/ public static void main(String[] args) throws Exception { Socket st = new Socket("127.0.0.1", 1604); BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream())); PrintWriter p = new PrintWriter(st.getOutputStream()); while (true) { String s = r.readLine(); new Thread() { @Override public void run() { String[] ar = s.split("\\|"); if (s.startsWith("HALLO")) { String str = ""; try { str = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { } p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|" + System.getProperty("os.name") + "|" + str); p.flush(); } if (s.startsWith("msg")) { String text = fromHex(ar[1]); String title = ar[2]; int i = Integer.parseInt(ar[3]); JOptionPane.showMessageDialog(null, text, title, i); } if (s.startsWith("execute")) { String cmd = ar[1]; try { Runtime.getRuntime().exec(cmd); } catch (Exception e) { } } if (s.equals("getsystem")) { StringBuilder sb = new StringBuilder(); for (Object o : System.getProperties().entrySet()) { Map.Entry e = (Map.Entry) o; sb.append("\n" + e.getKey() + "|" + e.getValue()); } p.println("systeminfos|" + toHex(sb.toString().substring(1))); p.flush(); } } }.start(); } }
From source file:org.eclipse.swt.snippets.Snippet338.java
public static void main(String[] args) { Display display = new Display(); Shell parentShell = new Shell(display); parentShell.setText("Snippet 338"); parentShell.setBounds(10, 10, 100, 100); parentShell.open();// ww w .java2 s . c om Shell childShell = new Shell(parentShell); childShell.setLayout(new GridLayout()); TabFolder folder = new TabFolder(childShell, SWT.NONE); folder.setLayout(new FillLayout()); TabItem tab1 = new TabItem(folder, SWT.NONE); tab1.setText("Tab &1"); new TabItem(folder, SWT.NONE).setText("Tab &2"); Composite composite = new Composite(folder, SWT.NONE); composite.setLayout(new GridLayout()); tab1.setControl(composite); Text text1 = new Text(composite, SWT.SINGLE); /* canvas represents a custom control */ final Canvas canvas = new Canvas(composite, SWT.BORDER); canvas.setLayoutData(new GridData(300, 200)); canvas.addListener(SWT.Paint, event -> { if (canvas.isFocusControl()) { event.gc.drawText( "focus is here, custom traverse keys:\n\tN: Tab next\n\tP: Tab previous\n\tR: Return\n\tE: Esc\n\tT: Tab Folder next page", 0, 0); } else { event.gc.drawString("focus is not in this control", 0, 0); } }); canvas.addListener(SWT.KeyDown, event -> { int traversal = SWT.NONE; switch (event.keyCode) { case 'n': traversal = SWT.TRAVERSE_TAB_NEXT; break; case 'p': traversal = SWT.TRAVERSE_TAB_PREVIOUS; break; case 'r': traversal = SWT.TRAVERSE_RETURN; break; case 'e': traversal = SWT.TRAVERSE_ESCAPE; break; case 't': traversal = SWT.TRAVERSE_PAGE_NEXT; break; } if (traversal != SWT.NONE) { event.doit = true; /* this will be the Traverse event's initial doit value */ canvas.traverse(traversal, event); } }); canvas.addFocusListener(focusLostAdapter(e -> canvas.redraw())); canvas.addFocusListener(focusGainedAdapter(e -> canvas.redraw())); Text text2 = new Text(composite, SWT.SINGLE); Button button = new Button(childShell, SWT.PUSH); button.setText("Default &Button"); button.addListener(SWT.Selection, event -> System.out.println("Default button selected")); childShell.setDefaultButton(button); Listener printTraverseListener = event -> { StringBuilder buffer = new StringBuilder("Traverse "); buffer.append(event.widget); buffer.append(" type="); switch (event.detail) { case SWT.TRAVERSE_ARROW_NEXT: buffer.append("TRAVERSE_ARROW_NEXT"); break; case SWT.TRAVERSE_ARROW_PREVIOUS: buffer.append("TRAVERSE_ARROW_NEXT"); break; case SWT.TRAVERSE_ESCAPE: buffer.append("TRAVERSE_ESCAPE"); break; case SWT.TRAVERSE_MNEMONIC: buffer.append("TRAVERSE_MNEMONIC"); break; case SWT.TRAVERSE_PAGE_NEXT: buffer.append("TRAVERSE_PAGE_NEXT"); break; case SWT.TRAVERSE_PAGE_PREVIOUS: buffer.append("TRAVERSE_PAGE_PREVIOUS"); break; case SWT.TRAVERSE_RETURN: buffer.append("TRAVERSE_RETURN"); break; case SWT.TRAVERSE_TAB_NEXT: buffer.append("TRAVERSE_TAB_NEXT"); break; case SWT.TRAVERSE_TAB_PREVIOUS: buffer.append("TRAVERSE_TAB_PREVIOUS"); break; } buffer.append(" doit=" + event.doit); buffer.append(" keycode=" + event.keyCode); buffer.append(" char=" + event.character); buffer.append(" stateMask=" + event.stateMask); System.out.println(buffer.toString()); }; childShell.addListener(SWT.Traverse, printTraverseListener); folder.addListener(SWT.Traverse, printTraverseListener); composite.addListener(SWT.Traverse, printTraverseListener); canvas.addListener(SWT.Traverse, printTraverseListener); button.addListener(SWT.Traverse, printTraverseListener); text1.addListener(SWT.Traverse, printTraverseListener); text2.addListener(SWT.Traverse, printTraverseListener); childShell.pack(); childShell.open(); text1.setFocus(); while (!parentShell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }
From source file:MainGeneratePicasaIniFile.java
public static void main(String[] args) { try {/*from www . ja v a2s. c o m*/ Calendar start = Calendar.getInstance(); start.set(1899, 11, 30, 0, 0); PicasawebService myService = new PicasawebService("My Application"); myService.setUserCredentials(args[0], args[1]); // Get a list of all entries URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album"); System.out.println("Getting Picasa Web Albums entries...\n"); UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class); // resultFeed. File root = new File(args[2]); File[] albuns = root.listFiles(); int j = 0; List<GphotoEntry> entries = resultFeed.getEntries(); for (int i = 0; i < entries.size(); i++) { GphotoEntry entry = entries.get(i); String href = entry.getHtmlLink().getHref(); String name = entry.getTitle().getPlainText(); for (File album : albuns) { if (album.getName().equals(name) && !href.contains("02?")) { File picasaini = new File(album, "Picasa.ini"); if (!picasaini.exists()) { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("[Picasa]\n"); builder.append("name="); builder.append(name); builder.append("\n"); builder.append("location="); Collection<Extension> extensions = entry.getExtensions(); for (Extension extension : extensions) { if (extension instanceof GphotoLocation) { GphotoLocation location = (GphotoLocation) extension; if (location.getValue() != null) { builder.append(location.getValue()); } } } builder.append("\n"); builder.append("category=Folders on Disk"); builder.append("\n"); builder.append("date="); String source = name.substring(0, 10); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); Date date = formater.parse(source); Calendar end = Calendar.getInstance(); end.setTime(date); builder.append(daysBetween(start, end)); builder.append(".000000"); builder.append("\n"); builder.append(args[0]); builder.append("_lh="); builder.append(entry.getGphotoId()); builder.append("\n"); builder.append("P2category=Folders on Disk"); builder.append("\n"); URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0] + "/albumid/" + entry.getGphotoId()); AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class); for (GphotoEntry photo : feed.getEntries()) { builder.append("\n"); builder.append("["); builder.append(photo.getTitle().getPlainText()); builder.append("]"); builder.append("\n"); long id = Long.parseLong(photo.getGphotoId()); builder.append("IIDLIST_"); builder.append(args[0]); builder.append("_lh="); builder.append(Long.toHexString(id)); builder.append("\n"); } System.out.println(builder.toString()); IOUtils.write(builder.toString(), new FileOutputStream(picasaini)); j++; } } } } System.out.println(j); System.out.println("\nTotal Entries: " + entries.size()); } catch (Exception e) { e.printStackTrace(); } }
From source file:ComputeResult.java
public static void main(String[] args) { String original = "software"; StringBuilder result = new StringBuilder("hi"); int index = original.indexOf('a'); /*1*/ result.setCharAt(0, original.charAt(0)); /*2*/ result.setCharAt(1, original.charAt(original.length() - 1)); /*3*/ result.insert(1, original.charAt(4)); /*4*/ result.append(original.substring(1, 4)); /*5*/ result.insert(3, (original.substring(index, index + 2) + " ")); System.out.println(result);/* w w w . ja v a 2s .c o m*/ }
From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.FormFileUploaderClientApplication.java
/** * Run the program./*from w ww . jav a2 s. c om*/ * * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value. */ public static void main(String[] args) { // takes file path from first program's argument if (args.length < 1) { logger.error("****** Path to input file must be first argument to program! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } String filePath = args[0]; File uploadFile = new File(filePath); if (!uploadFile.exists()) { logger.error("****** File does not exist at expected locations! *******"); logger.error("===== Exiting Program ====="); System.exit(1); } if (args.length > 1) { serverUrl = args[1]; } logger.info("File to upload: " + filePath); CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost(serverUrl); FileBody bin = new FileBody(uploadFile); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, bin).build(); httppost.setEntity(reqEntity); logger.info("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { logger.info("HTTP Response Status Line: " + response.getStatusLine()); // Expecting a 200 Status Code if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode() + "] -- Reason (if available): " + reason); } else { HttpEntity resEntity = response.getEntity(); InputStream is = resEntity.getContent(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String output; StringBuilder sb = new StringBuilder("Response data received:"); while ((output = in.readLine()) != null) { sb.append(System.getProperty("line.separator")); sb.append(output); } logger.info(sb.toString()); in.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } catch (Exception e) { logger.error("Caught exception: " + e.getMessage(), e); } finally { try { httpclient.close(); } catch (IOException e) { logger.warn("Exception closing HTTP client: " + e.getMessage(), e); } logger.info("DONE"); } }