List of usage examples for java.io PrintStream PrintStream
public PrintStream(File file) throws FileNotFoundException
From source file:dataflow.examples.DockerClientExample.java
public static void main(String[] args) throws IOException, DockerException, InterruptedException { String localTempDir = createLocalTempDir(); String dockerAddress = "unix:///var/run/docker.sock"; String dockerImage = "ubuntu:latest"; DockerClient dockerClient = new DefaultDockerClient(dockerAddress); String localInput = FilenameUtils.concat(localTempDir, "file_on_host.txt"); PrintStream stream = new PrintStream(localInput); stream.append("\nHello from the host machine.\n"); stream.close();/*from w w w . j a v a 2 s .c o m*/ // Run a simple command in the container to demonstrate we can read the // file mounted from the host. ArrayList<String> command = new ArrayList<String>(); command.add("cat"); command.add("/mounted/file_on_host.txt"); DockerProcessBuilder builder = new DockerProcessBuilder(command, dockerClient); builder.addVolumeMapping(localTempDir, "/mounted"); builder.setImage(dockerImage); // Start and run the container. builder.start(); }
From source file:org.nuxeo.connect.tools.report.viewer.Viewer.java
public static void main(String[] varargs) throws IOException, ParseException { class Arguments { Options options = new Options() .addOption(Option.builder("i").longOpt("input").hasArg().argName("file") .desc("report input file").build()) .addOption(Option.builder("o").longOpt("output").hasArg().argName("file") .desc("thread dump output file").build()); final CommandLine commandline = new DefaultParser().parse(options, varargs); Arguments() throws ParseException { }/*from w w w .ja va2 s .c o m*/ InputStream input() throws IOException { if (!commandline.hasOption('i')) { return System.in; } return Files.newInputStream(Paths.get(commandline.getOptionValue('i'))); } PrintStream output() throws IOException { if (!commandline.hasOption('o')) { return System.out; } return new PrintStream(commandline.getOptionValue('o')); } } Arguments arguments = new Arguments(); final JsonFactory jsonFactory = new JsonFactory(); PrintStream output = arguments.output(); JsonParser parser = jsonFactory.createParser(arguments.input()); ObjectMapper mapper = new ObjectMapper(); while (!parser.isClosed() && parser.nextToken() != JsonToken.NOT_AVAILABLE) { String hostid = parser.nextFieldName(); output.println(hostid); { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("mx-thread-dump".equals(parser.getCurrentName())) { parser.nextToken(); // start mx-thread-dump report while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { parser.nextToken(); printThreadDump(mapper.readTree(parser), output); } else { parser.nextToken(); parser.skipChildren(); } } } else if ("mx-thread-deadlocked".equals(parser.getCurrentName())) { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { if (parser.nextToken() == JsonToken.START_ARRAY) { printThreadDeadlocked(mapper.readerFor(Long.class).readValue(parser), output); } } else { parser.nextToken(); parser.skipChildren(); } } } else if ("mx-thread-monitor-deadlocked".equals(parser.getCurrentName())) { parser.nextToken(); while (parser.nextToken() == JsonToken.FIELD_NAME) { if ("value".equals(parser.getCurrentName())) { if (parser.nextToken() == JsonToken.START_ARRAY) { printThreadMonitorDeadlocked(mapper.readerFor(Long.class).readValues(parser), output); } } else { parser.nextToken(); parser.skipChildren(); } } } else { parser.nextToken(); parser.skipChildren(); } } } } }
From source file:edu.oregonstate.eecs.mcplan.domains.tamarisk.TamariskDataset.java
/** * @param args/* w w w . j ava 2 s. c o m*/ * @throws FileNotFoundException */ public static void main(final String[] args) throws FileNotFoundException { int idx = 0; final int Ninstances = Integer.parseInt(args[idx++]); System.out.println("Ninstances = " + Ninstances); final int Nreaches = Integer.parseInt(args[idx++]); System.out.println("Nreaches = " + Nreaches); final int Nhabitats = Integer.parseInt(args[idx++]); System.out.println("Nhabitats = " + Nhabitats); final int seed = Integer.parseInt(args[idx++]); System.out.println("seed = " + seed); final String out_filename = args[idx++]; System.out.println("out_filename = " + out_filename); final RandomGenerator rng = new MersenneTwister(seed); final Csv.Writer writer = new Csv.Writer(new PrintStream(new File(out_filename))); writer.cell("Nreaches").cell("Nhabitats"); for (int r = 0; r < Nreaches; ++r) { for (int h = 0; h < Nhabitats; ++h) { writer.cell("r" + r + "h" + h); } } writer.newline(); for (int i = 0; i < Ninstances; ++i) { final TamariskParameters params = new TamariskParameters(rng, Nreaches, Nhabitats); final DirectedGraph<Integer, DefaultEdge> g = params.createBalancedGraph(2); final TamariskState s = new TamariskState(rng, params, g); writer.cell(Nreaches).cell(Nhabitats); for (int r = 0; r < Nreaches; ++r) { for (int h = 0; h < Nhabitats; ++h) { writer.cell(s.habitats[r][h]); } } writer.newline(); } }
From source file:ShowImage.java
public static void main(String args[]) throws IOException { List<File> files = ImageIOUtils.getFiles(args, new String[] { "ntf", "nsf" }); for (Iterator iter = files.iterator(); iter.hasNext();) { try {/*from w ww .j av a2s . co m*/ File file = (File) iter.next(); log.debug("Reading: " + file.getAbsolutePath()); NITFReader imageReader = (NITFReader) ImageIOUtils.getImageReader("nitf", file); for (int i = 0; i < imageReader.getRecord().getImages().length; ++i) { log.debug(file.getName() + "[" + i + "]"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageSubheader subheader = imageReader.getRecord().getImages()[i].getSubheader(); subheader.print(new PrintStream(stream)); log.debug(stream.toString()); try { int numBands = subheader.getBandCount(); String irep = subheader.getImageRepresentation().getStringData().trim(); int bitsPerPixel = subheader.getNumBitsPerPixel().getIntData(); int nBytes = (bitsPerPixel - 1) / 8 + 1; if (irep.equals("RGB") && numBands == 3) { BufferedImage image = imageReader.read(i); ImageIOUtils.showImage(image, file.getName() + "[" + i + "]", true); } else { // read each band, separately for (int j = 0; j < numBands; ++j) { if (nBytes == 1 || nBytes == 2 || nBytes == 4 || nBytes == 8) { ImageReadParam readParam = imageReader.getDefaultReadParam(); readParam.setSourceBands(new int[] { j }); BufferedImage image = imageReader.read(i, readParam); ImageIOUtils.showImage(image, file.getName() + "[" + i + "][" + j + "]", true); ImageIO.write(image, "jpg", new FileOutputStream("image" + i + "_" + j + ".jpg")); // downsample // readParam.setSourceSubsampling(2, 2, 0, // 0); // BufferedImage smallerImage = imageReader // .read(i, readParam); // // ImageIOUtils.showImage(smallerImage, // "DOWNSAMPLED: " + file.getName()); } } } } catch (Exception e) { System.out.println(ExceptionUtils.getStackTrace(e)); log.error(ExceptionUtils.getStackTrace(e)); } } } catch (Exception e) { log.debug(ExceptionUtils.getStackTrace(e)); } } }
From source file:net.chrislongo.hls.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {//from ww w .j av a 2s.c o m String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:android.example.hlsmerge.crypto.Main.java
public static void main(String[] args) { CommandLine commandLine = parseCommandLine(args); String[] commandLineArgs = commandLine.getArgs(); try {//from ww w .ja v a2s . c o m String playlistUrl = commandLineArgs[0]; String outFile = null; String key = null; if (commandLine.hasOption(OPT_OUT_FILE)) { outFile = commandLine.getOptionValue(OPT_OUT_FILE); File file = new File(outFile); if (file.exists()) { if (!commandLine.hasOption(OPT_OVERWRITE)) { System.out.printf("File '%s' already exists. Overwrite? [y/N] ", outFile); int ch = System.in.read(); if (!(ch == 'y' || ch == 'Y')) { System.exit(0); } } file.delete(); } } if (commandLine.hasOption(OPT_KEY)) key = commandLine.getOptionValue(OPT_KEY); PlaylistDownloader downloader = new PlaylistDownloader(playlistUrl, null); if (commandLine.hasOption(OPT_SILENT)) { System.setOut(new PrintStream(new OutputStream() { public void close() { } public void flush() { } public void write(byte[] b) { } public void write(byte[] b, int off, int len) { } public void write(int b) { } })); } downloader.download(outFile, key); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:net.sf.jvifm.Main.java
public static void main(String[] args) { initConfigDir();//from www . ja va 2 s .c o m boolean locked = createFileLock(); if (!locked) return; initCommandRegister(); initServer(); initSysExeNameList(); try { File logFile = new File(HomeLocator.getConfigHome() + File.separator + "jvifm.log"); PrintStream ps = new PrintStream(new FileOutputStream(logFile)); //System.setOut(ps); //System.setErr(ps); } catch (Exception e) { e.printStackTrace(); } display = new Display(); fileManager = new FileManager(); shell = fileManager.open(display); String[][] panelDirs = AppStatus.loadAppStatus(); if (!(panelDirs == null) && panelDirs.length > 0) { for (int i = 0; i < panelDirs.length; i++) { String leftPath = FileLister.FS_ROOT; String rightPath = FileLister.FS_ROOT; if (panelDirs[i][0] != null && new File(panelDirs[i][0]).isDirectory()) { leftPath = panelDirs[i][0]; } if (panelDirs[i][1] != null && new File(panelDirs[i][1]).isDirectory()) { rightPath = panelDirs[i][1]; } fileManager.tabnew(leftPath, rightPath); } } else { fileManager.tabnew(FileLister.FS_ROOT, FileLister.FS_ROOT); } while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } }
From source file:de.peran.DependencyReadingStarter.java
public static void main(final String[] args) throws ParseException, FileNotFoundException { final Options options = OptionConstants.createOptions(OptionConstants.FOLDER, OptionConstants.STARTVERSION, OptionConstants.ENDVERSION, OptionConstants.OUT); final CommandLineParser parser = new DefaultParser(); final CommandLine line = parser.parse(options, args); final File projectFolder = new File(line.getOptionValue(OptionConstants.FOLDER.getName())); final File dependencyFile; if (line.hasOption(OptionConstants.OUT.getName())) { dependencyFile = new File(line.getOptionValue(OptionConstants.OUT.getName())); } else {/* ww w.j a v a2 s .c o m*/ dependencyFile = new File("dependencies.xml"); } File outputFile = projectFolder.getParentFile(); if (outputFile.isDirectory()) { outputFile = new File(projectFolder.getParentFile(), "ausgabe.txt"); } LOG.debug("Lese {}", projectFolder.getAbsolutePath()); final VersionControlSystem vcs = VersionControlSystem.getVersionControlSystem(projectFolder); System.setOut(new PrintStream(outputFile)); // System.setErr(new PrintStream(outputFile)); final DependencyReader reader; if (vcs.equals(VersionControlSystem.SVN)) { final String url = SVNUtils.getInstance().getWCURL(projectFolder); final List<SVNLogEntry> entries = getSVNCommits(line, url); LOG.debug("SVN commits: " + entries.stream().map(entry -> entry.getRevision()).collect(Collectors.toList())); reader = new DependencyReader(projectFolder, url, dependencyFile, entries); } else if (vcs.equals(VersionControlSystem.GIT)) { final List<GitCommit> commits = getGitCommits(line, projectFolder); reader = new DependencyReader(projectFolder, dependencyFile, commits); LOG.debug("Reader initalized"); } else { throw new RuntimeException("Unknown version control system"); } reader.readDependencies(); }
From source file:jk.kamoru.test.IMAPMail.java
public static void main(String[] args) { /* if (args.length < 3) {// w w w . j av a2 s . c om System.err.println( "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1); } */ String server = "imap.handysoft.co.kr"; String username = "namjk24@handysoft.co.kr"; String password = "22222"; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); File imap_log_file = new File("IMAMP-UNSEEN"); try { System.out.println(imap_log_file.getAbsolutePath()); PrintStream ps = new PrintStream(imap_log_file); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(ps, true)); } catch (FileNotFoundException e1) { imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); } try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); // imap.capability(); // imap.select("inbox"); // imap.examine("inbox"); imap.status("inbox", new String[] { "UNSEEN" }); // imap.logout(); imap.disconnect(); List<String> imap_log = FileUtils.readLines(imap_log_file); for (int i = 0; i < imap_log.size(); i++) { System.out.println(i + ":" + imap_log.get(i)); } String unseenText = imap_log.get(4); unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')')); int unseenCount = Integer.parseInt(unseenText.split(" ")[1]); System.out.println(unseenCount); //imap_log.indexOf("UNSEEN ") } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }
From source file:ca.uqac.dim.mapreduce.ltl.LTLValidation.java
/** * Program entry point./*w ww.j av a 2 s. c o m*/ * @param args Command-line arguments */ @SuppressWarnings("static-access") public static void main(String[] args) { // Define and process command line arguments Options options = new Options(); HelpFormatter help_formatter = new HelpFormatter(); Option opt; options.addOption("h", "help", false, "Show help"); opt = OptionBuilder.withArgName("property").hasArg() .withDescription("Property to verify, enclosed in double quotes").create("p"); options.addOption(opt); opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename").create("i"); options.addOption(opt); opt = OptionBuilder.withArgName("x").hasArg() .withDescription("Set verbosity level to x (default: 0 = quiet)").create("v"); options.addOption(opt); opt = OptionBuilder.withArgName("ParserType").hasArg().withDescription("Parser type (Dom or Sax)") .create("t"); options.addOption(opt); opt = OptionBuilder.withLongOpt("redirection").withArgName("x").hasArg() .withDescription("Set the redirection file for the System.out").create("r"); options.addOption(opt); CommandLine c_line = parseCommandLine(options, args); String redirectionFile = ""; //Contains a redirection file for the output if (c_line.hasOption("redirection")) { try { redirectionFile = c_line.getOptionValue("redirection"); PrintStream ps; ps = new PrintStream(redirectionFile); System.setOut(ps); } catch (FileNotFoundException e) { System.out.println("Redirection error !!!"); e.printStackTrace(); } } if (!c_line.hasOption("p") || !c_line.hasOption("i") | c_line.hasOption("h")) { help_formatter.printHelp(app_name, options); System.exit(1); } assert c_line.hasOption("p"); assert c_line.hasOption("i"); String trace_filename = c_line.getOptionValue("i"); String trace_format = getExtension(trace_filename); String property_str = c_line.getOptionValue("p"); String ParserType = ""; if (c_line.hasOption("t")) { ParserType = c_line.getOptionValue("t"); } else { System.err.println("No Parser Type in Arguments"); System.exit(ERR_ARGUMENTS); } if (c_line.hasOption("v")) m_verbosity = Integer.parseInt(c_line.getOptionValue("v")); // Obtain the property to verify and break into subformulas Operator property = null; try { int preset = Integer.parseInt(property_str); property = new Edoc2012Presets().property(preset); } catch (NumberFormatException e) { try { property = Operator.parseFromString(property_str); } catch (Operator.ParseException pe) { System.err.println("ERROR: parsing"); System.exit(1); } } Set<Operator> subformulas = property.getSubformulas(); // Initialize first collector depending on input file format int max_loops = property.getDepth(); int max_tuples_total = 0, total_tuples_total = 0; long time_begin = System.nanoTime(); TraceCollector initial_collector = null; { File in_file = new File(trace_filename); if (trace_format.compareToIgnoreCase(".txt") == 0) { initial_collector = new CharacterTraceCollector(in_file, subformulas); } else if (trace_format.compareToIgnoreCase(".xml") == 0) { if (ParserType.equals("Dom")) { initial_collector = new XmlDomTraceCollector(in_file, subformulas); } else if (ParserType.equals("Sax")) { initial_collector = new XmlSaxTraceCollector(in_file, subformulas); } else { initial_collector = new XmlSaxTraceCollector(in_file, subformulas); } } } if (initial_collector == null) { System.err.println("ERROR: unrecognized input format"); System.exit(1); } // Start workflow int trace_len = initial_collector.getTraceLength(); InCollector<Operator, LTLTupleValue> loop_collector = initial_collector; print(System.out, property.toString(), 2); print(System.out, loop_collector.toString(), 3); for (int i = 0; i < max_loops; i++) { print(System.out, "Loop " + i, 2); LTLSequentialWorkflow w = new LTLSequentialWorkflow(new LTLMapper(subformulas), new LTLReducer(subformulas, trace_len), loop_collector); loop_collector = w.run(); max_tuples_total += w.getMaxTuples(); total_tuples_total += w.getTotalTuples(); if (m_verbosity >= 3) { print(System.out, loop_collector.toString(), 3); } } boolean result = getVerdict(loop_collector, property); long time_end = System.nanoTime(); if (result) print(System.out, "Formula is true", 1); else print(System.out, "Formula is false", 1); long time_total = (time_end - time_begin) / 1000000; System.out.println(trace_len + "," + max_tuples_total + "," + total_tuples_total + "," + time_total); }