List of usage examples for java.io StringWriter StringWriter
public StringWriter()
From source file:com.e2info.helloasm.HelloAsmApp.java
public static void main(String[] args) throws IOException { String name = "HelloAsm"; int flag = ClassWriter.COMPUTE_MAXS; ClassWriter cw = new ClassWriter(flag); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, name, null, "java/lang/Object", null); cw.visitSource(name + ".java", null); {/*from w w w .j a v a 2s . co m*/ MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(Opcodes.RETURN); // we need this call to take effect ClassWriter.COMPUTE_MAXS flag. mv.visitMaxs(0, 0); mv.visitEnd(); } { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitCode(); mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("hello ASM"); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitInsn(Opcodes.RETURN); // we need this call to take effect ClassWriter.COMPUTE_MAXS flag. mv.visitMaxs(0, 0); mv.visitEnd(); } cw.visitEnd(); // build binary byte[] bin = cw.toByteArray(); // save asm trace for human readable { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); new ClassReader(bin).accept(new TraceClassVisitor(pw), 0); File f = new File(name + ".txt"); FileUtils.writeStringToFile(f, sw.toString()); } // save as calss file { File f = new File(name + ".class"); FileUtils.writeByteArrayToFile(f, bin); } }
From source file:com.datatorrent.stram.StreamingAppMaster.java
/** * @param args//from w w w. ja va2s . com * Command line args * @throws Throwable */ public static void main(final String[] args) throws Throwable { StdOutErrLog.tieSystemOutAndErrToLog(); LOG.info("Master starting with classpath: {}", System.getProperty("java.class.path")); LOG.info("version: {}", VersionInfo.APEX_VERSION.getBuildVersion()); StringWriter sw = new StringWriter(); for (Map.Entry<String, String> e : System.getenv().entrySet()) { sw.append("\n").append(e.getKey()).append("=").append(e.getValue()); } LOG.info("appmaster env:" + sw.toString()); Options opts = new Options(); opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used unless for testing purposes"); opts.addOption("help", false, "Print usage"); CommandLine cliParser = new GnuParser().parse(opts, args); // option "help" overrides and cancels any run if (cliParser.hasOption("help")) { new HelpFormatter().printHelp("ApplicationMaster", opts); return; } Map<String, String> envs = System.getenv(); ApplicationAttemptId appAttemptID = Records.newRecord(ApplicationAttemptId.class); if (!envs.containsKey(Environment.CONTAINER_ID.name())) { if (cliParser.hasOption("app_attempt_id")) { String appIdStr = cliParser.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else { throw new IllegalArgumentException("Application Attempt Id not set in the environment"); } } else { ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); } boolean result = false; StreamingAppMasterService appMaster = null; try { appMaster = new StreamingAppMasterService(appAttemptID); LOG.info("Initializing Application Master."); Configuration conf = new YarnConfiguration(); appMaster.init(conf); appMaster.start(); result = appMaster.run(); } catch (Throwable t) { LOG.error("Exiting Application Master", t); System.exit(1); } finally { if (appMaster != null) { appMaster.stop(); } } if (result) { LOG.info("Application Master completed."); System.exit(0); } else { LOG.info("Application Master failed."); System.exit(2); } }
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 {//from w ww . j a v a 2 s.co 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:com.discursive.jccook.slide.GetExample.java
public static void main(String[] args) throws HttpException, IOException { HttpClient client = new HttpClient(); String url = "http://www.discursive.com/jccook/dav/test.html"; Credentials credentials = new UsernamePasswordCredentials("davuser", "davpass"); // List resources in top directory WebdavResource resource = new WebdavResource(url, credentials); System.out.println("The three ways to Read resources."); // Read to a temporary file File tempFile = new File(resource.getName()); resource.getMethod(tempFile);/*from www . j av a 2 s.co m*/ System.out.println("1. " + resource.getName() + " saved in file: " + tempFile.toString()); // Read as a String String resourceData = resource.getMethodDataAsString(); System.out.println("2. Contents of " + resource.getName() + " as String."); System.out.println(resourceData); // Read with a stream InputStream resourceStream = resource.getMethodData(); Reader reader = new InputStreamReader(resourceStream); StringWriter writer = new StringWriter(); while (reader.ready()) { writer.write(reader.read()); } System.out.println("3. Contents of " + resource.getName() + " from InputStream."); System.out.println(writer.toString()); resource.close(); }
From source file:ar.com.zauber.garfio.Main.java
/** * @param args arguments./*w w w . j a v a2s . co m*/ * @throws Exception on error */ public static void main(final String[] args) throws Exception { if (args.length < 3) { System.err.printf("Usage: %s revision username config.properties [dry-run]", Main.class); System.exit(1); } final String revision = args[0]; final String username = args[1]; final String config = args[2]; final boolean isDryRun = args.length >= 4 && "dry-run".equals(args[3]); final PropertiesConfiguration configuration = getConfiguration(config, username, revision); final GarfioService garfioService = new DefaultGarfioService(getConfigurationDAO(configuration), getErrorNotificator()); final StringWriter writer = new StringWriter(); IOUtil.copy(System.in, writer); if (isDryRun) { final List<String> errors = garfioService.dryrun(configuration.getRepositoryName(), username, writer.toString()); for (String error : errors) { System.err.println(error); } System.exit(errors.isEmpty() ? 0 : 1); } else { garfioService.run(configuration.getRepositoryName(), revision, args[1], writer.toString()); } }
From source file:ModifyModelSample.java
public static void main(String args[]) { JFrame frame = new JFrame("Modifying Model"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); // Fill model final DefaultListModel model = new DefaultListModel(); for (int i = 0, n = labels.length; i < n; i++) { model.addElement(labels[i]);/*from w w w .j av a 2 s . c o m*/ } JList jlist = new JList(model); JScrollPane scrollPane1 = new JScrollPane(jlist); contentPane.add(scrollPane1, BorderLayout.WEST); final JTextArea textArea = new JTextArea(); textArea.setEditable(false); JScrollPane scrollPane2 = new JScrollPane(textArea); contentPane.add(scrollPane2, BorderLayout.CENTER); ListDataListener listDataListener = new ListDataListener() { public void contentsChanged(ListDataEvent listDataEvent) { appendEvent(listDataEvent); } public void intervalAdded(ListDataEvent listDataEvent) { appendEvent(listDataEvent); } public void intervalRemoved(ListDataEvent listDataEvent) { appendEvent(listDataEvent); } private void appendEvent(ListDataEvent listDataEvent) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); switch (listDataEvent.getType()) { case ListDataEvent.CONTENTS_CHANGED: pw.print("Type: Contents Changed"); break; case ListDataEvent.INTERVAL_ADDED: pw.print("Type: Interval Added"); break; case ListDataEvent.INTERVAL_REMOVED: pw.print("Type: Interval Removed"); break; } pw.print(", Index0: " + listDataEvent.getIndex0()); pw.print(", Index1: " + listDataEvent.getIndex1()); DefaultListModel theModel = (DefaultListModel) listDataEvent.getSource(); Enumeration elements = theModel.elements(); pw.print(", Elements: "); while (elements.hasMoreElements()) { pw.print(elements.nextElement()); pw.print(","); } pw.println(); textArea.append(sw.toString()); } }; model.addListDataListener(listDataListener); // Setup buttons JPanel jp = new JPanel(new GridLayout(2, 1)); JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1)); JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 1, 1)); jp.add(jp1); jp.add(jp2); JButton jb = new JButton("add F"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { model.add(0, "First"); } }); jb = new JButton("addElement L"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { model.addElement("Last"); } }); jb = new JButton("insertElementAt M"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); model.insertElementAt("Middle", size / 2); } }); jb = new JButton("set F"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); if (size != 0) model.set(0, "New First"); } }); jb = new JButton("setElementAt L"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); if (size != 0) model.setElementAt("New Last", size - 1); } }); jb = new JButton("load 10"); jp1.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { for (int i = 0, n = labels.length; i < n; i++) { model.addElement(labels[i]); } } }); jb = new JButton("clear"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { model.clear(); } }); jb = new JButton("remove F"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); if (size != 0) model.remove(0); } }); jb = new JButton("removeAllElements"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { model.removeAllElements(); } }); jb = new JButton("removeElement 'Last'"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { model.removeElement("Last"); } }); jb = new JButton("removeElementAt M"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); if (size != 0) model.removeElementAt(size / 2); } }); jb = new JButton("removeRange FM"); jp2.add(jb); jb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { int size = model.getSize(); if (size != 0) model.removeRange(0, size / 2); } }); contentPane.add(jp, BorderLayout.SOUTH); frame.setSize(640, 300); frame.setVisible(true); }
From source file:com.asual.lesscss.LessEngineCli.java
public static void main(String[] args) throws LessException, URISyntaxException { Options cmdOptions = new Options(); cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8."); cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output."); cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files."); cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version."); try {// w ww.j a v a 2 s . c o m CommandLineParser cmdParser = new GnuParser(); CommandLine cmdLine = cmdParser.parse(cmdOptions, args); LessOptions options = new LessOptions(); if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) { options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION)); } if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) { options.setCompress(true); } if (cmdLine.hasOption(LessOptions.CSS_OPTION)) { options.setCss(true); } if (cmdLine.hasOption(LessOptions.LESS_OPTION)) { options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL()); } LessEngine engine = new LessEngine(options); if (System.in.available() != 0) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringWriter sw = new StringWriter(); char[] buffer = new char[1024]; int n = 0; while (-1 != (n = in.read(buffer))) { sw.write(buffer, 0, n); } String src = sw.toString(); if (!src.isEmpty()) { System.out.println(engine.compile(src, null, options.isCompress())); System.exit(0); } } String[] files = cmdLine.getArgs(); if (files.length == 1) { System.out.println(engine.compile(new File(files[0]), options.isCompress())); System.exit(0); } if (files.length == 2) { engine.compile(new File(files[0]), new File(files[1]), options.isCompress()); System.exit(0); } } catch (IOException ioe) { System.err.println("Error opening input file."); } catch (ParseException pe) { System.err.println("Error parsing arguments."); } String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath() .split(File.separator); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions); System.exit(1); }
From source file:Service.java
public static void main(String[] args) { StringWriter sw = new StringWriter(); try {/*w ww . j a v a2s.c o m*/ JsonGenerator g = factory.createGenerator(sw); g.writeStartObject(); g.writeNumberField("code", 200); g.writeArrayFieldStart("languages"); for (Language l : Languages.get()) { g.writeStartObject(); g.writeStringField("name", l.getName()); g.writeStringField("locale", l.getLocaleWithCountryAndVariant().toString()); g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); g.flush(); } catch (Exception e) { throw new RuntimeException(e); } String languagesResponse = sw.toString(); String errorResponse = codeResponse(500); String okResponse = codeResponse(200); Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { try { String line = sc.nextLine(); JsonParser p = factory.createParser(line); String cmd = ""; String text = ""; String language = ""; while (p.nextToken() != JsonToken.END_OBJECT) { String name = p.getCurrentName(); if ("command".equals(name)) { p.nextToken(); cmd = p.getText(); } if ("text".equals(name)) { p.nextToken(); text = p.getText(); } if ("language".equals(name)) { p.nextToken(); language = p.getText(); } } p.close(); if ("check".equals(cmd)) { sw = new StringWriter(); JsonGenerator g = factory.createGenerator(sw); g.writeStartObject(); g.writeNumberField("code", 200); g.writeArrayFieldStart("matches"); for (RuleMatch match : new JLanguageTool(Languages.getLanguageForShortName(language)) .check(text)) { g.writeStartObject(); g.writeNumberField("offset", match.getFromPos()); g.writeNumberField("length", match.getToPos() - match.getFromPos()); g.writeStringField("message", substituteSuggestion(match.getMessage())); if (match.getShortMessage() != null) { g.writeStringField("shortMessage", substituteSuggestion(match.getShortMessage())); } g.writeArrayFieldStart("replacements"); for (String replacement : match.getSuggestedReplacements()) { g.writeString(replacement); } g.writeEndArray(); Rule rule = match.getRule(); g.writeStringField("ruleId", rule.getId()); if (rule instanceof AbstractPatternRule) { String subId = ((AbstractPatternRule) rule).getSubId(); if (subId != null) { g.writeStringField("ruleSubId", subId); } } g.writeStringField("ruleDescription", rule.getDescription()); g.writeStringField("ruleIssueType", rule.getLocQualityIssueType().toString()); if (rule.getUrl() != null) { g.writeArrayFieldStart("ruleUrls"); g.writeString(rule.getUrl().toString()); g.writeEndArray(); } Category category = rule.getCategory(); CategoryId catId = category.getId(); if (catId != null) { g.writeStringField("ruleCategoryId", catId.toString()); g.writeStringField("ruleCategoryName", category.getName()); } g.writeEndObject(); } g.writeEndArray(); g.writeEndObject(); g.flush(); System.out.println(sw.toString()); } else if ("languages".equals(cmd)) { System.out.println(languagesResponse); } else if ("quit".equals(cmd)) { System.out.println(okResponse); return; } else { System.out.println(errorResponse); } } catch (Exception e) { System.out.println(errorResponse); } } }
From source file:DOMGenerate.java
public static void main(String[] argv) { try {//from w ww . j a v a 2s. co m DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElementNS(null, "person"); // Create Root Element Element item = doc.createElementNS(null, "name"); // Create element item.appendChild(doc.createTextNode("Jeff")); root.appendChild(item); // Attach element to Root element item = doc.createElementNS(null, "age"); // Create another Element item.appendChild(doc.createTextNode("28")); root.appendChild(item); // Attach Element to previous element down tree item = doc.createElementNS(null, "height"); item.appendChild(doc.createTextNode("1.80")); root.appendChild(item); // Attach another Element - grandaugther doc.appendChild(root); // Add Root to Document DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS domImplLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer ser = domImplLS.createLSSerializer(); // Create a serializer // for the DOM LSOutput out = domImplLS.createLSOutput(); StringWriter stringOut = new StringWriter(); // Writer will be a String out.setCharacterStream(stringOut); ser.write(doc, out); // Serialize the DOM System.out.println("STRXML = " + stringOut.toString()); // Spit out the // DOM as a String } catch (Exception ex) { ex.printStackTrace(); } }
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 www . j a va2 s. c o m*/ } 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(); } }