Example usage for java.util Locale setDefault

List of usage examples for java.util Locale setDefault

Introduction

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

Prototype

public static synchronized void setDefault(Locale newLocale) 

Source Link

Document

Sets the default locale for this instance of the Java Virtual Machine.

Usage

From source file:org.key2gym.client.Main.java

/**
 * The main method which performs all the task described in the class
 * description.//from  w  ww.  j  ava  2  s.co m
 * 
 * @param args an array of arguments
 */
public static void main(String[] args) {

    /*
     * Configures the logger using 'etc/logging.properties' or the default
     * logging properties file.
     */
    try (InputStream input = new FileInputStream(PATH_LOGGING_PROPERTIES)) {
        PropertyConfigurator.configure(input);
    } catch (IOException ex) {
        try (InputStream input = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(RESOURCE_DEFAULT_LOGGING_PROPERTIES)) {
            PropertyConfigurator.configure(input);

            /*
             * Notify that the default logging properties file has been
             * used.
             */
            logger.info("Could not load the logging properties file");
        } catch (IOException ex2) {
            throw new RuntimeException("Failed to initialize logging system", ex2);
        }
    }

    logger.info("Starting...");

    /*
     * Loads the built-in default properties file.
     */
    try (InputStream input = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(RESOURCE_DEFAULT_CLIENT_PROPERTIES)) {
        Properties defaultProperties = null;
        defaultProperties = new Properties();
        defaultProperties.load(input);
        properties.putAll(defaultProperties);
    } catch (IOException ex) {
        throw new RuntimeException("Failed to load the default client properties file", ex);
    }

    /*
     * Loads the local client properties file.
     */
    try (FileInputStream input = new FileInputStream(PATH_APPLICATION_PROPERTIES)) {
        Properties localProperties = null;
        localProperties = new Properties();
        localProperties.load(input);
        properties.putAll(localProperties);
    } catch (IOException ex) {
        if (logger.isEnabledFor(Level.DEBUG)) {
            logger.debug("Failed to load the client properties file", ex);
        } else {
            logger.info("Could not load the local client properties file");
        }

        /*
         * It's okay to start without the local properties file.
         */
    }

    logger.debug("Effective properties: " + properties);

    if (properties.containsKey(PROPERTY_LOCALE_COUNTRY) && properties.containsKey(PROPERTY_LOCALE_LANGUAGE)) {

        /*
         * Changes the application's locale.
         */
        Locale.setDefault(new Locale(properties.getProperty(PROPERTY_LOCALE_LANGUAGE),
                properties.getProperty(PROPERTY_LOCALE_COUNTRY)));

    } else {
        logger.debug("Using the default locale");
    }

    /*
     * Changes the application's L&F.
     */
    String ui = properties.getProperty(PROPERTY_UI);
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if (ui.equalsIgnoreCase(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
            | UnsupportedLookAndFeelException ex) {
        logger.error("Failed to change the L&F:", ex);
    }

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);

    // Loads the client application context
    context = new ClassPathXmlApplicationContext("META-INF/client.xml");

    logger.info("Started!");
    launchAndWaitMainFrame();
    logger.info("Shutting down!");

    context.close();
}

From source file:com.martinkampjensen.thesis.Main.java

/**
 * The one and only Java main method in this project.
 * <p>/* w  w  w . j  a  v a 2 s. co m*/
 * After parsing command line arguments and setting options, control will be
 * delegated to the {@link Application} class.
 * 
 * @param args an array containing command line arguments.
 */
public static void main(String[] args) {
    Locale.setDefault(Constant.LOCALE);

    Debug.line("Application started");

    final Group optionGroup = createOptionGroup();
    final CommandLine cmdLine = parse(args, optionGroup);

    if (!query(cmdLine)) {
        printHelp(optionGroup);
    }

    Debug.line("Application ended");
}

From source file:de.mendelson.comm.as2.AS2.java

/**Method to start the server on from the command line*/
public static void main(String args[]) {

    // TODO remove
    cleanup();// w ww  .j  a v a 2s.c  o m

    String language = null;
    boolean startHTTP = true;
    boolean allowAllClients = false;
    int optind;
    for (optind = 0; optind < args.length; optind++) {
        if (args[optind].toLowerCase().equals("-lang")) {
            language = args[++optind];
        } else if (args[optind].toLowerCase().equals("-nohttpserver")) {
            startHTTP = false;
        } else if (args[optind].toLowerCase().equals("-allowallclients")) {
            allowAllClients = true;
        } else if (args[optind].toLowerCase().equals("-?")) {
            AS2.printUsage();
            System.exit(1);
        } else if (args[optind].toLowerCase().equals("-h")) {
            AS2.printUsage();
            System.exit(1);
        } else if (args[optind].toLowerCase().equals("-help")) {
            AS2.printUsage();
            System.exit(1);
        }
    }
    //load language from preferences
    if (language == null) {
        PreferencesAS2 preferences = new PreferencesAS2();
        language = preferences.get(PreferencesAS2.LANGUAGE);
    }
    if (language != null) {
        if (language.toLowerCase().equals("en")) {
            Locale.setDefault(Locale.ENGLISH);
        } else if (language.toLowerCase().equals("de")) {
            Locale.setDefault(Locale.GERMAN);
        } else if (language.toLowerCase().equals("fr")) {
            Locale.setDefault(Locale.FRENCH);
        } else {
            AS2.printUsage();
            System.out.println();
            System.out.println("Language " + language + " is not supported.");
            System.exit(1);
        }
    }
    Splash splash = new Splash("/de/mendelson/comm/as2/client/Splash.jpg");
    AffineTransform transform = new AffineTransform();
    splash.setTextAntiAliasing(false);
    transform.setToScale(1.0, 1.0);
    splash.addDisplayString(new Font("Verdana", Font.BOLD, 11), 7, 262, AS2ServerVersion.getFullProductName(),
            new Color(0x65, 0xB1, 0x80), transform);
    splash.setVisible(true);
    splash.toFront();
    //start server
    try {
        //register the database drivers for the VM
        Class.forName("org.hsqldb.jdbcDriver");
        //initialize the security provider
        BCCryptoHelper helper = new BCCryptoHelper();
        helper.initialize();
        AS2Server as2Server = new AS2Server(startHTTP, allowAllClients);
        AS2Agent agent = new AS2Agent(as2Server);
    } catch (UpgradeRequiredException e) {
        //an upgrade to HSQLDB 2.x is required, delete the lock file
        Logger.getLogger(AS2Server.SERVER_LOGGER_NAME).warning(e.getMessage());
        JOptionPane.showMessageDialog(null, e.getClass().getName() + ": " + e.getMessage());
        AS2Server.deleteLockFile();
        System.exit(1);
    } catch (Throwable e) {
        if (splash != null) {
            splash.destroy();
        }
        JOptionPane.showMessageDialog(null, e.getMessage());
        System.exit(1);
    }
    //start client
    AS2Gui gui = new AS2Gui(splash, "localhost");
    gui.setVisible(true);
    splash.destroy();
    splash.dispose();
}

From source file:velocitekProStartAnalyzer.MainWindow.java

/**
 * Launch the application.//from   w ww .ja va2 s .  com
 */
public static void main(String[] args) {
    Locale.setDefault(Locale.ENGLISH);
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            setStartFinishMapMarkers();
        }
    });
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            defaultSize();

        }
    });
}

From source file:raptor.Raptor.java

/**
 * The applications main method. Takes no arguments.
 *//* w  w w.  j a  v a2s . c o m*/
public static void main(String args[]) {
    //
    // Reality check: we really need at least version MINIMUM_JAVA_VERSION
    //
    if (System.getProperty("java.version").compareTo(MINIMUM_JAVA_VERSION) < 0) {
        croak("Sorry, you are using Java version " + System.getProperty("java.version")
                + " but Raptor needs version " + MINIMUM_JAVA_VERSION + " or later.");
    }
    local = L10n.getInstance();
    Locale.setDefault(L10n.currentLocale);
    try {
        Display.setAppName("Raptor");
        display = new Display();

        createInstance();

        if (L10n.noSavedLocaleFile)
            L10n.updateLanguage(true);

        display.addListener(SWT.Close, new Listener() {
            public void handleEvent(Event event) {
                getInstance().shutdown();
            }
        });

        instance.raptorWindow = new RaptorWindow();
        instance.raptorWindow.setBlockOnOpen(true);

        // Auto login the connectors.
        Connector[] connectors = ConnectorService.getInstance().getConnectors();
        for (final Connector connector : connectors) {
            // Wait 750 milliseconds so the RaptorWindow has time to be
            // created.
            ThreadService.getInstance().scheduleOneShot(750, new Runnable() {
                public void run() {
                    // See if we need to launch the login dialog
                    boolean connected = connector.onAutoConnect();
                    if (!connected && connector instanceof FicsConnector && Raptor.getInstance()
                            .getPreferences().getBoolean(APP_IS_LAUNCHING_LOGIN_DIALOG)) {
                        ((FicsConnector) connector).showLoginDialog();
                    }

                }
            });
        }

        display.timerExec(500, new Runnable() {
            public void run() {
                try {
                    // Launch the home page after a half second it requires
                    // a
                    // RaptorWindow.
                    if (getInstance().getPreferences().getBoolean(APP_IS_LAUNCHING_HOME_PAGE)
                            && BrowserUtils.internalBrowserSupported()) {
                        BrowserUtils
                                .openUrl(getInstance().getPreferences().getString(PreferenceKeys.APP_HOME_URL));
                    }

                    // Initialize this after a half second it requires a
                    // RaptorWindow.
                    Raptor.getInstance().cursorRegistry
                            .setDefaultCursor(Raptor.getInstance().getWindow().getShell().getCursor());

                    // Initialize this after a half second. It requires a
                    // RaptorWindow.
                    // ChessBoardCacheService.getInstance();

                    // Initialize the UCIEngineService after a half second.
                    // Requires a raptor window in case there is an error.
                    // UCIEngineService.getInstance();

                    // Remove the old imageCache user directory if its
                    // there. (version .98)
                    FileUtils.deleteDir(new File(USER_RAPTOR_HOME_PATH + "/imagecache"));

                } catch (Throwable t) {
                    Raptor.getInstance().onError("Error initializing Raptor", t);
                }
            }
        });

        // Open the app window
        instance.raptorWindow.open();
    } catch (Throwable t) {
        if (t instanceof SWTException) {
            instance.LOG.info(
                    "SWTException: (If this is a widget is disposed error just ignore it its nothing)", t);

        } else {
            instance.LOG.error(
                    "Error occured in main: (If this is a widget is disposed error just ignore it its nothing)",
                    t);
        }
    } finally {
        if (instance != null) {
            instance.shutdown();
        }
    }
}

From source file:org.apache.avalon.merlin.cli.Main.java

/**
 * Main command line enty point.//from w w  w. jav a  2  s.  co m
 * @param args the command line arguments
 */
public static void main(String[] args) {
    boolean debug = false;
    try {
        //
        // parse the commandline
        //

        CommandLineParser parser = new BasicParser();
        CommandLine line = parser.parse(CL_OPTIONS, args);

        File dir = getWorkingDirectory(line);
        File cache = getMerlinSystemRepository(line);
        Artifact artifact = getDefaultImplementation(dir, line);

        debug = line.hasOption("debug");

        if (line.hasOption("version")) {
            Main.printVersionInfo(cache, artifact);
            return;
        } else if (line.hasOption("help")) {
            if (line.hasOption("lang")) {
                ResourceManager.clearResourceCache();
                String language = line.getOptionValue("lang");
                Locale locale = new Locale(language, "");
                Locale.setDefault(locale);
                REZ = ResourceManager.getPackageResources(Main.class);
            }

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("merlin [block]", " ", buildCommandLineOptions(), "", true);
            return;
        } else {
            //
            // setup the initial context
            //

            InitialContextFactory factory = new DefaultInitialContextFactory("merlin", dir);
            factory.setCacheDirectory(cache);
            factory.setOnlineMode(!line.hasOption("offline"));
            InitialContext context = factory.createInitialContext();

            //
            // process the commandline and do the real work
            //

            MAIN = new Main(context, artifact, line);
        }
    } catch (Exception exception) {
        String msg = ExceptionHelper.packException(exception, debug);
        System.err.println(msg);
        System.exit(-1);
    } catch (Throwable throwable) {
        String msg = ExceptionHelper.packException(throwable, true);
        System.err.println(msg);
        System.exit(-1);
    }
}

From source file:org.tinymediamanager.TinyMediaManager.java

/**
 * The main method./*from w ww.j a  v  a 2 s  . c  o m*/
 * 
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    // simple parse command line
    if (args != null && args.length > 0) {
        LOGGER.debug("TMM started with: " + Arrays.toString(args));
        TinyMediaManagerCMD.parseParams(args);
        System.setProperty("java.awt.headless", "true");
    } else {
        // no cmd params found, but if we are headless - display syntax
        String head = System.getProperty("java.awt.headless");
        if (head != null && head.equals("true")) {
            LOGGER.info("TMM started 'headless', and without params -> displaying syntax ");
            TinyMediaManagerCMD.printSyntax();
            System.exit(0);
        }
    }

    // check if we have write permissions to this folder
    try {
        RandomAccessFile f = new RandomAccessFile("access.test", "rw");
        f.close();
        Files.deleteIfExists(Paths.get("access.test"));
    } catch (Exception e2) {
        String msg = "Cannot write to TMM directory, have no rights - exiting.";
        if (!GraphicsEnvironment.isHeadless()) {
            JOptionPane.showMessageDialog(null, msg);
        } else {
            System.out.println(msg);
        }
        System.exit(1);
    }

    // HACK for Java 7 and JavaFX not being in boot classpath
    // In Java 8 and on, this is installed inside jre/lib/ext
    // see http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8003171 and references
    // so we check if it is already existent in "new" directory, and if not, load it via reflection ;o)
    String dir = new File(LaunchUtil.getJVMPath()).getParentFile().getParent(); // bin, one deeper
    File jfx = new File(dir, "lib/ext/jfxrt.jar");
    if (!jfx.exists()) {
        // java 7
        jfx = new File(dir, "lib/jfxrt.jar");
        if (jfx.exists()) {
            try {
                TmmOsUtils.addPath(jfx.getAbsolutePath());
            } catch (Exception e) {
                LOGGER.debug("failed to load JavaFX - using old styles...");
            }
        }
    }

    if (Globals.isDebug()) {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        LOGGER.info("=== DEBUG CLASS LOADING =============================");
        for (URL url : urls) {
            LOGGER.info(url.getFile());
        }
    }

    LOGGER.info("=====================================================");
    LOGGER.info("=== tinyMediaManager (c) 2012-2016 Manuel Laggner ===");
    LOGGER.info("=====================================================");
    LOGGER.info("tmm.version      : " + ReleaseInfo.getRealVersion());

    if (Globals.isDonator()) {
        LOGGER.info("tmm.supporter    : THANKS FOR DONATING - ALL FEATURES UNLOCKED :)");
    }

    LOGGER.info("os.name          : " + System.getProperty("os.name"));
    LOGGER.info("os.version       : " + System.getProperty("os.version"));
    LOGGER.info("os.arch          : " + System.getProperty("os.arch"));
    LOGGER.trace("network.id       : " + License.getMac());
    LOGGER.info("java.version     : " + System.getProperty("java.version"));

    if (Globals.isRunningJavaWebStart()) {
        LOGGER.info("java.webstart    : true");
    }
    if (Globals.isRunningWebSwing()) {
        LOGGER.info("java.webswing    : true");
    }

    // START character encoding debug
    debugCharacterEncoding("default encoding : ");
    System.setProperty("file.encoding", "UTF-8");
    System.setProperty("sun.jnu.encoding", "UTF-8");
    Field charset;
    try {
        // we cannot (re)set the properties while running inside JVM
        // so we trick it to reread it by setting them to null ;)
        charset = Charset.class.getDeclaredField("defaultCharset");
        charset.setAccessible(true);
        charset.set(null, null);
    } catch (Exception e) {
        LOGGER.warn("Error resetting to UTF-8", e);
    }
    debugCharacterEncoding("set encoding to  : ");
    // END character encoding debug

    // set GUI default language
    Locale.setDefault(Utils.getLocaleFromLanguage(Globals.settings.getLanguage()));
    LOGGER.info("System language  : " + System.getProperty("user.language") + "_"
            + System.getProperty("user.country"));
    LOGGER.info(
            "GUI language     : " + Locale.getDefault().getLanguage() + "_" + Locale.getDefault().getCountry());
    LOGGER.info("Scraper language : " + MovieModuleManager.MOVIE_SETTINGS.getScraperLanguage());
    LOGGER.info("TV Scraper lang  : " + TvShowModuleManager.SETTINGS.getScraperLanguage());

    // start EDT
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            boolean newVersion = !Globals.settings.isCurrentVersion(); // same snapshots/svn considered as "new", for upgrades
            try {
                Thread.setDefaultUncaughtExceptionHandler(new Log4jBackstop());
                if (!GraphicsEnvironment.isHeadless()) {
                    Thread.currentThread().setName("main");
                } else {
                    Thread.currentThread().setName("headless");
                    LOGGER.debug("starting without GUI...");
                }
                Toolkit tk = Toolkit.getDefaultToolkit();
                tk.addAWTEventListener(TmmWindowSaver.getInstance(), AWTEvent.WINDOW_EVENT_MASK);
                if (!GraphicsEnvironment.isHeadless()) {
                    setLookAndFeel();
                }
                doStartupTasks();

                // suppress logging messages from betterbeansbinding
                org.jdesktop.beansbinding.util.logging.Logger.getLogger(ELProperty.class.getName())
                        .setLevel(Level.SEVERE);

                // init ui logger
                TmmUILogCollector.init();

                LOGGER.info("=====================================================");
                // init splash
                SplashScreen splash = null;
                if (!GraphicsEnvironment.isHeadless()) {
                    splash = SplashScreen.getSplashScreen();
                }
                Graphics2D g2 = null;
                if (splash != null) {
                    g2 = splash.createGraphics();
                    if (g2 != null) {
                        Font font = new Font("Dialog", Font.PLAIN, 14);
                        g2.setFont(font);
                    } else {
                        LOGGER.debug("got no graphics from splash");
                    }
                } else {
                    LOGGER.debug("no splash found");
                }

                if (g2 != null) {
                    updateProgress(g2, "starting tinyMediaManager", 0);
                    splash.update();
                }
                LOGGER.info("starting tinyMediaManager");

                // upgrade check
                String oldVersion = Globals.settings.getVersion();
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading to new version", 10);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksBeforeDatabaseLoading(oldVersion); // do the upgrade tasks for the old version
                    Globals.settings.setCurrentVersion();
                    Globals.settings.saveSettings();
                }

                // proxy settings
                if (Globals.settings.useProxy()) {
                    LOGGER.info("setting proxy");
                    Globals.settings.setProxy();
                }

                // MediaInfo /////////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading MediaInfo libs", 20);
                    splash.update();
                }
                MediaInfoUtils.loadMediaInfo();

                // load modules //////////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading movie module", 30);
                    splash.update();
                }
                TmmModuleManager.getInstance().startUp();
                TmmModuleManager.getInstance().registerModule(MovieModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(MovieModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading TV show module", 40);
                    splash.update();
                }

                TmmModuleManager.getInstance().registerModule(TvShowModuleManager.getInstance());
                TmmModuleManager.getInstance().enableModule(TvShowModuleManager.getInstance());

                if (g2 != null) {
                    updateProgress(g2, "loading plugins", 50);
                    splash.update();
                }

                // just instantiate static - will block (takes a few secs)
                PluginManager.getInstance();
                if (ReleaseInfo.isSvnBuild()) {
                    PluginManager.loadClasspathPlugins();
                }

                // do upgrade tasks after database loading
                if (newVersion) {
                    if (g2 != null) {
                        updateProgress(g2, "upgrading database to new version", 70);
                        splash.update();
                    }
                    UpgradeTasks.performUpgradeTasksAfterDatabaseLoading(oldVersion);
                }

                // launch application ////////////////////////////////////////////
                if (g2 != null) {
                    updateProgress(g2, "loading ui", 80);
                    splash.update();
                }
                if (!GraphicsEnvironment.isHeadless()) {
                    MainWindow window = new MainWindow("tinyMediaManager / " + ReleaseInfo.getRealVersion());

                    // finished ////////////////////////////////////////////////////
                    if (g2 != null) {
                        updateProgress(g2, "finished starting :)", 100);
                        splash.update();
                    }

                    // write a random number to file, to identify this instance (for
                    // updater, tracking, whatsoever)
                    Utils.trackEvent("startup");

                    TmmWindowSaver.getInstance().loadSettings(window);
                    window.setVisible(true);

                    // wizard for new user
                    if (Globals.settings.newConfig) {
                        Globals.settings.writeDefaultSettings(); // now all plugins are resolved - write again defaults!
                        TinyMediaManagerWizard wizard = new TinyMediaManagerWizard();
                        wizard.setVisible(true);
                    }

                    // show changelog
                    if (newVersion && !ReleaseInfo.getVersion().equals(oldVersion)) {
                        // special case nightly/svn: if same snapshot version, do not display changelog
                        Utils.trackEvent("updated");
                        showChangelog();
                    }
                } else {
                    TinyMediaManagerCMD.startCommandLineTasks();
                    // wait for other tmm threads (artwork download et all)
                    while (TmmTaskManager.getInstance().poolRunning()) {
                        Thread.sleep(2000);
                    }

                    LOGGER.info("bye bye");
                    // MainWindows.shutdown()
                    try {
                        // send shutdown signal
                        TmmTaskManager.getInstance().shutdown();
                        // save unsaved settings
                        Globals.settings.saveSettings();
                        // hard kill
                        TmmTaskManager.getInstance().shutdownNow();
                        // close database connection
                        TmmModuleManager.getInstance().shutDown();
                    } catch (Exception ex) {
                        LOGGER.warn(ex.getMessage());
                    }
                    System.exit(0);
                }
            } catch (IllegalStateException e) {
                LOGGER.error("IllegalStateException", e);
                if (!GraphicsEnvironment.isHeadless() && e.getMessage().contains("file is locked")) {
                    // MessageDialog.showExceptionWindow(e);
                    ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control()); //$NON-NLS-1$
                    MessageDialog dialog = new MessageDialog(MainWindow.getActiveInstance(),
                            bundle.getString("tmm.problemdetected")); //$NON-NLS-1$
                    dialog.setImage(IconManager.ERROR);
                    dialog.setText(bundle.getString("tmm.nostart"));//$NON-NLS-1$
                    dialog.setDescription(bundle.getString("tmm.nostart.instancerunning"));//$NON-NLS-1$
                    dialog.setResizable(true);
                    dialog.pack();
                    dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                    dialog.setVisible(true);
                }
                System.exit(1);
            } catch (Exception e) {
                LOGGER.error("Exception while start of tmm", e);
                if (!GraphicsEnvironment.isHeadless()) {
                    MessageDialog.showExceptionWindow(e);
                }
                System.exit(1);
            }
        }

        /**
         * Update progress on splash screen.
         * 
         * @param text
         *          the text
         */
        private void updateProgress(Graphics2D g2, String text, int progress) {
            Object oldAAValue = g2.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
            g2.setComposite(AlphaComposite.Clear);
            g2.fillRect(20, 200, 480, 305);
            g2.setPaintMode();

            g2.setColor(new Color(51, 153, 255));
            g2.fillRect(22, 272, 452 * progress / 100, 21);

            g2.setColor(Color.black);
            g2.drawString(text + "...", 23, 310);
            int l = g2.getFontMetrics().stringWidth(ReleaseInfo.getRealVersion()); // bound right
            g2.drawString(ReleaseInfo.getRealVersion(), 480 - l, 325);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, oldAAValue);
            LOGGER.debug("Startup (" + progress + "%) " + text);
        }

        /**
         * Sets the look and feel.
         * 
         * @throws Exception
         *           the exception
         */
        private void setLookAndFeel() throws Exception {
            // get font settings
            String fontFamily = Globals.settings.getFontFamily();
            try {
                // sanity check
                fontFamily = Font.decode(fontFamily).getFamily();
            } catch (Exception e) {
                fontFamily = "Dialog";
            }

            int fontSize = Globals.settings.getFontSize();
            if (fontSize < 12) {
                fontSize = 12;
            }

            String fontString = fontFamily + " " + fontSize;

            // Get the native look and feel class name
            // String laf = UIManager.getSystemLookAndFeelClassName();
            Properties props = new Properties();
            props.setProperty("controlTextFont", fontString);
            props.setProperty("systemTextFont", fontString);
            props.setProperty("userTextFont", fontString);
            props.setProperty("menuTextFont", fontString);
            // props.setProperty("windowTitleFont", "Dialog bold 20");

            fontSize = Math.round((float) (fontSize * 0.833));
            fontString = fontFamily + " " + fontSize;

            props.setProperty("subTextFont", fontString);
            props.setProperty("backgroundColor", "237 237 237");
            props.setProperty("menuBackgroundColor", "237 237 237");
            props.setProperty("controlBackgroundColor", "237 237 237");
            props.setProperty("menuColorLight", "237 237 237");
            props.setProperty("menuColorDark", "237 237 237");
            props.setProperty("toolbarColorLight", "237 237 237");
            props.setProperty("toolbarColorDark", "237 237 237");
            props.setProperty("tooltipBackgroundColor", "255 255 255");
            props.put("windowDecoration", "system");
            props.put("logoString", "");

            // Get the look and feel class name
            com.jtattoo.plaf.luna.LunaLookAndFeel.setTheme(props);
            String laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";

            // Install the look and feel
            UIManager.setLookAndFeel(laf);
        }

        /**
         * Does some tasks at startup
         */
        private void doStartupTasks() {
            // rename downloaded files
            UpgradeTasks.renameDownloadedFiles();

            // extract templates, if GD has not already done
            Utils.extractTemplates();

            // check if a .desktop file exists
            if (Platform.isLinux()) {
                File desktop = new File(TmmOsUtils.DESKTOP_FILE);
                if (!desktop.exists()) {
                    TmmOsUtils.createDesktopFileForLinux(desktop);
                }
            }
        }

        private void showChangelog() {
            // read the changelog
            try {
                final String changelog = Utils.readFileToString(Paths.get("changelog.txt"));
                if (StringUtils.isNotBlank(changelog)) {
                    EventQueue.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            WhatsNewDialog dialog = new WhatsNewDialog(changelog);
                            dialog.pack();
                            dialog.setLocationRelativeTo(MainWindow.getActiveInstance());
                            dialog.setModalityType(ModalityType.APPLICATION_MODAL);
                            dialog.setVisible(true);
                        }
                    });
                }
            } catch (IOException e) {
                // no file found
                LOGGER.warn(e.getMessage());
            }
        }
    });
}

From source file:view.EditorView.java

public static void main(String[] args) {
    Common.setAppName("zorkGameEditor");
    Common.setAwsAccessKey(AppConfig.awsLogAccessKeyID);
    Common.setAwsSecretAccessKey(AppConfig.awsLogSecretAccessKeyID);
    FOKLogger.enableLoggingOfUncaughtExceptions();
    for (String arg : args) {
        if (arg.toLowerCase().matches("mockappversion=.*")) {
            // Set the mock version
            String version = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.setMockAppVersion(version);
        } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) {
            // Set the mock build number
            String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.setMockBuildNumber(buildnumber);
        } else if (arg.toLowerCase().matches("mockpackaging=.*")) {
            // Set the mock packaging
            String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            Common.setMockPackaging(packaging);
        } else if (arg.toLowerCase().matches("locale=.*")) {
            // set the gui language
            String guiLanguageCode = arg.substring(arg.toLowerCase().indexOf('=') + 1);
            FOKLogger.info(MainWindow.class.getName(), "Setting language: " + guiLanguageCode);
            Locale.setDefault(new Locale(guiLanguageCode));
        }/*ww w .j  av a2s.  c  o  m*/
    }

    launch(args);
}

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   w  ww  .  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;/*from  ww w.ja va2  s.  co  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 ###");
}