Example usage for java.util Locale US

List of usage examples for java.util Locale US

Introduction

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

Prototype

Locale US

To view the source code for java.util Locale US.

Click Source Link

Document

Useful constant for country.

Usage

From source file:fr.cs.examples.frames.Frames1.java

public static void main(String[] args) {
    try {/*www  .j  a va  2s.c  om*/

        // configure Orekit
        Autoconfiguration.configureOrekit();

        //  Initial state definition : date, orbit
        TimeScale utc = TimeScalesFactory.getUTC();
        AbsoluteDate initialDate = new AbsoluteDate(2008, 10, 01, 0, 0, 00.000, utc);
        double mu = 3.986004415e+14; // gravitation coefficient
        Frame inertialFrame = FramesFactory.getEME2000(); // inertial frame for orbit definition
        Vector3D posisat = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        Vector3D velosat = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        PVCoordinates pvsat = new PVCoordinates(posisat, velosat);
        Orbit initialOrbit = new CartesianOrbit(pvsat, inertialFrame, initialDate, mu);

        // Propagator : consider a simple keplerian motion
        Propagator kepler = new KeplerianPropagator(initialOrbit);

        // The local orbital frame (LOF) is related to the orbit propagated by the kepler propagator.
        LocalOrbitalFrame lof = new LocalOrbitalFrame(inertialFrame, LOFType.QSW, kepler, "QSW");

        // Earth and frame
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);

        // Station
        final double longitude = FastMath.toRadians(45.);
        final double latitude = FastMath.toRadians(25.);
        final double altitude = 0.;
        final GeodeticPoint station = new GeodeticPoint(latitude, longitude, altitude);
        final TopocentricFrame staF = new TopocentricFrame(earth, station, "station");

        System.out.println("          time           doppler (m/s)");

        // Stop date
        final AbsoluteDate finalDate = new AbsoluteDate(initialDate, 6000, utc);

        // Loop
        AbsoluteDate extrapDate = initialDate;
        while (extrapDate.compareTo(finalDate) <= 0) {

            // We can simply get the position and velocity of station in LOF frame at any time
            PVCoordinates pv = staF.getTransformTo(lof, extrapDate).transformPVCoordinates(PVCoordinates.ZERO);

            // And then calculate the doppler signal
            double doppler = Vector3D.dotProduct(pv.getPosition(), pv.getVelocity())
                    / pv.getPosition().getNorm();

            System.out.format(Locale.US, "%s   %9.3f%n", extrapDate, doppler);

            extrapDate = new AbsoluteDate(extrapDate, 600, utc);

        }

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:com.google.play.developerapi.samples.UploadApkWithListing.java

public static void main(String[] args) {
    try {// www.  j a  va  2  s . co  m
        Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME),
                "ApplicationConfig.PACKAGE_NAME cannot be null or empty!");

        // Create the API service.
        AndroidPublisher service = AndroidPublisherHelper.init(ApplicationConfig.APPLICATION_NAME,
                ApplicationConfig.SERVICE_ACCOUNT_EMAIL);
        final Edits edits = service.edits();

        // Create a new edit to make changes.
        Insert editRequest = edits.insert(ApplicationConfig.PACKAGE_NAME, null /** no content */
        );
        AppEdit edit = editRequest.execute();
        final String editId = edit.getId();
        log.info(String.format("Created edit with id: %s", editId));

        // Upload new apk to developer console
        final String apkPath = UploadApkWithListing.class.getResource(ApplicationConfig.APK_FILE_PATH).toURI()
                .getPath();
        final AbstractInputStreamContent apkFile = new FileContent(AndroidPublisherHelper.MIME_TYPE_APK,
                new File(apkPath));
        Upload uploadRequest = edits.apks().upload(ApplicationConfig.PACKAGE_NAME, editId, apkFile);
        Apk apk = uploadRequest.execute();
        log.info(String.format("Version code %d has been uploaded", apk.getVersionCode()));

        // Assign apk to beta track.
        List<Integer> apkVersionCodes = new ArrayList<>();
        apkVersionCodes.add(apk.getVersionCode());
        Update updateTrackRequest = edits.tracks().update(ApplicationConfig.PACKAGE_NAME, editId, TRACK_BETA,
                new Track().setVersionCodes(apkVersionCodes));
        Track updatedTrack = updateTrackRequest.execute();
        log.info(String.format("Track %s has been updated.", updatedTrack.getTrack()));

        // Update recent changes field in apk listing.
        final ApkListing newApkListing = new ApkListing();
        newApkListing.setRecentChanges(APK_LISTING_RECENT_CHANGES_TEXT);

        Apklistings.Update updateRecentChangesRequest = edits.apklistings().update(
                ApplicationConfig.PACKAGE_NAME, editId, apk.getVersionCode(), Locale.US.toString(),
                newApkListing);
        updateRecentChangesRequest.execute();
        log.info("Recent changes has been updated.");

        // Commit changes for edit.
        Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId);
        AppEdit appEdit = commitRequest.execute();
        log.info(String.format("App edit with id %s has been comitted", appEdit.getId()));

    } catch (IOException | URISyntaxException | GeneralSecurityException ex) {
        log.error("Exception was thrown while uploading apk and updating recent changes", ex);
    }
}

From source file:fr.cs.examples.propagation.MasterMode.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///from  w ww.ja  va  2  s. c  o  m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();

        // gravitation coefficient
        double mu = 3.986004415e+14;

        // inertial frame
        Frame inertialFrame = FramesFactory.getEME2000();

        // Initial date
        AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000, TimeScalesFactory.getUTC());

        // Initial orbit
        double a = 24396159; // semi major axis in meters
        double e = 0.72831215; // eccentricity
        double i = FastMath.toRadians(7); // inclination
        double omega = FastMath.toRadians(180); // perigee argument
        double raan = FastMath.toRadians(261); // right ascention of ascending node
        double lM = 0; // mean anomaly
        Orbit initialOrbit = new KeplerianOrbit(a, e, i, omega, raan, lM, PositionAngle.MEAN, inertialFrame,
                initialDate, mu);

        // Initial state definition
        SpacecraftState initialState = new SpacecraftState(initialOrbit);

        // Adaptive step integrator with a minimum step of 0.001 and a maximum step of 1000
        final double minStep = 0.001;
        final double maxstep = 1000.0;
        final double positionTolerance = 10.0;
        final OrbitType propagationType = OrbitType.KEPLERIAN;
        final double[][] tolerances = NumericalPropagator.tolerances(positionTolerance, initialOrbit,
                propagationType);
        AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(minStep, maxstep, tolerances[0],
                tolerances[1]);

        // Propagator
        NumericalPropagator propagator = new NumericalPropagator(integrator);
        propagator.setOrbitType(propagationType);

        // Force Model (reduced to perturbing gravity field)
        final NormalizedSphericalHarmonicsProvider provider = GravityFieldFactory.getNormalizedProvider(10, 10);
        ForceModel holmesFeatherstone = new HolmesFeatherstoneAttractionModel(
                FramesFactory.getITRF(IERSConventions.IERS_2010, true), provider);

        // Add force model to the propagator
        propagator.addForceModel(holmesFeatherstone);

        // Set up initial state in the propagator
        propagator.setInitialState(initialState);

        // Set up operating mode for the propagator as master mode
        // with fixed step and specialized step handler
        propagator.setMasterMode(60., new TutorialStepHandler());

        // Extrapolate from the initial to the final date
        SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(630.));
        KeplerianOrbit o = (KeplerianOrbit) OrbitType.KEPLERIAN.convertType(finalState.getOrbit());
        System.out.format(Locale.US, "Final state:%n%s %12.3f %10.8f %10.6f %10.6f %10.6f %10.6f%n",
                finalState.getDate(), o.getA(), o.getE(), FastMath.toDegrees(o.getI()),
                FastMath.toDegrees(o.getPerigeeArgument()),
                FastMath.toDegrees(o.getRightAscensionOfAscendingNode()),
                FastMath.toDegrees(o.getTrueAnomaly()));

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:fr.cs.examples.frames.Frames3.java

public static void main(String[] args) {
    try {//from   www .ja  v  a  2s .  c om

        // configure Orekit and printing format
        Autoconfiguration.configureOrekit();

        // Initial state definition :
        // ==========================

        // Date
        // ****
        AbsoluteDate initialDate = new AbsoluteDate(new DateComponents(1970, 04, 07), TimeComponents.H00,
                TimeScalesFactory.getUTC());

        // Orbit
        // *****
        // The Sun is in the orbital plane for raan ~ 202
        double mu = 3.986004415e+14; // gravitation coefficient
        Frame eme2000 = FramesFactory.getEME2000(); // inertial frame
        Orbit orbit = new CircularOrbit(7178000.0, 0.5e-4, -0.5e-4, FastMath.toRadians(50.),
                FastMath.toRadians(220.), FastMath.toRadians(5.300), PositionAngle.MEAN, eme2000, initialDate,
                mu);

        // Attitude laws
        // *************

        // Earth
        Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
                Constants.WGS84_EARTH_FLATTENING, earthFrame);

        // Target pointing attitude provider over satellite nadir at date, without yaw compensation
        NadirPointing nadirLaw = new NadirPointing(eme2000, earth);

        // Target pointing attitude provider with yaw compensation
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        YawSteering yawSteeringLaw = new YawSteering(eme2000, nadirLaw, sun, Vector3D.MINUS_I);

        // Propagator : Eckstein-Hechler analytic propagator
        Propagator propagator = new EcksteinHechlerPropagator(orbit, yawSteeringLaw,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);

        // Let's write the results in a file in order to draw some plots.
        propagator.setMasterMode(10, new OrekitFixedStepHandler() {

            PrintStream out = null;

            public void init(SpacecraftState s0, AbsoluteDate t) throws PropagationException {
                try {
                    File file = new File(System.getProperty("user.home"), "XYZ.dat");
                    System.out.println("Results written to file: " + file.getAbsolutePath());
                    out = new PrintStream(file);
                    out.println("#time X Y Z Wx Wy Wz");
                } catch (IOException ioe) {
                    throw new PropagationException(ioe, LocalizedFormats.SIMPLE_MESSAGE,
                            ioe.getLocalizedMessage());
                }
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {

                    // get the transform from orbit/attitude reference frame to spacecraft frame
                    Transform inertToSpacecraft = currentState.toTransform();

                    // get the position of the Sun in orbit/attitude reference frame
                    Vector3D sunInert = sun.getPVCoordinates(currentState.getDate(), currentState.getFrame())
                            .getPosition();

                    // convert Sun position to spacecraft frame
                    Vector3D sunSat = inertToSpacecraft.transformPosition(sunInert);

                    // and the spacecraft rotational rate also
                    Vector3D spin = inertToSpacecraft.getRotationRate();

                    // Lets calculate the reduced coordinates
                    double sunX = sunSat.getX() / sunSat.getNorm();
                    double sunY = sunSat.getY() / sunSat.getNorm();
                    double sunZ = sunSat.getZ() / sunSat.getNorm();

                    out.format(Locale.US, "%s %12.3f %12.3f %12.3f %12.7f %12.7f %12.7f%n",
                            currentState.getDate(), sunX, sunY, sunZ, spin.getX(), spin.getY(), spin.getZ());

                    if (isLast) {
                        out.close();
                    }
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }

        });

        System.out.println("Running...");
        propagator.propagate(initialDate.shiftedBy(6000));

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:fr.cs.examples.attitude.EarthObservation.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///from   w w w .j a v a2 s.c o m
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //  Initial state definition : date, orbit
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 01, 23, 30, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        // Attitudes sequence definition
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>());
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new ContinueOnEvent<EclipseDetector>());

        final AttitudesSequence attitudesSequence = new AttitudesSequence();
        final AttitudesSequence.SwitchHandler switchHandler = new AttitudesSequence.SwitchHandler() {
            public void switchOccurred(AttitudeProvider preceding, AttitudeProvider following,
                    SpacecraftState s) {
                if (preceding == dayObservationLaw) {
                    output.add(s.getDate() + ": switching to night law");
                } else {
                    output.add(s.getDate() + ": switching to day law");
                }
            }
        };
        attitudesSequence.addSwitchingCondition(dayObservationLaw, nightRestingLaw, dayNightEvent, false, true,
                10.0, AngularDerivativesFilter.USE_R, switchHandler);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, dayObservationLaw, nightDayEvent, true, false,
                10.0, AngularDerivativesFilter.USE_R, switchHandler);
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
        }

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);

        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(180.0, new OrekitFixedStepHandler() {
            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    DecimalFormatSymbols angleDegree = new DecimalFormatSymbols(Locale.US);
                    angleDegree.setDecimalSeparator('\u00b0');
                    DecimalFormat ad = new DecimalFormat(" 00.000;-00.000", angleDegree);
                    // the Earth position in spacecraft frame should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    output.add(currentState.getDate() + " " + ad.format(FastMath.toDegrees(eclipseAngle)) + " "
                            + ad.format(FastMath.toDegrees(pointingOffset)));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        // Propagate from the initial date for the fixed duration
        SpacecraftState finalState = propagator.propagate(initialDate.shiftedBy(12600.));

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

        System.out.println("Propagation ended at " + finalState.getDate());

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:executables.Align.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    Options options = new Options()
            .addOption(OptionBuilder.withArgName("f1").withDescription("Fasta file 1").hasArg().create("f1"))
            .addOption(OptionBuilder.withArgName("f2").withDescription("Fasta file 2").hasArg().create("f2"))
            .addOption(OptionBuilder.withArgName("s1").withDescription("sequence 1").hasArg().create("s1"))
            .addOption(OptionBuilder.withArgName("s2").withDescription("sequence 2").hasArg().create("s2"))
            .addOption(OptionBuilder.withArgName("gap-linear").withDescription("Linear gap cost").hasArg()
                    .create("gl"))
            .addOption(OptionBuilder.withArgName("gap-open").withDescription("Affine gap open cost").hasArg()
                    .create("go"))
            .addOption(OptionBuilder.withArgName("gap-extend").withDescription("Affine gap extend cost")
                    .hasArg().create("ge"))
            .addOption(OptionBuilder.withArgName("gap-function").withDescription("Gap function file").hasArg()
                    .create("gf"))
            .addOption(//from  w w w.ja v  a  2s  .c o  m
                    OptionBuilder.withArgName("gapless").withDescription("Gapless alignment").create("gapless"))
            .addOption(OptionBuilder.withArgName("mode")
                    .withDescription("Alignment mode: global,local,freeshift (Default: freeshift)").hasArg()
                    .create('m'))
            .addOption(OptionBuilder.withArgName("match").withDescription("Match score").hasArg().create("ma"))
            .addOption(OptionBuilder.withArgName("mismatch").withDescription("Mismatch score").hasArg()
                    .create("mi"))
            .addOption(OptionBuilder.withDescription("Do not append unaligned flanking sequences")
                    .create("noflank"))
            .addOption(OptionBuilder.withArgName("check").withDescription("Calculate checkscore").create('c'))
            .addOption(OptionBuilder.withArgName("format").withDescription(
                    "Output format, see String.format, parameters are: id1,id2,score,alignment (alignment only, if -f is specified); (default: '%s %s %.4f' w/o -f and '%s %s %.4f\n%s' w/ -f)")
                    .hasArg().create("format"))
            .addOption(OptionBuilder.withArgName("matrix")
                    .withDescription("Output dynamic programming matrix as well").create("matrix"))
            .addOption(OptionBuilder.withArgName("quasar-format")
                    .withDescription("Scoring matrix in quasar format").hasArg().create('q'))
            .addOption(
                    OptionBuilder.withArgName("pairs").withDescription("Pairs file").hasArg().create("pairs"))
            .addOption(OptionBuilder.withArgName("output").withDescription("Output").hasArg().create('o'))
            .addOption(OptionBuilder.withArgName("seqlib").withDescription("Seqlib file").hasArg()
                    .create("seqlib"))
            .addOption(OptionBuilder.withArgName("full").withDescription("Full output").create('f'));

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        LongScoring<CharSequence> scoring = createScoring(cmd);
        AlignmentMode mode = createMode(cmd);
        if (mode == null)
            throw new ParseException("Mode unknown: " + cmd.getOptionValue('m'));

        Iterator<MutablePair<String, String>> idIterator = createSequences(scoring, cmd);

        GapCostFunction gap = createGapFunction(cmd);
        String format = getFormat(cmd);

        LongAligner<CharSequence> aligner;
        if (gap instanceof AffineGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((AffineGapCostFunction) gap).getGapOpen(),
                    ((AffineGapCostFunction) gap).getGapExtend(), mode);
        else if (gap instanceof LinearGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, ((LinearGapCostFunction) gap).getGap(), mode);
        else if (gap instanceof InfiniteGapCostFunction)
            aligner = new LongAligner<CharSequence>(scoring, mode);
        else
            throw new RuntimeException("Gap cost function " + gap.toString() + " currently not supported!");

        SimpleAlignmentFormatter formatter = cmd.hasOption('f')
                ? new SimpleAlignmentFormatter().setAppendUnaligned(!cmd.hasOption("noflank"))
                : null;

        CheckScore checkscore = cmd.hasOption('c') ? new CheckScore() : null;
        Alignment alignment = checkscore != null || formatter != null ? new Alignment() : null;

        float score;
        String ali;
        LineOrientedFile out = new LineOrientedFile(
                cmd.hasOption('o') ? cmd.getOptionValue('o') : LineOrientedFile.STDOUT);
        Writer wr = out.startWriting();

        while (idIterator.hasNext()) {
            MutablePair<String, String> ids = idIterator.next();

            score = alignment == null ? aligner.alignCache(ids.Item1, ids.Item2)
                    : aligner.alignCache(ids.Item1, ids.Item2, alignment);
            ali = formatter != null ? formatter.format(alignment, scoring, gap, mode,
                    scoring.getCachedSubject(ids.Item1), scoring.getCachedSubject(ids.Item2)) : "";
            out.writeLine(String.format(Locale.US, format, ids.Item1, ids.Item2, score, ali));

            if (cmd.hasOption("matrix")) {
                aligner.writeMatrix(wr,
                        aligner.getScoring().getCachedSubject(ids.Item1).toString().toCharArray(),
                        aligner.getScoring().getCachedSubject(ids.Item2).toString().toCharArray());
            }

            if (checkscore != null)
                checkscore.checkScore(aligner, scoring.getCachedSubject(ids.Item1).length(),
                        scoring.getCachedSubject(ids.Item2).length(), alignment, score);

        }

        out.finishWriting();

    } catch (ParseException e) {
        e.printStackTrace();
        HelpFormatter f = new HelpFormatter();
        f.printHelp("Align", options);
    }
}

From source file:com.github.horrorho.inflatabledonkey.Main.java

/**
 * @param args the command line arguments
 * @throws IOException/*from   ww  w  . ja v  a2  s .  c  om*/
 */
public static void main(String[] args) throws IOException {
    try {
        if (!PropertyLoader.instance().test(args)) {
            return;
        }
    } catch (IllegalArgumentException ex) {
        System.out.println("Argument error: " + ex.getMessage());
        System.out.println("Try '" + Property.APP_NAME.value() + " --help' for more information.");
        System.exit(-1);
    }

    // SystemDefault HttpClient.
    // TODO concurrent
    CloseableHttpClient httpClient = HttpClients.custom().setUserAgent("CloudKit/479 (13A404)")
            .useSystemProperties().build();

    // Auth
    // TODO rework when we have UncheckedIOException for Authenticator
    Auth auth = Property.AUTHENTICATION_TOKEN.value().map(Auth::new).orElse(null);

    if (auth == null) {
        auth = Authenticator.authenticate(httpClient, Property.AUTHENTICATION_APPLEID.value().get(),
                Property.AUTHENTICATION_PASSWORD.value().get());
    }
    logger.debug("-- main() - auth: {}", auth);
    logger.info("-- main() - dsPrsID:mmeAuthToken: {}:{}", auth.dsPrsID(), auth.mmeAuthToken());

    if (Property.ARGS_TOKEN.booleanValue().orElse(false)) {
        System.out.println("DsPrsID:mmeAuthToken " + auth.dsPrsID() + ":" + auth.mmeAuthToken());
        return;
    }

    logger.info("-- main() - Apple ID: {}", Property.AUTHENTICATION_APPLEID.value());
    logger.info("-- main() - password: {}", Property.AUTHENTICATION_PASSWORD.value());
    logger.info("-- main() - token: {}", Property.AUTHENTICATION_TOKEN.value());

    // Account
    Account account = Accounts.account(httpClient, auth);

    // Backup
    Backup backup = Backup.create(httpClient, account);

    // BackupAccount
    BackupAccount backupAccount = backup.backupAccount(httpClient);
    logger.debug("-- main() - backup account: {}", backupAccount);

    // Devices
    List<Device> devices = backup.devices(httpClient, backupAccount.devices());
    logger.debug("-- main() - device count: {}", devices.size());

    // Snapshots
    List<SnapshotID> snapshotIDs = devices.stream().map(Device::snapshots).flatMap(Collection::stream)
            .collect(Collectors.toList());
    logger.info("-- main() - total snapshot count: {}", snapshotIDs.size());

    Map<String, Snapshot> snapshots = backup.snapshot(httpClient, snapshotIDs).stream().collect(
            Collectors.toMap(s -> s.record().getRecordIdentifier().getValue().getName(), Function.identity()));

    boolean repeat = false;
    do {

        for (int i = 0; i < devices.size(); i++) {
            Device device = devices.get(i);
            List<SnapshotID> deviceSnapshotIDs = device.snapshots();

            System.out.println(i + " " + device.info());

            for (int j = 0; j < deviceSnapshotIDs.size(); j++) {
                SnapshotID sid = deviceSnapshotIDs.get(j);
                System.out.println("\t" + j + snapshots.get(sid.id()).info() + "   " + sid.timestamp());
            }
        }
        if (Property.PRINT_SNAPSHOTS.booleanValue().orElse(false)) {
            return;
        }
        // Selection
        Scanner input = new Scanner(System.in);

        int deviceIndex;
        int snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (devices.size() > 1) {
            System.out.printf("Select a device [0 - %d]: ", devices.size() - 1);
            deviceIndex = input.nextInt();
        } else
            deviceIndex = Property.SELECT_DEVICE_INDEX.intValue().get();

        if (deviceIndex >= devices.size() || deviceIndex < 0) {
            System.out.println("No such device: " + deviceIndex);
            System.exit(-1);
        }

        Device device = devices.get(deviceIndex);
        System.out.println("Selected device: " + deviceIndex + ", " + device.info());

        if (device.snapshots().size() > 1) {
            System.out.printf("Select a snapshot [0 - %d]: ", device.snapshots().size() - 1);
            snapshotIndex = input.nextInt();
        } else
            snapshotIndex = Property.SELECT_SNAPSHOT_INDEX.intValue().get();

        if (snapshotIndex >= devices.get(deviceIndex).snapshots().size() || snapshotIndex < 0) {
            System.out.println("No such snapshot for selected device: " + snapshotIndex);
            System.exit(-1);
        }

        logger.info("-- main() - arg device index: {}", deviceIndex);
        logger.info("-- main() - arg snapshot index: {}", snapshotIndex);

        String selected = devices.get(deviceIndex).snapshots().get(snapshotIndex).id();
        Snapshot snapshot = snapshots.get(selected);
        System.out.println("Selected snapshot: " + snapshotIndex + ", " + snapshot.info());

        // Asset list.
        List<Assets> assetsList = backup.assetsList(httpClient, snapshot);
        logger.info("-- main() - assets count: {}", assetsList.size());

        // Domains filter --domain option
        String chosenDomain = Property.FILTER_DOMAIN.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg domain substring filter: {}", Property.FILTER_DOMAIN.value());
        // Output domains --domains option
        if (Property.PRINT_DOMAIN_LIST.booleanValue().orElse(false)) {
            System.out.println("Domains / file count:");
            assetsList.stream().filter(a -> a.domain().isPresent())
                    .map(a -> a.domain().get() + " / " + a.files().size()).sorted()
                    .forEach(System.out::println);

            System.out.print("Type a domain ('null' to exit): ");
            chosenDomain = input.next().toLowerCase(Locale.US);
            if (chosenDomain.equals("null"))
                return;
            // TODO check Assets without domain information.
        }

        String domainSubstring = chosenDomain;

        Predicate<Optional<String>> domainFilter = domain -> domain.map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.contains(domainSubstring)).orElse(false);

        List<String> files = Assets.files(assetsList, domainFilter);
        logger.info("-- main() - domain filtered file count: {}", files.size());

        // Output folders.
        Path outputFolder = Paths.get(Property.OUTPUT_FOLDER.value().orElse("output"));
        Path assetOutputFolder = outputFolder.resolve("assets"); // TODO assets value injection
        Path chunkOutputFolder = outputFolder.resolve("chunks"); // TODO chunks value injection
        logger.info("-- main() - output folder chunks: {}", chunkOutputFolder);
        logger.info("-- main() - output folder assets: {}", assetOutputFolder);

        // Download tools.
        AuthorizeAssets authorizeAssets = AuthorizeAssets.backupd();
        DiskChunkStore chunkStore = new DiskChunkStore(chunkOutputFolder);
        StandardChunkEngine chunkEngine = new StandardChunkEngine(chunkStore);
        AssetDownloader assetDownloader = new AssetDownloader(chunkEngine);
        KeyBagManager keyBagManager = backup.newKeyBagManager();

        // Mystery Moo. 
        Moo moo = new Moo(authorizeAssets, assetDownloader, keyBagManager);

        // Filename extension filter.
        String filenameExtension = Property.FILTER_EXTENSION.value().orElse("").toLowerCase(Locale.US);
        logger.info("-- main() - arg filename extension filter: {}", Property.FILTER_EXTENSION.value());

        Predicate<Asset> assetFilter = asset -> asset.relativePath().map(d -> d.toLowerCase(Locale.US))
                .map(d -> d.endsWith(filenameExtension)).orElse(false);

        // Batch process files in groups of 100.
        // TODO group files into batches based on file size.
        List<List<String>> batches = ListUtils.partition(files, 100);

        for (List<String> batch : batches) {
            List<Asset> assets = backup.assets(httpClient, batch).stream().filter(assetFilter::test)
                    .collect(Collectors.toList());
            logger.info("-- main() - filtered asset count: {}", assets.size());
            moo.download(httpClient, assets, assetOutputFolder);
        }
        System.out.print("Download other snapshot (Y/N)? ");
        repeat = input.next().toLowerCase(Locale.US).charAt(0) == 'y';
    } while (repeat == true);
}

From source file:it.acubelab.smaph.learn.TuneModel.java

public static void main(String[] args) throws Exception {
    Locale.setDefault(Locale.US);
    String freebKey = "<FREEBASE_KEY>";
    String bingKey = "<BING_KEY>";

    WikipediaApiInterface wikiApi = new WikipediaApiInterface("benchmark/cache/wid.cache",
            "benchmark/cache/redirect.cache");
    FreebaseApi freebApi = new FreebaseApi(freebKey, "freeb.cache");

    Vector<ModelConfigurationResult> bestEQFModels = new Vector<>();
    Vector<ModelConfigurationResult> bestEFModels = new Vector<>();
    int wikiSearchTopK = 5; // <======== mind this
    double gamma = 1.0;
    double C = 1.0;
    for (double editDistanceThr = 0.7; editDistanceThr <= 0.7; editDistanceThr += 0.1) {
        WikipediaToFreebase wikiToFreebase = new WikipediaToFreebase("mapdb");

        SmaphAnnotator bingAnnotator = GenerateTrainingAndTest.getDefaultBingAnnotator(wikiApi, wikiToFreebase,
                editDistanceThr, wikiSearchTopK, bingKey);
        SmaphAnnotator.setCache("bing.cache.full");

        BinaryExampleGatherer trainEntityFilterGatherer = new BinaryExampleGatherer();
        BinaryExampleGatherer develEntityFilterGatherer = new BinaryExampleGatherer();
        GenerateTrainingAndTest.gatherExamplesTrainingAndDevel(bingAnnotator, trainEntityFilterGatherer,
                develEntityFilterGatherer, wikiApi, wikiToFreebase, freebApi);

        SmaphAnnotator.unSetCache();//from  ww w . j  a v a  2s  .c  o m

        Pair<Vector<ModelConfigurationResult>, ModelConfigurationResult> modelAndStatsEF = trainIterative(
                trainEntityFilterGatherer, develEntityFilterGatherer, editDistanceThr,
                OptimizaionProfiles.MAXIMIZE_MACRO_F1, -1.0, gamma, C);
        /*
         * Pair<Vector<ModelConfigurationResult>, ModelConfigurationResult>
         * modelAndStatsEF = trainIterative( trainEmptyQueryGatherer,
         * develEmptyQueryGatherer, editDistanceThr,
         * OptimizaionProfiles.MAXIMIZE_TN, 0.02);
         */
        /*
         * for (ModelConfigurationResult res : modelAndStatsEQF.first)
         * System.out.println(res.getReadable());
         */
        for (ModelConfigurationResult res : modelAndStatsEF.first)
            System.out.println(res.getReadable());

        /* bestEQFModels.add(modelAndStatsEQF.second); */
        bestEFModels.add(modelAndStatsEF.second);
        System.gc();
    }

    for (ModelConfigurationResult modelAndStatsEQF : bestEQFModels)
        System.out.println("Best EQF:" + modelAndStatsEQF.getReadable());
    for (ModelConfigurationResult modelAndStatsEF : bestEFModels)
        System.out.println("Best EF:" + modelAndStatsEF.getReadable());

    System.out.println("Flushing Bing API...");

    SmaphAnnotator.flush();
    wikiApi.flush();
}

From source file:fr.afcepf.atod.wine.data.parser.XmlParser.java

public static void main(String[] args) {
    log.info("\t ### debut du test ###");
    /*URL url;//  w  w  w. j  a  v  a 2  s. c  o  m
    try {
     url = new URL(apiBaseUrl+"/categorymap?filter=categories(490)&apikey="+apikey); 
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/ategoryMap.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/categoryMap.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins rouges fr au dela de 100  
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+124)+price(100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/RedWines100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/RedWines100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins rouges fr entre 50 et 100
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+124)+price(50|100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/RedWines50-100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/RedWines50-100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins rouges fr entre 10 et 50
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+124)+price(10|50)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/RedWines10-50.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/RedWines10-50.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins blancs fr au dela de 100  
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+125)+price(100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/WhiteWines100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/WhiteWines100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins blancs fr entre 50 et 100
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+125)+price(50|100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/WhiteWines50-100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/WhiteWines50-100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins blancs fr entre 10 et 50
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+125)+price(10|50)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/WhiteWines10-50.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/WhiteWines10-50.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 champagnes fr au dela de 100  
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+123)+price(100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/ChampagneWines100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/ChampagneWines100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 champagnes fr entre 50 et 100 
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+123)+price(50|100)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/ChampagneWines50-100.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/ChampagneWines50-100.xml");
     FileUtils.copyURLToFile(url, file);
       }
       //100 vins ross fr
       url = new URL(apiBaseUrl+"/catalog?filter=categories(490+126)&size=100&search=France&apikey="+apikey);
       if(Files.exists(Paths.get(getResourcePath() + "FilesXML/Wines/RoseWines10-50.xml"))==false){
      File file = new File(getResourcePath() + "FilesXML/Wines/RoseWines10-50.xml");
     FileUtils.copyURLToFile(url, file);
       }                       
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }*/
    Locale.setDefault(Locale.US);
    BeanFactory bf2 = new AnnotationConfigApplicationContext(ElasticsearchConfiguration.class);
    WineService esRepository = (WineService) bf2.getBean(WineService.class);
    esRepository.deleteIdx();
    BeanFactory bf = new ClassPathXmlApplicationContext("classpath:springData.xml");
    IDaoProduct daoVin = (IDaoProduct) bf.getBean(IDaoProduct.class);
    IDaoSupplier daoSupplier = (IDaoSupplier) bf.getBean(IDaoSupplier.class);
    IDaoAdmin daoAdmin = bf.getBean(IDaoAdmin.class);
    IDaoSpecialEvent daoEvent = bf.getBean(IDaoSpecialEvent.class);
    IDaoCountry daoCountry = bf.getBean(IDaoCountry.class);
    IDaoCustomer daoCustomer = bf.getBean(IDaoCustomer.class);
    IDaoShippingMethode daoShippingMethod = bf.getBean(IDaoShippingMethode.class);
    IDaoPaymentInfo daoPayment = bf.getBean(IDaoPaymentInfo.class);
    IDaoProductFeature daoFeature = (IDaoProductFeature) bf.getBean(IDaoProductFeature.class);
    try {
        daoCountry
                .insertObj(new Country(null, "AT", "Autriche", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "BE", "Belgique", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "BG", "Bulgarie", "BGN", "Lev Bulgare", "flaticon-bulgaria-lev"));
        daoCountry.insertObj(new Country(null, "CY", "Chypre", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "CZ", "Rpublique Tchque", "CZK", "Couronne tchque",
                "flaticon-czech-republic-koruna-currency-symbol"));
        daoCountry.insertObj(
                new Country(null, "DE", "Allemagne", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "DK", "Danemark", "DKK", "Couronne danoise",
                "flaticon-denmark-krone-currency-symbol"));
        daoCountry.insertObj(new Country(null, "EE", "Estonie", "EEK", "Couronne estonienne",
                "flaticon-estonia-kroon-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "ES", "Espagne", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "FI", "Finlande", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "GB", "Royaume-Uni", "GBP", "Livre sterling",
                "flaticon-pound-symbol-variant"));
        daoCountry.insertObj(new Country(null, "GR", "Grce", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "HU", "Hongrie", "HUF", "Forint hongrois",
                "flaticon-hungary-forint-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "IE", "Irlande", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "IT", "Italie", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(
                new Country(null, "JP", "Japon", "JPY", "Yen japonais", "flaticon-yen-currency-symbol"));
        daoCountry.insertObj(new Country(null, "LT", "Lituanie", "LTL", "Litas lituanien",
                "flaticon-lithuania-litas-currency-symbol"));
        daoCountry.insertObj(
                new Country(null, "LU", "Luxembourg", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "LV", "Lettonie", "LVL", "Lats letton", "flaticon-latvia-lat"));
        daoCountry.insertObj(new Country(null, "MT", "Malte", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "NL", "Pays-Bas", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "PL", "Pologne", "PLN", "Zloty polonais",
                "flaticon-poland-zloty-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "PT", "Portugal", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry
                .insertObj(new Country(null, "RO", "Roumanie", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "SE", "Sude", "SEK", "Couronne sudoise",
                "flaticon-sweden-krona-currency-symbol"));
        daoCountry.insertObj(
                new Country(null, "SI", "Slovnie", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(
                new Country(null, "SK", "Slovaquie", "EUR", "Euro", "flaticon-euro-currency-symbol"));
        daoCountry.insertObj(new Country(null, "US", "Etats-Unis", "USD", "Dollar U.S.",
                "flaticon-dollar-currency-symbol-2"));
        daoCountry.insertObj(new Country(null, "FR", "France", "EUR", "Euro", "flaticon-euro-currency-symbol"));
    } catch (WineException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    Admin admin = null;
    Customer customer1 = null;
    Customer customer2 = null;
    Customer customer3 = null;

    try {
        admin = new Admin(null, "strateur", "admini", new Date(), "nicolastorero@gmail.com",
                "nicolastorero@gmail.com", "test1234", "0680413240", new Date(), new Date(), Civility.MR);
        customer1 = new Customer(null, "Wang", "Fen", new Date(), "fenwang@hotmail.com", "fenwang@hotmail.com",
                "test1234", "0666666666", new Date(), new Date(), Civility.MISS, true);
        customer2 = new Customer(null, "Anes", "Zouheir", new Date(), "zouheir.anes@gmail.com",
                "zouheir.anes@gmail.com", "test1234", "0666666666", new Date(), new Date(), Civility.MR, true);
        customer3 = new Customer(null, "Storero", "Nicolas", new Date(), "nicolastorero@gmail.com",
                "nicolastorero@gmail.com", "test1234", "0666666666", new Date(), new Date(), Civility.MR, true);
        daoAdmin.insertObj(admin);
        daoShippingMethod.insertObj(new ShippingMethod(null, "Colissimo"));
        daoPayment.insertObj(new PaymentInfo(null, "Visa"));
        daoCustomer.insertObj(customer1);
        daoCustomer.insertObj(customer2);
        Country c = daoCountry.findObj(29);
        customer3.addAdress(new Adress(null, "rue de rivoli", "18", "75001", "Paris", c, false));
        customer3.addAdress(new Adress(null, "rue de rivoli", "18", "75001", "Paris", c, true));
        daoCustomer.updateObj(customer3);
    } catch (WineException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    Product productRand = new Product(null, "pre", 500.0, "un produit");
    SpecialEvent se = new SpecialEvent(null, "Promotest", new Date(), new Date(), new Date(),
            "10% sur une slection de produits", true, admin, 10);
    Product productAccessorie = new ProductAccessories(null, "un mug", 25.0, "un beau mug", new Date());
    Supplier supplier1 = new Supplier(null, "Aux bon vins de Bourgogne", "05 85 74 85 69",
            "vinsbourgogne@gmail.com", new Date());
    Supplier supplier2 = new Supplier(null, "Aux bon vins de Bordeaux", "04 85 74 85 69",
            "vinsbordeaux@gmail.com", new Date());
    Supplier supplier3 = new Supplier(null, "Aux bon vins de l'Aude", "07 85 74 85 69", "vinsaude@gmail.com",
            new Date());
    try {
        //Les Set sont particulirement adapts pour manipuler une grande
        //quantit de donnes. Cependant, les performances de ceux-ci peuvent
        //tre amoindries en insertion. Gnralement, on opte pour un HashSet,
        //car il est plus performant en temps d'accs 
        ProductSupplier productSuppliers1 = new ProductSupplier();
        ProductSupplier productSuppliers2 = new ProductSupplier();
        productSuppliers1.setProduct(productRand);
        productSuppliers1.setSupplier(daoSupplier.insertObj(supplier1));
        productSuppliers1.setQuantity(30);
        productSuppliers2.setProduct(productRand);
        productSuppliers2.setSupplier(daoSupplier.insertObj(supplier2));
        productSuppliers2.setQuantity(15);
        productRand.getProductSuppliers().add(productSuppliers1);
        productRand.getProductSuppliers().add(productSuppliers2);
        daoVin.insertObj(productRand);
        ProductSupplier productSuppliers3 = new ProductSupplier();
        productSuppliers3.setProduct(productAccessorie);
        productSuppliers3.setSupplier(daoSupplier.insertObj(supplier3));
        productSuppliers3.setQuantity(20);
        productAccessorie.getProductSuppliers().add(productSuppliers3);
        daoVin.insertObj(productAccessorie);
        for (Path filepath : Files.newDirectoryStream(Paths.get(getResourcePath() + "FilesXML/Wines/"))) {
            if (filepath.getFileName().toString().contains("xml")) {
                list.add(parseSampleXml("FilesXML/Wines/" + filepath.getFileName()));
            }
        }
    } catch (WineException ex) {
        java.util.logging.Logger.getLogger(XmlParser.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        java.util.logging.Logger.getLogger(XmlParser.class.getName()).log(Level.SEVERE, null, e);
    }
    try {
        daoEvent.insertObj(se);
        if (features.isEmpty() == false) {
            for (ProductFeature pf : features.values()) {
                daoFeature.insertObj(pf);
            }
        }
        Integer cpt = 0;
        for (ArrayList<ProductWine> subList : list) {
            for (ProductWine productWine : subList) {
                ProductSupplier ps = new ProductSupplier();
                ps.setProduct(productWine);
                ps.setSupplier(supplier1);
                ps.setQuantity(randomWithRange(1, 50));
                productWine.getProductSuppliers().add(ps);
                if (cpt % 2 == 0) {
                    ProductSupplier ps2 = new ProductSupplier();
                    ps2.setProduct(productWine);
                    ps2.setSupplier(supplier2);
                    ps2.setQuantity(randomWithRange(1, 50));
                    productWine.getProductSuppliers().add(ps2);
                } else if (cpt % 3 == 0) {
                    ProductSupplier ps3 = new ProductSupplier();
                    ps3.setProduct(productWine);
                    ps3.setSupplier(supplier3);
                    ps3.setQuantity(randomWithRange(1, 50));
                    productWine.getProductSuppliers().add(ps3);
                }
                if (cpt < 11) {
                    productWine.setSpeEvent(se);
                }
                daoVin.insertObj(productWine);
                Wine esWine = new Wine(productWine.getId(), productWine.getName(), productWine.getAppellation(),
                        productWine.getPrice(), productWine.getApiId(),
                        new WineType(productWine.getProductType().getId(),
                                productWine.getProductType().getType()),
                        new WineVintage(((productWine.getProductVintage() != null)
                                ? productWine.getProductVintage().getYear().toString()
                                : "")),
                        new WineVarietal(productWine.getProductVarietal().getId(),
                                productWine.getProductVarietal().getDescription()));
                for (ProductFeature feat : productWine.getFeatures()) {
                    esWine.addFeature(new WineFeature(feat.getId(), feat.getLabel()));
                }
                esRepository.save(esWine);
                cpt++;
            }
        }
    } catch (WineException paramE) {
        // TODO Auto-generated catch block
        paramE.printStackTrace();
    }

    /*BeanFactory bf = new ClassPathXmlApplicationContext("classpath:springData.xml");
    IDaoProduct daoVin = (IDaoProduct) bf.getBean(IDaoProduct.class);
    try {
     BeanFactory bf = new ClassPathXmlApplicationContext("classpath:springData.xml");
       IDaoProduct daoVin = (IDaoProduct) bf.getBean(IDaoProduct.class);
       List<Product> list = daoVin.findAllObj();
       for (Product product : list) {
      String imagesUrl = ((ProductWine)product).getImagesUrl();
      String xmlId = ((ProductWine)product).getApiId().toString();
      String [] urls = imagesUrl.split("\\|");
      for (int i = 0; i < urls.length; i++) {
       if(urls[i].trim()!=""){
          URL url = new URL(urls[i].trim());
          String filename = FilenameUtils.getBaseName(url.toString())+"."+FilenameUtils.getExtension(url.toString());
          if(Files.exists(Paths.get(getResourcePath() + "wine_pictures/"+xmlId+"/"+filename))==false){
              File file = new File(getResourcePath() + "wine_pictures/"+xmlId+"/"+filename);
              try {
                FileUtils.copyURLToFile(url, file);
             } catch (FileNotFoundException e) {
                        
             }
           }
          if(filename==xmlId+"m.jpg"){
             if(Files.exists(Paths.get(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"l.jpg"))==false){
                 File file = new File(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"l.jpg");
                 URL url2 = new URL(urls[i].trim().replace("m.jpg", "l.jpg"));
                 try {
                   FileUtils.copyURLToFile(url2, file);
                } catch (FileNotFoundException e) {
                           
                }
              }
          }
       }
    }
             
      if(xmlId.length()==6){
       URL url = new URL("http://cdn.fluidretail.net/customers/c1477/"+xmlId.substring(0, 2)+"/"+xmlId.substring(2,4)+"/"+xmlId.substring(4)+"/_s/pi/n/"+xmlId+"_spin_spin2/main_variation_na_view_01_204x400.jpg");
        if(Files.exists(Paths.get(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"_front.jpg"))==false){
           File file = new File(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"_front.jpg");
           try {
             FileUtils.copyURLToFile(url, file);
          } catch (FileNotFoundException e) {
                     
          }
        }
        URL url2 = new URL("http://cdn.fluidretail.net/customers/c1477/"+xmlId.substring(0, 2)+"/"+xmlId.substring(2,4)+"/"+xmlId.substring(4)+"/_s/pi/n/"+xmlId+"_spin_spin2/main_variation_na_view_07_204x400.jpg");
        if(Files.exists(Paths.get(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"_back.jpg"))==false){
           File file = new File(getResourcePath() + "wine_pictures/"+xmlId+"/"+xmlId+"_back.jpg");
           try {
              FileUtils.copyURLToFile(url2, file);
           } catch (FileNotFoundException e) {
                     
          }
        }
    }
       }
    } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (WineException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
    //http://cdn.fluidretail.net/customers/c1477/13/68/80/_s/pi/n/136880_spin_spin2/main_variation_na_view_01_204x400.jpg*/
    insert_translations(bf, bf2);
    log.info("\t ### Fin du test ###");
}

From source file:Main.java

static String composeDate(int y, int m, int d) {
    return String.format(Locale.US, "%04d.%02d.%02d", y, m + 1, d);
}