List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file) throws FileNotFoundException
From source file:lambertmrev.LambertMRev.java
/** * @param args the command line arguments */// ww w .j a v a 2s .c om public static void main(String[] args) { // Want to test the Lambert class so you can specify the number of revs for which to compute //System.out.print("this is the frames tutorial \n"); try { Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getTAI(); AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, utc); double mu = 3.986004415e+14; double a = 24396159; // semi major axis in meters double e = 0.72831215; // eccentricity double i = Math.toRadians(7); // inclination double omega = Math.toRadians(180); // perigee argument double raan = Math.toRadians(261); // right ascension of ascending node double lM = 0; // mean anomaly Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame, initialDate, mu); //KeplerianPropagator kepler = new KeplerianPropagator(initialOrbit); // set geocentric positions Vector3D r1 = new Vector3D(-6.88999e3, 3.92763e4, 2.67053e3); Vector3D r2 = new Vector3D(-3.41458e4, 2.05328e4, 3.44315e3); Vector3D r1_site = new Vector3D(4.72599e3, 1.26633e3, 4.07799e3); Vector3D r2_site = new Vector3D(4.70819e3, 1.33099e3, 4.07799e3); // get the topocentric positions Vector3D top1 = Transform.geo2radec(r1.scalarMultiply(1000), r1_site.scalarMultiply(1000)); Vector3D top2 = Transform.geo2radec(r2.scalarMultiply(1000), r2_site.scalarMultiply(1000)); // time of flight in seconds double tof = 3 * 3600; // propagate to 0 and tof Lambert test = new Lambert(); boolean cw = false; int multi_revs = 1; RealMatrix v1_mat; Random randomGenerator = new Random(); PrintWriter out_a = new PrintWriter("out_java_a.txt"); PrintWriter out_e = new PrintWriter("out_java_e.txt"); PrintWriter out_rho1 = new PrintWriter("out_java_rho1.txt"); PrintWriter out_rho2 = new PrintWriter("out_java_rho2.txt"); // start the loop double A, Ecc, rho1, rho2, tof_hyp; long time1 = System.nanoTime(); for (int ll = 0; ll < 1e6; ll++) { rho1 = top1.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top1.getZ() / 1000; rho2 = top2.getZ() / 1000 + 1e-3 * randomGenerator.nextGaussian() * top2.getZ() / 1000; //tof_hyp = FastMath.abs(tof + 0.1*3600 * randomGenerator.nextGaussian()); // from topo to geo Vector3D r1_hyp = Transform.radec2geo(top1.getX(), top1.getY(), rho1, r1_site); Vector3D r2_hyp = Transform.radec2geo(top2.getX(), top2.getY(), rho2, r2_site); // System.out.println(r1_hyp.scalarMultiply(1000).getNorm()); // System.out.println(r2_hyp.scalarMultiply(1000).getNorm()); // System.out.println(tof/3600); test.lambert_problem(r1_hyp.scalarMultiply(1000), r2_hyp.scalarMultiply(1000), tof, mu, cw, multi_revs); v1_mat = test.get_v1(); Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2)); // System.out.println(v1); PVCoordinates rv1 = new PVCoordinates(r1_hyp.scalarMultiply(1000), v1); Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu); A = orbit_out.getA(); Ecc = orbit_out.getE(); // System.out.println(ll + " - " +A); out_a.println(A); out_e.println(Ecc); out_rho1.println(rho1); out_rho2.println(rho2); } long time2 = System.nanoTime(); long timeTaken = time2 - time1; out_a.close(); out_e.close(); out_rho1.close(); out_rho2.close(); System.out.println("Time taken " + timeTaken / 1000 / 1000 + " milli secs"); // get the truth test.lambert_problem(r1.scalarMultiply(1000), r2.scalarMultiply(1000), tof, mu, cw, multi_revs); v1_mat = test.get_v1(); Vector3D v1 = new Vector3D(v1_mat.getEntry(0, 0), v1_mat.getEntry(0, 1), v1_mat.getEntry(0, 2)); PVCoordinates rv1 = new PVCoordinates(r1.scalarMultiply(1000), v1); Orbit orbit_out = new KeplerianOrbit(rv1, inertialFrame, initialDate, mu); //System.out.println(orbit_out.getA()); } catch (FileNotFoundException ex) { Logger.getLogger(LambertMRev.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java
public static void main(String[] args) throws IOException, GtfsException { final String url = args[0]; final String key = args[1]; final String gtfsFile = args[2]; final String out = args[3].replaceAll("/$", ""); final Map<String, String> agencyMapping = new HashMap<String, String>(); agencyMapping.put("1", "2"); final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping); oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key); gson = OneBusAwayGsonFactory.newInstance(true); final Calendar end = Calendar.getInstance(); end.set(2013, 11, 22, 0, 0);//from www . j a va 2s .c o m final Calendar start = Calendar.getInstance(); start.set(2013, 10, 4, 0, 0); final Calendar current = Calendar.getInstance(); current.setTime(start.getTime()); while (current.before(end) || current.equals(end)) { System.out.println(current.getTime()); for (final Stop stop : gtfs.getAllStops()) { final String stopId = stop.getId().toString(); final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH)); final String methodDir = String.format("%s/schedule-for-stop", out); final File outDir = new File(String.format("%s/%s", methodDir, dateDir)); outDir.mkdirs(); final File f = new File(outDir, String.format("%s.json", stopId)); final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime()); final String json = gson.toJson(ss); final Writer w = new PrintWriter(f); w.write(json); w.close(); } current.add(Calendar.DAY_OF_MONTH, 1); } final File outDir = new File(String.format("%s/trip-details", out)); outDir.mkdirs(); for (final Trip trip : gtfs.getAllTrips()) { final String tripId = trip.getId().toString(); final File f = new File(outDir, String.format("%s.json", tripId)); final TripSchedule ts = oba.getTripDetails(tripId); final String json = gson.toJson(ts); final Writer w = new PrintWriter(f); w.write(json); w.close(); } }
From source file:gobblin.compaction.hive.CompactionRunner.java
public static void main(String[] args) throws IOException, ConfigurationException { properties = CliOptions.parseArgs(MRCompactionRunner.class, args); File compactionConfigDir = new File(properties.getProperty(COMPACTION_CONFIG_DIR)); File[] listOfFiles = compactionConfigDir.listFiles(); if (listOfFiles == null || listOfFiles.length == 0) { System.err.println("No compaction configuration files found under " + compactionConfigDir); System.exit(1);/* ww w. j a v a 2 s . com*/ } int numOfJobs = 0; for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { numOfJobs++; } } LOG.info("Found " + numOfJobs + " compaction tasks."); try (PrintWriter pw = new PrintWriter(new OutputStreamWriter( new FileOutputStream(properties.getProperty(TIMING_FILE, TIMING_FILE_DEFAULT)), Charset.forName("UTF-8")))) { for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { Configuration jobConfig = new PropertiesConfiguration(file.getAbsolutePath()); jobProperties = ConfigurationConverter.getProperties(jobConfig); long startTime = System.nanoTime(); compact(); long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; double seconds = TimeUnit.NANOSECONDS.toSeconds(elapsedTime); pw.printf("%s: %f%n", file.getAbsolutePath(), seconds); } } } }
From source file:com.xiangzhurui.util.email.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin;//from www . jav a 2 s.c o m FileReader fileReader = null; Writer writer; SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } System.out.print("Filename: "); System.out.flush(); filename = stdin.readLine(); try { fileReader = new FileReader(filename); } catch (FileNotFoundException e) { System.err.println("File not found. " + e.getMessage()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:gobblin.compaction.CompactionRunner.java
public static void main(String[] args) throws ConfigurationException, IOException, SQLException { if (args.length != 1) { LOG.info("Proper usage: java -jar compaction.jar <global-config-file>\n" + "or\n" + "hadoop jar compaction.jar <global-config-file>\n" + "or\n" + "yarn jar compaction.jar <global-config-file>\n"); System.exit(1);/*ww w. j a v a 2s . c om*/ } Configuration globalConfig = new PropertiesConfiguration(args[0]); properties = ConfigurationConverter.getProperties(globalConfig); File compactionConfigDir = new File(properties.getProperty(COMPACTION_CONFIG_DIR)); File[] listOfFiles = compactionConfigDir.listFiles(); if (listOfFiles == null || listOfFiles.length == 0) { System.err.println("No compaction configuration files found under " + compactionConfigDir); System.exit(1); } int numOfJobs = 0; for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { numOfJobs++; } } LOG.info("Found " + numOfJobs + " compaction tasks."); PrintWriter pw = new PrintWriter(new OutputStreamWriter( new FileOutputStream(properties.getProperty(TIMING_FILE, TIMING_FILE_DEFAULT)), Charset.forName("UTF-8"))); for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { Configuration jobConfig = new PropertiesConfiguration(file.getAbsolutePath()); jobProperties = ConfigurationConverter.getProperties(jobConfig); long startTime = System.nanoTime(); compact(); long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; double seconds = TimeUnit.NANOSECONDS.toSeconds(elapsedTime); pw.printf("%s: %f%n", file.getAbsolutePath(), seconds); } } pw.close(); }
From source file:ThreadLister.java
/** * The main() method create a simple graphical user interface to display the * threads in. This allows us to see the "event dispatch thread" used by AWT * and Swing./* w w w. j a v a 2 s . c o m*/ */ public static void main(String[] args) { // Create a simple Swing GUI JFrame frame = new JFrame("ThreadLister Demo"); JTextArea textarea = new JTextArea(); frame.getContentPane().add(new JScrollPane(textarea), BorderLayout.CENTER); frame.setSize(500, 400); frame.setVisible(true); // Get the threadlisting as a string using a StringWriter stream StringWriter sout = new StringWriter(); // To capture the listing PrintWriter out = new PrintWriter(sout); ThreadLister.listAllThreads(out); // List threads to stream out.close(); String threadListing = sout.toString(); // Get listing as a string // Finally, display the thread listing in the GUI textarea.setText(threadListing); }
From source file:HSqlPrimerDesign.java
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, InstantiationException, SQLException, FileNotFoundException { Class.forName(JDBC_DRIVER_HSQL).newInstance(); conn = DriverManager.getConnection(DB_SERVER_URL, USER, PASS); PrintWriter log = new PrintWriter(new File("javalog.log")); DpalLoad.main(args);/*from ww w . j av a2 s .c om*/ Dpal_Inst = DpalLoad.INSTANCE_WIN64; // int[][] arr =calcHairpin("GGGGGGCCCCCCCCCCCCGGGGGGG",4); // if(arr.length<=1){ // System.out.println("No Hairpin's found"); // }else{ // System.out.println("Hairpin(s) found"); // } Statement stat = conn.createStatement(); ResultSet call = stat.executeQuery( "Select * From " + "Primerdb.primers where Cluster ='A1' and UniqueP =True and Bp = 20"); Set<CharSequence> primers = new HashSet<>(); while (call.next()) { primers.add(call.getString("Sequence")); } // primers.stream().forEach(x->{ // log.println(x); // log.println(complementarity(x, x, Dpal_Inst)); // int[][] arr =calcHairpin((String)x,4); // if(arr.length<=1){ // log.println("No Hairpin's found"); // }else{ // log.println("Hairpin(s) found"); // } // log.println(); // log.flush(); // }); }
From source file:ProductionJS.java
/** * @param args// w w w .j a va 2s . co m */ public static void main(String[] args) { boolean precondition = true; BackupLog backupLog = new BackupLog("log/backupLog.txt"); Property properties = null; Settings settings = null; // Load main cfg file try { properties = new Property("cfg/cfg"); } catch (IOException e) { backupLog.log("ERROR : Config file not found"); precondition = false; } // Load cfg for Log4J if (precondition) { try { DOMConfigurator.configureAndWatch(properties.getProperty("loggerConfiguration")); logger.info("ProductionJS is launched\n_______________________"); } catch (Exception e) { backupLog.log(e.getMessage()); precondition = false; } } // Load settings for current execution if (precondition) { try { settings = new Settings(new File(properties.getProperty("importConfiguration"))); } catch (IOException e) { logger.error("Properties file not found"); precondition = false; } catch (org.json.simple.parser.ParseException e) { logger.error("Properties file reading error : JSON may be invalid, check it!"); precondition = false; } } // All is OK : GO! if (precondition) { logger.info("Configuration OK"); logger.info("\"_______________________\nConcat BEGIN\n_______________________\n"); Concat concat = new Concat(); try { if (settings.getPrior() != null) { logger.info("Add Prior files\n_______________________\n"); concat.addJSONArray(settings.getPrior()); } for (int i = 0; i < settings.getIn().size(); i++) { ProductionJS.logger.info("Importation number " + (i + 1)); ProductionJS.logger.info("Directory imported " + settings.getIn().get(i)); Directory dir = new Directory(new File(settings.getIn().get(i).toString())); dir.scan(); concat.add(dir.getFiles()); } concat.output(settings.getOut()); logger.info("\"_______________________\nConcat END\n_______________________\n"); if (settings.getMinify() != null && settings.getMinify() == true) { logger.info( "\"_______________________\nMinify of concatened file BEGIN\n_______________________\n"); new Minify(new File(settings.getOut()), settings.getOut()); logger.info( "\"_______________________\nMinify of concatened file END\n_______________________\n"); } if (settings.getLicense() != null) { logger.info("Add License\n_______________________\n"); concat = new Concat(); UUID uniqueID = UUID.randomUUID(); PrintWriter tmp = new PrintWriter(uniqueID.toString() + ".txt"); tmp.println(settings.getLicense()); tmp.close(); File license = new File(uniqueID.toString() + ".txt"); concat.add(license); File out = new File(settings.getOut()); File tmpOut = new File(uniqueID + out.getName()); out.renameTo(tmpOut); concat.add(tmpOut); concat.output(settings.getOut()); license.delete(); tmpOut.delete(); } } catch (IOException e) { StackTrace stackTrace = new StackTrace(e.getStackTrace()); logger.error("An error occurred " + e.getMessage() + " " + stackTrace.toString()); } } }
From source file:org.kuali.student.git.importer.GitImporterMain.java
/** * @param args/*w w w . j av a2 s .c o m*/ */ public static void main(final String[] args) { if (args.length != 8 && args.length != 9) { log.error( "USAGE: <svn dump file> <git repository> <veto.log> <skipped-copy-from.log> <blob.log> <gc enabled> <svn repo base url> <repo uuid> [<git command path>]"); log.error("\t<veto.log> : which paths were veto's as not being a valid branch"); log.error("\t<skipped-copy-from.log> : which copy-from-paths were skipped"); log.error("\t<blob.log> : issues related to blobs (typically directory copy related)"); log.error("\t<gc enabled> : set to 1 (true ever 500 revs) or 0 (false) to disable"); log.error("\t<svn repo base url> : the svn repo base url to use in the git-svn-id"); log.error( "\t<repo uuid> : The svn repository uuid to use in the git-svn-id.\n\tIt you are importing from a clone use this to set the field to the real repositories uuid."); log.error("\t<git command path> : the path to a native git to use for gc's which occur every 500 revs"); System.exit(-1); } try { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext( "GitImporterMain-applicationContext.xml"); applicationContext.registerShutdownHook(); SvnDumpFilter filter = applicationContext.getBean(SvnDumpFilter.class); BranchDetector branchDetector = applicationContext.getBean("branchDetector", BranchDetector.class); // final MergeDetectorData detectorData = applicationContext // .getBean(MergeDetectorData.class); File dumpFile = new File(args[0]); if (!dumpFile.exists()) { throw new FileNotFoundException(args[0] + " path not found"); } File gitRepository = new File(args[1]).getAbsoluteFile(); if (!gitRepository.getParentFile().exists()) throw new FileNotFoundException(args[1] + "path not found"); final PrintWriter vetoLog = new PrintWriter(args[2]); final PrintWriter copyFromSkippedLog = new PrintWriter(args[3]); final PrintWriter blobLog = new PrintWriter(args[4]); boolean gcEnabled = true; final boolean printGitSvnIds = true; // not optional anymore String repositoryBaseUrl = null; String repositoryUUID = null; if (args[5].trim().equals("0")) gcEnabled = false; repositoryBaseUrl = args[6].trim(); repositoryUUID = args[7].trim(); String nativeGitCommandPath = null; if (args.length == 9) nativeGitCommandPath = args[8].trim(); final Repository repo = GitRepositoryUtils.buildFileRepository(gitRepository, false); // extract any known branches from the repository BZip2CompressorInputStream compressedInputStream = new BZip2CompressorInputStream( new FileInputStream(dumpFile)); filter.parseDumpFile(compressedInputStream, new GitImporterParseOptions(repo, vetoLog, copyFromSkippedLog, blobLog, printGitSvnIds, repositoryBaseUrl, repositoryUUID, branchDetector, gcEnabled, nativeGitCommandPath)); vetoLog.close(); copyFromSkippedLog.close(); blobLog.close(); compressedInputStream.close(); } catch (Exception e) { log.error("Processing failed", e); } }
From source file:glacierpipe.GlacierPipeMain.java
public static void main(String[] args) throws IOException, ParseException { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(OPTIONS, args); if (cmd.hasOption("help")) { try (PrintWriter writer = new PrintWriter(System.err)) { printHelp(writer);/*from www . ja v a 2s . co m*/ } System.exit(0); } else if (cmd.hasOption("upload")) { // Turn the CommandLine into Properties Properties cliProperties = new Properties(); for (Iterator<?> i = cmd.iterator(); i.hasNext();) { Option o = (Option) i.next(); String opt = o.getLongOpt(); opt = opt != null ? opt : o.getOpt(); String value = o.getValue(); value = value != null ? value : ""; cliProperties.setProperty(opt, value); } // Build up a configuration ConfigBuilder configBuilder = new ConfigBuilder(); // Archive name List<?> archiveList = cmd.getArgList(); if (archiveList.size() > 1) { throw new ParseException("Too many arguments"); } else if (archiveList.isEmpty()) { throw new ParseException("No archive name provided"); } configBuilder.setArchive(archiveList.get(0).toString()); // All other arguments on the command line configBuilder.setFromProperties(cliProperties); // Load any config from the properties file Properties fileProperties = new Properties(); try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) { fileProperties.load(in); } catch (IOException e) { System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile, e); } configBuilder.setFromProperties(fileProperties); // ... Config config = new Config(configBuilder); IOBuffer buffer = new MemoryIOBuffer(config.partSize); AmazonGlacierClient client = new AmazonGlacierClient( new BasicAWSCredentials(config.accessKey, config.secretKey)); client.setEndpoint(config.endpoint); // Actual upload try (InputStream in = new BufferedInputStream(System.in, 4096); PrintWriter writer = new PrintWriter(System.err); ObservableProperties configMonitor = config.reloadProperties ? new ObservableProperties(config.propertiesFile) : null; ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) { TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer); if (configMonitor != null) { configMonitor.registerObserver(throttlingStrategy); } GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy); pipe.pipe(client, config.vault, config.archive, in); } catch (Exception e) { e.printStackTrace(System.err); } System.exit(0); } else { try (PrintWriter writer = new PrintWriter(System.err)) { writer.println("No action specified."); printHelp(writer); } System.exit(-1); } }