List of usage examples for java.lang StringBuilder append
@Override public StringBuilder append(double d)
From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java
public static void main(String[] args) throws Exception { HelpFormatter formatter = new HelpFormatter(); // cli options Options options = new Options(); options.addOption(CMD_OPT_INPUT, true, "Input file"); // options.addOption(CMD_OPT_OUTPUT, true, "Output file"); try {/*from w w w . ja va2 s . co m*/ // evaluate command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption(CMD_OPT_INPUT)) { // option value String optionValue = cmd.getOptionValue(CMD_OPT_INPUT); // input file File inputFile = new File(optionValue); // id extractor IdExtractor idExtractor = new IdExtractor(inputFile); Vector<Vector> data = idExtractor.parse(); // // TODO implement output folder // if (cmd.hasOption(CMD_OPT_OUTPUT)) // { // // file output // throw new Exception("Not implemented"); // } // else // { // console output System.out.println("Id;Value"); for (Vector vector : data) { StringBuilder sb = new StringBuilder(); if (vector.size() >= 1) { sb.append(vector.get(0)); } sb.append(";"); if (vector.size() >= 2) { sb.append(vector.get(1)); } System.out.println(sb.toString()); } // } } else { throw new IllegalArgumentException(); } } catch (ParseException e) { formatter.printHelp("ExtractorCLI", options); } catch (IllegalArgumentException e) { formatter.printHelp("ExtractorCLI", options); } }
From source file:com.yahoo.flowetl.commons.runner.Main.java
/** * The main method entry point.//from w ww. j a v a 2 s .co m */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println( Main.class.getSimpleName() + " [runner fully qualified java class name] arguments ..."); return; } System.out.println("+Argument info:"); StringBuilder argsStr = new StringBuilder(); for (int i = 0; i < args.length; i++) { argsStr.append("(" + (i + 1) + ") " + args[i] + " [" + args[i].length() + " chars]"); if (i + 1 != args.length) { argsStr.append(" "); } } System.out.println(argsStr); Map<String, Object> sysInfo = getRuntimeInfo(); System.out.println("+Runtime info:"); for (Entry<String, Object> e : sysInfo.entrySet()) { System.out.println("--- " + e.getKey() + " => " + (e.getValue() == null ? "" : e.getValue())); } String classToRun = args[0]; Class<?> testToRun = KlassUtils.getClassForName(classToRun); if (KlassUtils.isAbstract(testToRun) || KlassUtils.isInterface(testToRun)) { System.out.println("+Runner class name that is not abstract or an interface is required!"); return; } if (ClassUtils.isAssignable(testToRun, (Runner.class)) == false) { System.out.println("+Runner class name that is a instance/subclass of " + Runner.class.getSimpleName() + " is required!"); return; } Class<Runner> rToRun = KlassUtils.getClassForName(classToRun); System.out.println("+Running program specified by runner class " + rToRun); Runner r = KlassUtils.getInstanceOf(rToRun, new Object[] {}); String[] nargs = (String[]) ArrayUtils.subarray(args, 1, args.length); System.out.println("+Proxying to object " + r + " with arguments [" + StringUtils.join(nargs, ",") + "]"); r.runProgram(nargs); }
From source file:org.openeclass.EclassMobile.java
public static void main(String[] args) { try {/* w w w . j a va 2 s .c om*/ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("uname", mUsername)); nvps.add(new BasicNameValuePair("pass", mPassword)); httppost.setEntity(new UrlEncodedFormEntity(nvps)); System.out.println("twra tha kanei add"); System.out.println("prin to response"); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) System.out.println("Invalid response from server: " + status.toString()); System.out.println("meta to response"); Header[] head = response.getAllHeaders(); for (int i = 0; i < head.length; i++) System.out.println("to head exei " + head[i]); System.out.println("Login form get: " + response.getStatusLine()); HttpEntity entity = response.getEntity(); InputStream ips = entity.getContent(); BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024); StringBuilder sb = new StringBuilder(); String s = ""; while ((s = buf.readLine()) != null) { sb.append(s); } System.out.println("to sb einai " + sb.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:ca.uqac.info.trace.TraceGenerator.java
public static void main(String[] args) { // Parse command line arguments Options options = setupOptions();/*ww w .ja va 2 s. c o m*/ CommandLine c_line = setupCommandLine(args, options); int verbosity = 0, max_events = 1000000; if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } String generator_name = "simplerandom"; if (c_line.hasOption("g")) { generator_name = c_line.getOptionValue("generator"); } long time_per_msg = 1000; if (c_line.hasOption("i")) { time_per_msg = Integer.parseInt(c_line.getOptionValue("i")); } if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (c_line.hasOption("e")) { max_events = Integer.parseInt(c_line.getOptionValue("e")); } String feeder_params = ""; if (c_line.hasOption("parameters")) { feeder_params = c_line.getOptionValue("parameters"); } MessageFeeder mf = instantiateFeeder(generator_name, feeder_params); if (mf == null) { System.err.println("Unrecognized feeder name"); System.exit(ERR_ARGUMENTS); } // Trap Ctrl-C to send EOT before shutting down Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { char EOT = 4; System.out.print(EOT); } }); for (int num_events = 0; mf.hasNext() && num_events < max_events; num_events++) { long time_begin = System.nanoTime(); String message = mf.next(); StringBuilder out = new StringBuilder(); out.append(message); System.out.print(out.toString()); long time_end = System.nanoTime(); long duration = time_per_msg - (long) ((time_end - time_begin) / 1000000f); if (duration > 0) { try { Thread.sleep(duration); } catch (InterruptedException e) { } } if (verbosity > 0) { System.err.print("\r" + num_events + " " + duration + "/" + time_per_msg); } } }
From source file:ui.pack.MyFrame.java
public static void main(String... args) throws IOException { //MyFrame mf= new MyFrame(); HttpClient client = HttpClientBuilder.create().build(); String url = "http://localhost:8080/students/all"; HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuilder builder = new StringBuilder(); while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } else {// w ww . j a v a2s. c o m builder.append(line); } } bufferedReader.close(); String result = builder.toString(); System.out.println(result); JSONArray arr = new JSONArray(result); System.out.println(arr.length()); //client. }
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 {/*ww w. ja v a 2 s . 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:UploadUrlGenerator.java
public static void main(String[] args) throws Exception { Options opts = new Options(); opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url") .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build()); opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key") .desc("Sets the Access Key (user) to sign the request").build()); opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret") .desc("Sets the secret key to sign the request").build()); opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name") .desc("The bucket containing the object").build()); opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key") .desc("The object name (key) to access with the URL").build()); opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes") .desc("Minutes from local time to expire the request. 1 day = 1440, 1 week=10080, " + "1 month (30 days)=43200, 1 year=525600. Defaults to 1 hour (60).") .build());//from www . j a va 2s .c om opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class) .desc("The HTTP verb that will be used with the URL (PUT, GET, etc). Defaults to GET.").build()); opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype") .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request. " + "Must match exactly. Defaults to application/octet-stream for PUT/POST and " + "null for all others") .build()); DefaultParser dp = new DefaultParser(); CommandLine cmd = null; try { cmd = dp.parse(opts, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter hf = new HelpFormatter(); hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true); System.exit(255); } URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION)); String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION); String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION); String bucket = cmd.getOptionValue(BUCKET_OPTION); String key = cmd.getOptionValue(KEY_OPTION); HttpMethod method = HttpMethod.GET; if (cmd.hasOption(VERB_OPTION)) { method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase()); } int expiresMinutes = 60; if (cmd.hasOption(EXPIRES_OPTION)) { expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION)); } String contentType = null; if (method == HttpMethod.PUT || method == HttpMethod.POST) { contentType = "application/octet-stream"; } if (cmd.hasOption(CONTENT_TYPE_OPTION)) { contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION); } BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration cc = new ClientConfiguration(); // Force use of v2 Signer. ECS does not support v4 signatures yet. cc.setSignerOverride("S3SignerType"); AmazonS3Client s3 = new AmazonS3Client(credentials, cc); s3.setEndpoint(endpoint.toString()); S3ClientOptions s3c = new S3ClientOptions(); s3c.setPathStyleAccess(true); s3.setS3ClientOptions(s3c); // Sign the URL Calendar c = Calendar.getInstance(); c.add(Calendar.MINUTE, expiresMinutes); GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime()) .withMethod(method); if (contentType != null) { req = req.withContentType(contentType); } URL u = s3.generatePresignedUrl(req); System.out.printf("URL: %s\n", u.toURI().toASCIIString()); System.out.printf("HTTP Verb: %s\n", method); System.out.printf("Expires: %s\n", c.getTime()); System.out.println("To Upload with curl:"); StringBuilder sb = new StringBuilder(); sb.append("curl "); if (method != HttpMethod.GET) { sb.append("-X "); sb.append(method.toString()); sb.append(" "); } if (contentType != null) { sb.append("-H \"Content-Type: "); sb.append(contentType); sb.append("\" "); } if (method == HttpMethod.POST || method == HttpMethod.PUT) { sb.append("-T <filename> "); } sb.append("\""); sb.append(u.toURI().toASCIIString()); sb.append("\""); System.out.println(sb.toString()); System.exit(0); }
From source file:com.yahoo.athenz.example.http.tls.client.HttpTLSClient.java
public static void main(String[] args) { // parse our command line to retrieve required input CommandLine cmd = parseCommandLine(args); final String url = cmd.getOptionValue("url"); final String keyPath = cmd.getOptionValue("key"); final String certPath = cmd.getOptionValue("cert"); final String trustStorePath = cmd.getOptionValue("trustStorePath"); final String trustStorePassword = cmd.getOptionValue("trustStorePassword"); // we are going to setup our service private key and // certificate into a ssl context that we can use with // our http client try {//from w w w. ja v a 2s . co m KeyRefresher keyRefresher = Utils.generateKeyRefresher(trustStorePath, trustStorePassword, certPath, keyPath); SSLContext sslContext = Utils.buildSSLContext(keyRefresher.getKeyManagerProxy(), keyRefresher.getTrustManagerProxy()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection(); con.setReadTimeout(15000); con.setDoOutput(true); con.connect(); try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Data output: " + sb.toString()); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } }
From source file:com.yahoo.labs.samoa.topology.impl.StormTopologySubmitter.java
public static void main(String[] args) throws IOException { Properties props = StormSamoaUtils.getProperties(); String uploadedJarLocation = props.getProperty(StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY); if (uploadedJarLocation == null) { logger.error("Invalid properties file. It must have key {}", StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY); return;/*from w w w . ja v a2s . com*/ } List<String> tmpArgs = new ArrayList<String>(Arrays.asList(args)); int numWorkers = StormSamoaUtils.numWorkers(tmpArgs); args = tmpArgs.toArray(new String[0]); StormTopology stormTopo = StormSamoaUtils.argsToTopology(args); Config conf = new Config(); conf.putAll(Utils.readStormConfig()); conf.putAll(Utils.readCommandLineOpts()); conf.setDebug(false); conf.setNumWorkers(numWorkers); String profilerOption = props.getProperty(StormTopologySubmitter.YJP_OPTIONS_KEY); if (profilerOption != null) { String topoWorkerChildOpts = (String) conf.get(Config.TOPOLOGY_WORKER_CHILDOPTS); StringBuilder optionBuilder = new StringBuilder(); if (topoWorkerChildOpts != null) { optionBuilder.append(topoWorkerChildOpts); optionBuilder.append(' '); } optionBuilder.append(profilerOption); conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, optionBuilder.toString()); } Map<String, Object> myConfigMap = new HashMap<String, Object>(conf); StringWriter out = new StringWriter(); try { JSONValue.writeJSONString(myConfigMap, out); } catch (IOException e) { System.out.println("Error in writing JSONString"); e.printStackTrace(); return; } Config config = new Config(); config.putAll(Utils.readStormConfig()); String nimbusHost = (String) config.get(Config.NIMBUS_HOST); NimbusClient nc = new NimbusClient(nimbusHost); String topologyName = stormTopo.getTopologyName(); try { System.out.println("Submitting topology with name: " + topologyName); nc.getClient().submitTopology(topologyName, uploadedJarLocation, out.toString(), stormTopo.getStormBuilder().createTopology()); System.out.println(topologyName + " is successfully submitted"); } catch (AlreadyAliveException aae) { System.out.println("Fail to submit " + topologyName + "\nError message: " + aae.get_msg()); } catch (InvalidTopologyException ite) { System.out.println("Invalid topology for " + topologyName); ite.printStackTrace(); } catch (TException te) { System.out.println("Texception for " + topologyName); te.printStackTrace(); } }
From source file:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java
/** * Run the program.//from w w w .j a v a 2s. c o m * * @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 + "false"); FileBody bin = new FileBody(uploadFile); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart(FITS_FORM_FIELD_DATAFILE, bin); HttpEntity reqEntity = builder.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(); while ((output = in.readLine()) != null) { sb.append(output); sb.append(System.getProperty("line.separator")); } 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"); } }