List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:se.berazy.api.examples.App.java
/** * Operation examples.//from w w w .j a v a 2s .c o m * @param args */ public static void main(String[] args) { Scanner scanner = null; try { client = new BookkeepingClient(); System.out.println("Choose operation to invoke:\n"); System.out.println("1. Create invoice"); System.out.println("2. Credit invoice"); scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); line = (line != null) ? line.trim().toLowerCase() : ""; if (line.equals("1")) { outPutResponse(createInvoice()); } else if (line.equals("2")) { outPutResponse(creditInvoice()); } else if (line.equals("q") || line.equals("quit") || line.equals("exit")) { System.exit(0); } else { System.out.println("\nPlease choose an operation from 1-7."); } } scanner.close(); } catch (Exception ex) { System.out.println(String.format( "\nAn exception occured, press CTRL+C to exit or enter 'q', 'quit' or 'exit'.\n\nException: %s %s", ex.getMessage(), ex.getStackTrace())); } finally { if (scanner != null) { scanner.close(); } } }
From source file:mamo.vanillaVotifier.VanillaVotifier.java
public static void main(String[] args) { String[] javaVersion = System.getProperty("java.version").split("\\."); if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2 && Integer.parseInt(javaVersion[1]) >= 6)) { System.out.println(("You need at least Java 1.6 to run this program! Current version: " + System.getProperty("java.version") + ".")); return;//from w ww . j a v a 2 s.c o m } VanillaVotifier votifier = new VanillaVotifier(); for (String arg : args) { if (arg.equalsIgnoreCase("-report-exceptions")) { votifier.reportExceptions = true; } else if (arg.equalsIgnoreCase("-help")) { votifier.getLogger().printlnTranslation("s58"); return; } else { votifier.getLogger().printlnTranslation("s55", new AbstractMap.SimpleEntry<String, Object>("option", arg)); return; } } votifier.getLogger().printlnTranslation("s42"); if (!(loadConfig(votifier) && startServer(votifier))) { return; } Scanner in = new Scanner(System.in); while (true) { String command; try { command = in.nextLine(); } catch (NoSuchElementException e) { // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring. continue; } catch (Exception e) { votifier.getLogger().printlnTranslation("s57", new AbstractMap.SimpleEntry<String, Object>("exception", e)); if (!stopServer(votifier)) { System.exit(0); // "return" somehow isn't enough. } return; } if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) { if (command.split(" ").length == 1) { stopServer(votifier); break; } else { votifier.getLogger().printlnTranslation("s17"); } } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) { if (command.split(" ").length == 1) { Listener listener = new Listener() { @Override public void onEvent(Event event, VanillaVotifier votifier) { if (event instanceof ServerStoppedEvent) { if (loadConfig((VanillaVotifier) votifier) && startServer((VanillaVotifier) votifier)) { votifier.getServer().getListeners().remove(this); } else { System.exit(0); } } } }; votifier.getServer().getListeners().add(listener); if (!stopServer(votifier)) { // Kill the process if the server doesn't stop System.exit(0); // "return" somehow isn't enough. return; } } else { votifier.getLogger().printlnTranslation("s56"); } } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) { String[] commandArgs = command.split(" "); int keySize; if (commandArgs.length == 1) { keySize = 2048; } else if (commandArgs.length == 2) { try { keySize = Integer.parseInt(commandArgs[1]); } catch (NumberFormatException e) { votifier.getLogger().printlnTranslation("s19"); continue; } if (keySize < 512) { votifier.getLogger().printlnTranslation("s51"); continue; } if (keySize > 16384) { votifier.getLogger().printlnTranslation("s52"); continue; } } else { votifier.getLogger().printlnTranslation("s20"); continue; } votifier.getLogger().printlnTranslation("s16"); votifier.getConfig().genKeyPair(keySize); try { votifier.getConfig().save(); } catch (Exception e) { votifier.getLogger().printlnTranslation("s21", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } votifier.getLogger().printlnTranslation("s23"); } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) { String[] commandArgs = command.split(" "); if (commandArgs.length == 2) { try { votifier.getTester().testVote(new Vote("TesterService", commandArgs[1], votifier.getConfig().getInetSocketAddress().getAddress().getHostName())); } catch (Exception e) { // GeneralSecurityException, IOException votifier.getLogger().printlnTranslation("s27", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } } else { votifier.getLogger().printlnTranslation("s26"); } } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) { if (command.split(" ").length >= 2) { try { votifier.getTester() .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n")); } catch (Exception e) { // GeneralSecurityException, IOException votifier.getLogger().printlnTranslation("s35", new AbstractMap.SimpleEntry<String, Object>("exception", e)); } } else { votifier.getLogger().printlnTranslation("s34"); } } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s31"); } else { votifier.getLogger().printlnTranslation("s32"); } } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s36"); } else { votifier.getLogger().printlnTranslation("s37"); } } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s40"); } else { votifier.getLogger().printlnTranslation("s41"); } } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) { if (command.split(" ").length == 1) { votifier.getLogger().printlnTranslation("s43"); } else { votifier.getLogger().printlnTranslation("s44"); } } else { votifier.getLogger().printlnTranslation("s33"); } } }
From source file:gentracklets.GenTracklets.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();// w w w . j a va 2 s. co m DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 0.4; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); propagator.addForceModel(srp); propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(3); startDates.setElementAt(new AbsoluteDate(2015, 12, 8, 20, 00, 00, utc), 0); startDates.setElementAt(new AbsoluteDate(2015, 12, 9, 21, 00, 00, utc), 1); startDates.setElementAt(new AbsoluteDate(2015, 12, 10, 22, 00, 00, utc), 2); double tstep = 30; int l = 7; for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = "S_" + tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // FileWriter trackletsOutKep = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1h/AMR040/" + app); // FileWriter trackletsOutPer = new FileWriter("/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1h/AMR040/" + app); // BufferedWriter trackletsKepBW = new BufferedWriter(trackletsOutKep); // BufferedWriter trackletsPerBW = new BufferedWriter(trackletsOutPer); // with formatted output File file1 = new File( "/home/zittersteijn/Documents/tracklets/simulated/keplerian/ASTRA/dt1d/AMR040/" + app); File file2 = new File( "/home/zittersteijn/Documents/tracklets/simulated/perturbed/ASTRA/dt1d/AMR040/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < l; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); SpacecraftState currentStateKep = kepler.propagate(propDate); SpacecraftState currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the tracklets to seperate files with the RA, DEC, epoch and fence given // System.out.println(tles.get(kk).getSatelliteNumber() + "\t" + radec[0] / (2 * FastMath.PI) * 180 + "\t" + currentState.getDate()); AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:fi.jyu.it.ties456.week38.Main.Main.java
public static void main(String[] args) throws NoSuchTeacherException_Exception { TeacherRegistryService connect = new TeacherRegistryService(); TeacherRegistry teacher = connect.getTeacherRegistryPort(); CourseISService connectCourse = new CourseISService(); CourseIS course = connectCourse.getCourseISPort(); int i;// w w w. j a v a 2 s . c o m Scanner inputchoice = new Scanner(System.in); Scanner cin = new Scanner(System.in); do { System.out.println("0: Quit the application"); System.out.println("1: Search the teacher Info"); System.out.println("2: Create the Course"); i = inputchoice.nextInt(); switch (i) { case 0: System.out.println("quit the application"); break; case 1: System.out.println("Input search info of teacher"); String searchString = cin.nextLine(); JSONObject result = searchTeacher(teacher, searchString); if (result == null) System.out.println("No person found"); else System.out.println(result); break; case 2: createCourse(teacher, course); break; default: System.err.println("Not a valid choice"); } } while (i != 0); }
From source file:gentracklets.Propagate.java
public static void main(String[] args) throws OrekitException { // load the data files File data = new File("/home/zittersteijn/Documents/java/libraries/orekit-data.zip"); DataProvidersManager DM = DataProvidersManager.getInstance(); ZipJarCrawler crawler = new ZipJarCrawler(data); DM.clearProviders();/*from w w w . jav a2 s . co m*/ DM.addProvider(crawler); // Read in TLE elements File tleFile = new File("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); FileReader TLEfr; Vector<TLE> tles = new Vector<>(); tles.setSize(30); try { // read and save TLEs to a vector TLEfr = new FileReader("/home/zittersteijn/Documents/TLEs/ASTRA20151207.tle"); BufferedReader readTLE = new BufferedReader(TLEfr); Scanner s = new Scanner(tleFile); String line1, line2; TLE2 tle = new TLE2(); int nrOfObj = 4; for (int ii = 1; ii < nrOfObj + 1; ii++) { System.out.println(ii); line1 = s.nextLine(); line2 = s.nextLine(); if (TLE.isFormatOK(line1, line2)) { tles.setElementAt(new TLE(line1, line2), ii); System.out.println(tles.get(ii).toString()); } else { System.out.println("format problem"); } } readTLE.close(); // define a groundstation Frame inertialFrame = FramesFactory.getEME2000(); TimeScale utc = TimeScalesFactory.getUTC(); double longitude = FastMath.toRadians(7.465); double latitude = FastMath.toRadians(46.87); double altitude = 950.; GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude); Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, earthFrame); TopocentricFrame staF = new TopocentricFrame(earth, station, "station"); Vector<Orbit> eles = new Vector<>(); eles.setSize(tles.size()); for (int ii = 1; ii < nrOfObj + 1; ii++) { double a = FastMath.pow(Constants.WGS84_EARTH_MU / FastMath.pow(tles.get(ii).getMeanMotion(), 2), (1.0 / 3)); // convert them to orbits Orbit kep = new KeplerianOrbit(a, tles.get(ii).getE(), tles.get(ii).getI(), tles.get(ii).getPerigeeArgument(), tles.get(ii).getRaan(), tles.get(ii).getMeanAnomaly(), PositionAngle.MEAN, inertialFrame, tles.get(ii).getDate(), Constants.WGS84_EARTH_MU); eles.setElementAt(kep, ii); // set up propagators KeplerianPropagator kepler = new KeplerianPropagator(eles.get(ii)); System.out.println("a: " + a); // Initial state definition double mass = 1000.0; SpacecraftState initialState = new SpacecraftState(kep, mass); // Adaptive step integrator // with a minimum step of 0.001 and a maximum step of 1000 double minStep = 0.001; double maxstep = 1000.0; double positionTolerance = 10.0; OrbitType propagationType = OrbitType.KEPLERIAN; double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, kep, propagationType); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0], tolerances[1]); NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(propagationType); // set up and add force models double AMR = 4.0; double crossSection = mass * AMR; double Cd = 0.01; double Cr = 0.5; double Co = 0.8; NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(4, 4); ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel( FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider); SphericalSpacecraft ssc = new SphericalSpacecraft(crossSection, Cd, Cr, Co); PVCoordinatesProvider sun = CelestialBodyFactory.getSun(); SolarRadiationPressure srp = new SolarRadiationPressure(sun, Constants.WGS84_EARTH_EQUATORIAL_RADIUS, ssc); // propagator.addForceModel(srp); // propagator.addForceModel(holmesFeatherstone); propagator.setInitialState(initialState); // propagate the orbits with steps size and tracklet lenght at several epochs (tracklets) Vector<AbsoluteDate> startDates = new Vector<>(); startDates.setSize(1); startDates.setElementAt(new AbsoluteDate(2016, 1, 26, 20, 00, 00, utc), 0); // set the step size [s] and total length double tstep = 100; double ld = 3; double ls = FastMath.floor(ld * (24 * 60 * 60) / tstep); System.out.println(ls); SpacecraftState currentStateKep = kepler.propagate(startDates.get(0)); SpacecraftState currentStatePer = propagator.propagate(startDates.get(0)); for (int tt = 0; tt < startDates.size(); tt++) { // set up output file String app = tles.get(ii).getSatelliteNumber() + "_" + startDates.get(tt) + ".txt"; // with formatted output File file1 = new File("/home/zittersteijn/Documents/propagate/keplerian/MEO/" + app); File file2 = new File("/home/zittersteijn/Documents/propagate/perturbed/MEO/" + app); file1.createNewFile(); file2.createNewFile(); Formatter fmt1 = new Formatter(file1); Formatter fmt2 = new Formatter(file2); for (int kk = 0; kk < (int) ls; kk++) { AbsoluteDate propDate = startDates.get(tt).shiftedBy(tstep * kk); currentStateKep = kepler.propagate(propDate); currentStatePer = propagator.propagate(propDate); System.out.println(currentStateKep.getPVCoordinates().getPosition() + "\t" + currentStateKep.getDate()); // convert to RADEC coordinates double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, propDate); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, propDate); // write the orbit to seperate files with the RA, DEC, epoch and fence given AbsoluteDate year = new AbsoluteDate(YEAR, utc); fmt1.format("%.12f %.12f %.12f %d%n", radecKep[0], radecKep[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); fmt2.format("%.12f %.12f %.12f %d%n", radecPer[0], radecPer[2], (currentStateKep.getDate().durationFrom(year) / (24 * 3600)), (tt + 1)); } fmt1.flush(); fmt1.close(); fmt2.flush(); fmt2.close(); } double[] radecKep = conversions.geo2radec(currentStateKep.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double[] radecPer = conversions.geo2radec(currentStatePer.getPVCoordinates(), staF, inertialFrame, new AbsoluteDate(startDates.get(0), ls * tstep)); double sig0 = 1.0 / 3600.0 / 180.0 * FastMath.PI; double dRA = radecKep[0] - radecPer[0] / (sig0 * sig0); double dDEC = radecKep[2] - radecPer[2] / (sig0 * sig0); System.out.println(dRA + "\t" + dDEC); } } catch (FileNotFoundException ex) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException iox) { Logger.getLogger(GenTracklets.class.getName()).log(Level.SEVERE, null, iox); } }
From source file:de.prozesskraft.ptest.Fingerprint.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { // try//w w w . j a v a 2 s .c o m // { // if (args.length != 3) // { // System.out.println("Please specify processdefinition file (xml) and an outputfilename"); // } // // } // catch (ArrayIndexOutOfBoundsException e) // { // System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString()); // } /*---------------------------- get options from ini-file ----------------------------*/ File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Fingerprint.class) + "/" + "../etc/ptest-fingerprint.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option opath = OptionBuilder.withArgName("PATH").hasArg() .withDescription( "[mandatory; default: .] the root path for the tree you want to make a fingerprint from.") // .isRequired() .create("path"); Option osizetol = OptionBuilder.withArgName("FLOAT").hasArg().withDescription( "[optional; default: 0.02] the sizeTolerance (as factor in percent) of all file entries will be set to this value. [0.0 < sizetol < 1.0]") // .isRequired() .create("sizetol"); Option omd5 = OptionBuilder.withArgName("no|yes").hasArg() .withDescription("[optional; default: yes] should be the md5sum of files determined? no|yes") // .isRequired() .create("md5"); Option oignore = OptionBuilder.withArgName("STRING").hasArgs() .withDescription("[optional] path-pattern that should be ignored when creating the fingerprint") // .isRequired() .create("ignore"); Option oignorefile = OptionBuilder.withArgName("FILE").hasArg().withDescription( "[optional] file with path-patterns (one per line) that should be ignored when creating the fingerprint") // .isRequired() .create("ignorefile"); Option ooutput = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory; default: <path>/fingerprint.xml] fingerprint file") // .isRequired() .create("output"); Option of = new Option("f", "[optional] force overwrite fingerprint file if it already exists"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(opath); options.addOption(osizetol); options.addOption(omd5); options.addOption(oignore); options.addOption(oignorefile); options.addOption(ooutput); options.addOption(of); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); try { // parse the command line arguments commandline = parser.parse(options, args); } catch (Exception exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); exiter(); } /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("fingerprint", options); System.exit(0); } else if (commandline.hasOption("v")) { System.out.println("web: " + web); System.out.println("author: " + author); System.out.println("version:" + version); System.out.println("date: " + date); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ String path = ""; String sizetol = ""; boolean md5 = false; Float sizetolFloat = null; String output = ""; java.io.File ignorefile = null; ArrayList<String> ignore = new ArrayList<String>(); if (!(commandline.hasOption("path"))) { System.err.println("setting default for -path=."); path = "."; } else { path = commandline.getOptionValue("path"); } if (!(commandline.hasOption("sizetol"))) { System.err.println("setting default for -sizetol=0.02"); sizetol = "0.02"; sizetolFloat = 0.02F; } else { sizetol = commandline.getOptionValue("sizetol"); sizetolFloat = Float.parseFloat(sizetol); if ((sizetolFloat > 1) || (sizetolFloat < 0)) { System.err.println("use only values >=0.0 and <1.0 for -sizetol"); System.exit(1); } } if (!(commandline.hasOption("md5"))) { System.err.println("setting default for -md5=yes"); md5 = true; } else if (commandline.getOptionValue("md5").equals("no")) { md5 = false; } else if (commandline.getOptionValue("md5").equals("yes")) { md5 = true; } else { System.err.println("use only values no|yes for -md5"); System.exit(1); } if (commandline.hasOption("ignore")) { ignore.addAll(Arrays.asList(commandline.getOptionValues("ignore"))); } if (commandline.hasOption("ignorefile")) { ignorefile = new java.io.File(commandline.getOptionValue("ignorefile")); if (!ignorefile.exists()) { System.err.println("warn: ignore file does not exist: " + ignorefile.getCanonicalPath()); } } if (!(commandline.hasOption("output"))) { System.err.println("setting default for -output=" + path + "/fingerprint.xml"); output = path + "/fingerprint.xml"; } else { output = commandline.getOptionValue("output"); } // wenn output bereits existiert -> abbruch java.io.File outputFile = new File(output); if (outputFile.exists()) { if (commandline.hasOption("f")) { outputFile.delete(); } else { System.err .println("error: output file (" + output + ") already exists. use -f to force overwrite."); System.exit(1); } } // if ( !( commandline.hasOption("output")) ) // { // System.err.println("option -output is mandatory."); // exiter(); // } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ Dir dir = new Dir(); dir.setBasepath(path); dir.setOutfilexml(output); // ignore file in ein Array lesen if ((ignorefile != null) && (ignorefile.exists())) { Scanner sc = new Scanner(ignorefile); while (sc.hasNextLine()) { ignore.add(sc.nextLine()); } sc.close(); } // // autoignore hinzufuegen // String autoIgnoreString = ini.get("autoignore", "autoignore"); // ignoreLines.addAll(Arrays.asList(autoIgnoreString.split(","))); // // debug // System.out.println("ignorefile content:"); // for(String actLine : ignore) // { // System.out.println("line: "+actLine); // } try { dir.genFingerprint(sizetolFloat, md5, ignore); } catch (NullPointerException e) { System.err.println("file/dir does not exist " + path); e.printStackTrace(); exiter(); } catch (IOException e) { e.printStackTrace(); exiter(); } System.out.println("writing to file: " + dir.getOutfilexml()); dir.writeXml(); }
From source file:IMAPService.java
public static void main(String[] args) { // Arguments/*from w ww .j a v a 2 s . com*/ String server = ""; int port = -1; String login = ""; String password = ""; boolean deleteAfterDownload = false; boolean downloadAll = false; String[] foldersToDownload = null; // Set up apache cli Options options = new Options(); Option S = new Option("S", true, "Server Name"); S.setRequired(true); options.addOption(S); Option P = new Option("P", true, "Port Number"); P.setRequired(true); options.addOption(P); Option l = new Option("l", true, "Login"); l.setRequired(true); options.addOption(l); Option p = new Option("p", true, "Password if not on stdin"); options.addOption(p); Option d = new Option("d", false, "Delete after downloading"); d.setRequired(false); options.addOption(d); Option a = new Option("a", false, "Download from all folders"); a.setRequired(false); options.addOption(a); Option f = new Option("f", true, "Download messages from specified folder"); options.addOption(f); CommandLineParser clp = new DefaultParser(); try { CommandLine cl = clp.parse(options, args); if (cl.hasOption("S")) server = cl.getOptionValue("S"); if (cl.hasOption("P")) port = Integer.parseInt(cl.getOptionValue("P")); if (cl.hasOption("l")) login = cl.getOptionValue("l"); if (cl.hasOption("p")) password = cl.getOptionValue("p"); if (cl.hasOption("d")) deleteAfterDownload = true; if (cl.hasOption("a")) downloadAll = true; else if (cl.hasOption("f")) foldersToDownload = cl.getOptionValues("f"); else { showArgMenu(options); return; } } catch (Exception e) { showArgMenu(options); return; } if (password.isEmpty()) { // Grab p/w of stdin if it's there Scanner sc = new Scanner(System.in); password = sc.nextLine(); sc.close(); } if (!server.isEmpty() && port != -1 && !login.isEmpty() && !password.isEmpty() && (downloadAll || foldersToDownload != null)) { //IMAPService imapService = new IMAPService("imap.gmail.com", 993); IMAPService imapService = new IMAPService(server, port); //imapService.login("kinglibingli@gmail.com", "kingli1bingli"); imapService.login(login, password); imapService.buildMailbox(); // Check if service should delete emails if (deleteAfterDownload) imapService.deleteEmailsAfterDownload(); // Proceed with downloads if (downloadAll) imapService.downloadAllFolders(); else { for (String folderNames : foldersToDownload) { imapService.downloadFoldersEmails(folderNames); } } imapService.logout(); } }
From source file:org.springintegration.demo.Main.java
/** * Load the Spring Integration Application Context * * @param args - command line arguments//from ww w . ja v a2 s . c om */ public static void main(final String... args) { LOGGER.info("\n=========================================================" + "\n " + "\n Welcome to Spring Integration! " + "\n " + "\n For more information please visit: " + "\n http://www.springsource.org/spring-integration " + "\n " + "\n========================================================="); final AbstractApplicationContext context = new ClassPathXmlApplicationContext( "classpath:META-INF/spring/integration/*-context.xml"); context.registerShutdownHook(); final Scanner scanner = new Scanner(System.in); LOGGER.info("\n=========================================================" + "\n " + "\n Please press 'q + Enter' to quit the application. " + "\n " + "\n========================================================="); System.out.print("Please enter a string and press <enter>: "); while (true) { final String input = scanner.nextLine(); if ("q".equals(input.trim())) { break; } } LOGGER.info("Exiting application...bye."); System.exit(0); }
From source file:com.canyapan.randompasswordgenerator.cli.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("h", false, "prints help"); options.addOption("def", false, "generates 8 character password with default options"); options.addOption("p", true, "password length (default 8)"); options.addOption("l", false, "include lower case characters"); options.addOption("u", false, "include upper case characters"); options.addOption("d", false, "include digits"); options.addOption("s", false, "include symbols"); options.addOption("lc", true, "minimum lower case character count (default 0)"); options.addOption("uc", true, "minimum upper case character count (default 0)"); options.addOption("dc", true, "minimum digit count (default 0)"); options.addOption("sc", true, "minimum symbol count (default 0)"); options.addOption("a", false, "avoid ambiguous characters"); options.addOption("f", false, "force every character type"); options.addOption("c", false, "continuous password generation"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;//from w w w. ja v a 2s. co m boolean printHelp = false; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelp = true; } if (printHelp || args.length == 0 || cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "java -jar RandomPasswordGenerator.jar [-p <arg>] [-l] [-u] [-s] [-d] [-dc <arg>] [-a] [-f]", options); return; } RandomPasswordGenerator rpg = new RandomPasswordGenerator(); if (cmd.hasOption("def")) { rpg.withDefault().withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))); } else { rpg.withPasswordLength(Integer.parseInt(cmd.getOptionValue("p", "8"))) .withLowerCaseCharacters(cmd.hasOption("l")).withUpperCaseCharacters(cmd.hasOption("u")) .withDigits(cmd.hasOption("d")).withSymbols(cmd.hasOption("s")) .withAvoidAmbiguousCharacters(cmd.hasOption("a")) .withForceEveryCharacterType(cmd.hasOption("f")); if (cmd.hasOption("lc")) { rpg.withMinLowerCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("lc", "0"))); } if (cmd.hasOption("uc")) { rpg.withMinUpperCaseCharacterCount(Integer.parseInt(cmd.getOptionValue("uc", "0"))); } if (cmd.hasOption("dc")) { rpg.withMinDigitCount(Integer.parseInt(cmd.getOptionValue("dc", "0"))); } if (cmd.hasOption("sc")) { rpg.withMinSymbolCount(Integer.parseInt(cmd.getOptionValue("sc", "0"))); } } Scanner scanner = new Scanner(System.in); try { do { final String password = rpg.generate(); final PasswordMeter.Result result = PasswordMeter.check(password); System.out.printf("%s%nScore: %s%%%nComplexity: %s%n%n", password, result.getScore(), result.getComplexity()); if (cmd.hasOption("c")) { System.out.print("Another? y/N: "); } } while (cmd.hasOption("c") && scanner.nextLine().matches("^(?i:y(?:es)?)$")); } catch (RandomPasswordGeneratorException e) { System.err.println(e.getMessage()); } catch (PasswordMeterException e) { System.err.println(e.getMessage()); } }
From source file:fr.tpt.s3.mcdag.bench.MainBench.java
public static void main(String[] args) throws IOException, InterruptedException { // Command line options Options options = new Options(); Option input = new Option("i", "input", true, "MC-DAG XML models"); input.setRequired(true);/*from w w w. j a v a 2s.c o m*/ input.setArgs(Option.UNLIMITED_VALUES); options.addOption(input); Option output = new Option("o", "output", true, "Folder where results have to be written."); output.setRequired(true); options.addOption(output); Option uUti = new Option("u", "utilization", true, "Utilization."); uUti.setRequired(true); options.addOption(uUti); Option output2 = new Option("ot", "output-total", true, "File where total results are being written"); output2.setRequired(true); options.addOption(output2); Option oCores = new Option("c", "cores", true, "Cores given to the test"); oCores.setRequired(true); options.addOption(oCores); Option oLvls = new Option("l", "levels", true, "Levels tested for the system"); oLvls.setRequired(true); options.addOption(oLvls); Option jobs = new Option("j", "jobs", true, "Number of threads to be launched."); jobs.setRequired(false); options.addOption(jobs); Option debug = new Option("d", "debug", false, "Debug logs."); debug.setRequired(false); options.addOption(debug); /* * Parsing of the command line */ CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("Benchmarks MultiDAG", options); System.exit(1); return; } String inputFilePath[] = cmd.getOptionValues("input"); String outputFilePath = cmd.getOptionValue("output"); String outputFilePathTotal = cmd.getOptionValue("output-total"); double utilization = Double.parseDouble(cmd.getOptionValue("utilization")); boolean boolDebug = cmd.hasOption("debug"); int nbLvls = Integer.parseInt(cmd.getOptionValue("levels")); int nbJobs = 1; int nbFiles = inputFilePath.length; if (cmd.hasOption("jobs")) nbJobs = Integer.parseInt(cmd.getOptionValue("jobs")); int nbCores = Integer.parseInt(cmd.getOptionValue("cores")); /* * While files need to be allocated * run the tests in the pool of threads */ // For dual-criticality systems we call a specific thread if (nbLvls == 2) { System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls); int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int fedTotal = 0; int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int fedPreempts = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int fedActiv = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { fedTotal += Integer.parseInt(val); } else if (j == 3) { fedPreempts += Integer.parseInt(val); } else if (j == 4) { fedActiv += Integer.parseInt(val); } else if (j == 5) { laxTotal += Integer.parseInt(val); } else if (j == 6) { laxPreempts += Integer.parseInt(val); } else if (j == 7) { laxActiv += Integer.parseInt(val); } else if (j == 8) { edfTotal += Integer.parseInt(val); } else if (j == 9) { edfPreempts += Integer.parseInt(val); } else if (j == 10) { edfActiv += Integer.parseInt(val); } else if (j == 11) { hybridTotal += Integer.parseInt(val); } else if (j == 12) { hybridPreempts += Integer.parseInt(val); } else if (j == 13) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double fedPerc = (double) fedTotal / nbFiles; double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double fedPercPreempts = (double) fedPreempts / fedActiv; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; " + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else if (nbLvls > 2) { int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { laxTotal += Integer.parseInt(val); } else if (j == 3) { laxPreempts += Integer.parseInt(val); } else if (j == 4) { laxActiv += Integer.parseInt(val); } else if (j == 5) { edfTotal += Integer.parseInt(val); } else if (j == 6) { edfPreempts += Integer.parseInt(val); } else if (j == 7) { edfActiv += Integer.parseInt(val); } else if (j == 8) { hybridTotal += Integer.parseInt(val); } else if (j == 9) { hybridPreempts += Integer.parseInt(val); } else if (j == 10) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else { System.err.println("Wrong number of levels"); System.exit(-1); } System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls); }