Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

In this page you can find the example usage for java.util Scanner Scanner.

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

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   www  .  j  a v  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:au.edu.uws.eresearch.cr8it.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments/*from   w  w w .  j ava 2  s. c  o  m*/
 */
public static void main(final String... args) {

    String contextFilePath = "spring-integration-context.xml";
    String configFilePath = "config/config-file.groovy";
    String environment = System.getProperty("environment");

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n          Welcome to C8it Integration!                 "
                + "\n                                                         "
                + "\n    For more information please visit:                   "
                + "\n    http://www.springsource.org/spring-integration       "
                + "\n                                                         "
                + "\n=========================================================");
    }

    ConfigObject config = Config.getConfig(environment, configFilePath);
    Map configMap = config.flatten();
    System.setProperty("environment", environment);
    System.setProperty("cr8it.client.config.file", (String) configMap.get("file.runtimePath"));

    //final AbstractApplicationContext context =
    //new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml");

    String absContextPath = "config/integration/" + contextFilePath;
    File contextFile = new File(absContextPath);
    final AbstractApplicationContext context;
    if (!contextFile.exists()) {
        absContextPath = "classpath:" + absContextPath;
        context = new ClassPathXmlApplicationContext(absContextPath);
    } else {
        absContextPath = "file:" + absContextPath;
        context = new FileSystemXmlApplicationContext(absContextPath);
    }

    context.registerShutdownHook();

    SpringIntegrationUtils.displayDirectories(context);

    final Scanner scanner = new Scanner(System.in);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n                                                         "
                + "\n=========================================================");
    }

    while (!scanner.hasNext("q")) {
        //Do nothing unless user presses 'q' to quit.
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    System.exit(0);

}

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  .java 2s . c o 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:gr.demokritos.iit.demos.Demo.java

public static void main(String[] args) {
    try {/*from w w w  .  j  av a2 s  . c  o m*/
        Options options = new Options();
        options.addOption("h", HELP, false, "show help.");
        options.addOption("i", INPUT, true,
                "The file containing JSON " + " representations of tweets or SAG posts - 1 per line"
                        + " default file looked for is " + DEFAULT_INFILE);
        options.addOption("o", OUTPUT, true,
                "Where to write the output " + " default file looked for is " + DEFAULT_OUTFILE);
        options.addOption("p", PROCESS, true, "Type of processing to do "
                + " ner for Named Entity Recognition re for Relation Extraction" + " default is NER");
        options.addOption("s", SAG, false,
                "Whether to process as SAG posts" + " default is off - if passed means process as SAG posts");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        // DEFAULTS
        String filename = DEFAULT_INFILE;
        String outfilename = DEFAULT_OUTFILE;
        String process = NER;
        boolean isSAG = false;

        if (cmd.hasOption(HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("NER + RE extraction module", options);
            System.exit(0);
        }
        if (cmd.hasOption(INPUT)) {
            filename = cmd.getOptionValue(INPUT);
        }
        if (cmd.hasOption(OUTPUT)) {
            outfilename = cmd.getOptionValue(OUTPUT);
        }
        if (cmd.hasOption(SAG)) {
            isSAG = true;
        }
        if (cmd.hasOption(PROCESS)) {
            process = cmd.getOptionValue(PROCESS);
        }
        System.out.println();
        System.out.println("Reading from file: " + filename);
        System.out.println("Process type: " + process);
        System.out.println("Processing SAG: " + isSAG);
        System.out.println("Writing to file: " + outfilename);
        System.out.println();

        List<String> jsoni = new ArrayList();
        Scanner in = new Scanner(new FileReader(filename));
        while (in.hasNextLine()) {
            String json = in.nextLine();
            jsoni.add(json);
        }
        PrintWriter writer = new PrintWriter(outfilename, "UTF-8");
        System.out.println("Read " + jsoni.size() + " lines from " + filename);
        if (process.equalsIgnoreCase(RE)) {
            System.out.println("Running Relation Extraction");
            System.out.println();
            String json = API.RE(jsoni, isSAG);
            System.out.println(json);
            writer.print(json);
        } else {
            System.out.println("Running Named Entity Recognition");
            System.out.println();
            jsoni = API.NER(jsoni, isSAG);
            /*
            for(String json: jsoni){
               NamedEntityList nel = NamedEntityList.fromJSON(json);
               nel.prettyPrint();
            }
            */
            for (String json : jsoni) {
                System.out.println(json);
                writer.print(json);
            }
        }
        writer.close();
    } catch (ParseException | UnsupportedEncodingException | FileNotFoundException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Service.java

public static void main(String[] args) {

    StringWriter sw = new StringWriter();
    try {//  www  .j  a  va 2s .  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: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;// w  ww . j  a v  a 2 s .  c om
    }

    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:clientpaxos.ClientPaxos.java

/**
 * @param args the command line arguments
 */// www .  ja  v a2 s. co m
public static void main(String[] args) throws IOException, InterruptedException, Exception {
    // TODO code application logic here

    String host = "";
    int port = 0;

    try (BufferedReader br = new BufferedReader(new FileReader("ipserver.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        if (line != null) {
            host = line;
            line = br.readLine();
            if (line != null) {
                port = Integer.parseInt(line);
            }
        }
    }

    scanner = new Scanner(System.in);

    //System.out.print("Input server IP hostname : ");
    //host = scan.nextLine();
    //System.out.print("Input server Port : ");
    //port = scan.nextInt();
    //scan.nextLine();
    tcpSocket = new Socket(host, port);
    System.out.println("Connected");
    Thread t = new Thread(new StringGetter());
    t.start();
    while (true) {
        sleep(100);
        if (!voteInput) {
            System.out.print("COMMAND : ");
        }
        //send msg to server
        String msg = scanner.next();
        //if ((day && isAlive == 1) || (!day && role.equals("werewolf") && isAlive == 1)) {
        ParseCommand(msg);
        //}
    }
}

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.  j  a va2s. 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:com.left8.evs.evs.EvS.java

/**
 * Main method that provides a simple console input interface for the user,
 * if she wishes to execute the tool as a .jar executable.
 * @param args A list of arguments./*  www.  ja v  a  2 s  . c o  m*/
 * @throws org.apache.commons.cli.ParseException ParseExcetion
 */
public static void main(String[] args) throws ParseException {

    Config config = null;
    try {
        config = new Config();
    } catch (IOException ex) {
        Utilities.printMessageln("Configuration file 'config.properties' " + "not in classpath!");
        Logger.getLogger(EvS.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(1);
    }

    if (args.length != 0) { //If the user supplied arguments
        Console console = new Console(args, config); //Read the console

        showMongoLogging = console.showMongoLogging();
        showInlineInfo = console.showInlineInfo();
        hasExtCommands = console.hasExternalCommands();
        choice = console.getChoiceValue();
    }

    if (!showMongoLogging) {
        //Stop reporting logging information
        Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
        mongoLogger.setLevel(Level.SEVERE);
    }

    System.out.println("\n----EvS----");

    if (!hasExtCommands) {
        System.out.println("Select one of the following options");
        System.out.println("1. Run Offline Peak Finding experiments.");
        System.out.println("2. Run EDCoW experiments.");
        System.out.println("3. Run each of the above methods without " + "the sentiment annotations.");
        System.out.println("Any other key to exit.");
        System.out.println("");
        System.out.print("Your choice: ");

        Scanner keyboard = new Scanner(System.in);
        choice = keyboard.nextInt();
    }

    switch (choice) {
    case 1: { //Offline Peak Finding
        int window = 10;
        double alpha = 0.85;
        int taph = 1;
        int pi = 5;
        Dataset ds = new Dataset(config);
        PeakFindingCorpus corpus = new PeakFindingCorpus(config, ds.getTweetList(), ds.getSWH());
        corpus.createCorpus(window);

        List<BinPair<String, Integer>> bins = BinsCreator.createBins(corpus, config, window);
        PeakFindingSentimentCorpus sCorpus = new PeakFindingSentimentCorpus(corpus);

        SentimentPeakFindingExperimenter exper = new SentimentPeakFindingExperimenter(sCorpus, bins, alpha,
                taph, pi, window, config);

        //Experiment with Taph
        List<String> lines = exper.experimentUsingTaph(1, 10, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingTaph(1, 10, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingTaph(1, 10, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        //Experiment with Alpha
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingAlpha(0.85, 0.99, 0.01, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        break;
    }
    case 2: { //EDCoW
        Dataset ds = new Dataset(config);
        SentimentEDCoWCorpus corpus = new SentimentEDCoWCorpus(config, ds.getTweetList(), ds.getSWH(), 10);

        corpus.getEDCoWCorpus().createCorpus();
        corpus.getEDCoWCorpus().setDocTermFreqIdList();
        int delta = 5, delta2 = 11, gamma = 6;
        double minTermSupport = 0.001, maxTermSupport = 0.01;

        SentimentEDCoWExperimenter exper = new SentimentEDCoWExperimenter(corpus, delta, delta2, gamma,
                minTermSupport, maxTermSupport, choice, choice, config);

        //Experiment with delta
        List<String> lines = exper.experimentUsingDelta(1, 20, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingDelta(1, 20, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingDelta(1, 20, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        //Experiment with gamma
        lines = exper.experimentUsingGamma(6, 10, 1, 0, showInlineInfo);
        exper.exportToFile("stanford.txt", lines);
        lines = exper.experimentUsingGamma(6, 10, 1, 1, showInlineInfo);
        exper.exportToFile("naive_bayes.txt", lines);
        lines = exper.experimentUsingGamma(6, 10, 1, 2, showInlineInfo);
        exper.exportToFile("bayesian_net.txt", lines);

        break;
    }
    case 3: {
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 0);
        break;
    }
    case 4: { //Directly run OPF
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 1);
        break;
    }
    case 5: { //Directly run EDCoW
        EDMethodPicker.selectEDMethod(config, showInlineInfo, 2);
        break;
    }
    default: {
        System.out.println("Exiting now...");
        System.exit(0);
    }
    }
}

From source file:FileSplitter.java

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Split? [true/false]: ");
    boolean split = Boolean.parseBoolean(scan.next());

    if (split) {// w  w w.  j a va 2  s  .c  o m
        File file = new File("T:/Java/com/power/nb/visual/dist/visual.zip");
        FileSplitter splitter = new FileSplitter(file);
        System.out.println("splitter.split(3): " + splitter.split(3));
    } else {
        File file = new File("T:/Java/com/power/nb/visual/dist/visual.zip.part.0");
        FileSplitter splitter = new FileSplitter(file);
        System.out.println("splitter.unsplit(): " + splitter.unsplit());
    }
}