Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

In this page you can find the example usage for javax.persistence EntityManager merge.

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:org.sigmah.server.util.PersonnalEventLoader.java

public static void main(String[] args) {
    LOGGER.info("PersonnalEventLoader started");
    Integer projectId;//ww  w. j av a  2 s.  c  om
    Integer count;
    final Injector injector = Guice.createInjector(
            // Configuration module.
            new ConfigurationModule(),
            // Persistence module.
            new PersistenceModule(),
            // Mapper module.
            new MapperModule(),
            // I18nServer module.
            new I18nServerModule());

    if (args != null && args.length > 1 && StringUtils.isNumeric(args[0]) && StringUtils.isNumeric(args[1])) {
        count = Integer.valueOf(args[1]);
        projectId = Integer.valueOf(args[0]);
    } else {
        LOGGER.error("Parameters are not correct");
        LOGGER.info("PersonnalEventLoader ended with errors");
        return;
    }

    injector.getInstance(PersistService.class).start();
    final ProjectDAO projectDAO = injector.getInstance(ProjectDAO.class);
    final Project project = projectDAO.findById(projectId);
    if (project != null) {
        final EntityManager em = injector.getProvider(EntityManager.class).get();
        em.getTransaction().begin();
        LOGGER.info("Creating" + count + " PersonalEvent");
        try {
            final Calendar cal = count < 365 ? initCalendar(2016) : initCalendar(2015);
            for (int i = 0; i < count; i++) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
                PersonalEvent personEvent = personalEventFactory(cal.getTime(), project.getCalendarId(), i);
                em.merge(personEvent);
            }
            em.getTransaction().commit();
        } catch (Exception e) {
            LOGGER.error("An error occured while duplicating projects.", e);
            em.getTransaction().rollback();
        } finally {
            injector.getInstance(PersistService.class).stop();
        }
        LOGGER.info("PersonnalEventLoader ended with success");
    } else {
        LOGGER.error("Project  with id = " + projectId + " not found.");
        injector.getInstance(PersistService.class).stop();
        LOGGER.info("PersonnalEventLoader ended with errors");
    }
}

From source file:org.sigmah.server.util.Loader.java

/**
 * Load one project from data base and duplicate its multiples times for
 * test./*from ww  w.  j a  v a 2s .  com*/
 *
 * @param args
 */
public static void main(String[] args) {
    LOGGER.info("Loader project started.");
    final Injector injector = Guice.createInjector(
            // Configuration module.
            new ConfigurationModule(),
            // Persistence module.
            new PersistenceModule(),
            // Mapper module.
            new MapperModule(),
            // I18nServer module.
            new I18nServerModule());
    if (args != null) {
        if (args.length > 0 && StringUtils.isNumeric(args[0])) {
            projectId = Integer.valueOf(args[0]);
        }
        if (args.length > 1 && StringUtils.isNumeric(args[1])) {
            count = Integer.valueOf(args[1]);
        }
    }

    injector.getInstance(PersistService.class).start();
    final EntityManager em = injector.getProvider(EntityManager.class).get();
    final ProjectDAO projectDAO = injector.getInstance(ProjectDAO.class);
    final Project project = projectDAO.findById(projectId);
    if (project == null) {
        LOGGER.info("Project not found .");
        return;
    }
    LOGGER.info("Duplicating project with id: " + project + " for " + count + " times ");
    em.getTransaction().begin();
    try {
        final Class[] classes = { Organization.class, ProjectModel.class, User.class, OrgUnit.class,
                Country.class, PhaseModel.class, LogFrameModel.class };

        for (int i = 0; i < count; i++) {
            final Project newProject = Realizer.realize(project, new HashSet<>(Arrays.asList("id")), classes);
            newProject.setName("gen-" + i);
            newProject.getId();
            em.merge(newProject);
        }
        em.getTransaction().commit();
    } catch (Exception e) {
        LOGGER.error("An error occured while duplicating projects.", e);
        em.getTransaction().rollback();
    } finally {
        injector.getInstance(PersistService.class).stop();
    }
    LOGGER.info("Loader project ended.");
}

From source file:op.OPDE.java

/**
 * Hier ist die main Methode von OPDE. In dieser Methode wird auch festgestellt, wie OPDE gestartet wurde.
 * <ul>/*from ww  w. j ava2 s .  c o  m*/
 * <li>Im Standard Modus, das heisst mit graphischer Oberflche. Das drfte der hufigste Fall sein.</li>
 * <li>Im DFNImport Modus. Der wird meist auf dem Datenbankserver gebraucht um Nachts die Durchfhrungsnachweise anhand der
 * DFNImport Tabelle zu generieren. Das alles gehrt zu der Pflegeplanung.</li>
 * <li>Im BHPImport Modus. Auch dieser Modus wird auf dem DB-Server gebraucht um die Behandlungspflege Massnahmen
 * anhand der rztlichen Verordnungen zu generieren.</li>
 * </ul>
 *
 * @param args Hier stehen die Kommandozeilen Parameter. Diese werden mit
 */
public static void main(String[] args) throws Exception {
    /***
     *
     *              ____
     *            ,'  , `.
     *         ,-+-,.' _ |              ,--,
     *      ,-+-. ;   , ||            ,--.'|         ,---,
     *     ,--.'|'   |  ;|            |  |,      ,-+-. /  |
     *    |   |  ,', |  ':  ,--.--.   `--'_     ,--.'|'   |
     *    |   | /  | |  || /       \  ,' ,'|   |   |  ,"' |
     *    '   | :  | :  |,.--.  .-. | '  | |   |   | /  | |
     *    ;   . |  ; |--'  \__\/: . . |  | :   |   | |  | |
     *    |   : |  | ,     ," .--.; | '  : |__ |   | |  |/
     *    |   : '  |/     /  /  ,.  | |  | '.'||   | |--'
     *    ;   | |`-'     ;  :   .'   \;  :    ;|   |/
     *    |   ;/         |  ,     .-./|  ,   / '---'
     *    '---'           `--`---'     ---`-'
     *
     */
    uptime = SYSCalendar.now();

    //        arial14 = new Font("Arial", Font.PLAIN, 14);
    //        arial28 = new Font("Arial", Font.PLAIN, 28);

    /***
     *      _                                               ____                  _ _
     *     | |    __ _ _ __   __ _ _   _  __ _  __ _  ___  | __ ) _   _ _ __   __| | | ___
     *     | |   / _` | '_ \ / _` | | | |/ _` |/ _` |/ _ \ |  _ \| | | | '_ \ / _` | |/ _ \
     *     | |__| (_| | | | | (_| | |_| | (_| | (_| |  __/ | |_) | |_| | | | | (_| | |  __/
     *     |_____\__,_|_| |_|\__, |\__,_|\__,_|\__, |\___| |____/ \__,_|_| |_|\__,_|_|\___|
     *                       |___/             |___/
     */
    lang = ResourceBundle.getBundle("languageBundle", Locale.getDefault());

    validatorFactory = Validation.buildDefaultValidatorFactory();

    /***
     *       ____      _       _             _ _                                                        _   _
     *      / ___|__ _| |_ ___| |__     __ _| | |  _ __ ___   __ _ _   _  ___    _____  _____ ___ _ __ | |_(_) ___  _ __  ___
     *     | |   / _` | __/ __| '_ \   / _` | | | | '__/ _ \ / _` | | | |/ _ \  / _ \ \/ / __/ _ \ '_ \| __| |/ _ \| '_ \/ __|
     *     | |__| (_| | || (__| | | | | (_| | | | | | | (_) | (_| | |_| |  __/ |  __/>  < (_|  __/ |_) | |_| | (_) | | | \__ \
     *      \____\__,_|\__\___|_| |_|  \__,_|_|_| |_|  \___/ \__, |\__,_|\___|  \___/_/\_\___\___| .__/ \__|_|\___/|_| |_|___/
     *                                                       |___/                               |_|
     */
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            OPDE.fatal(e);
        }
    });

    localProps = new SortedProperties();
    props = new Properties();

    /***
     *                         _      _               ___        __
     *      _ __ ___  __ _  __| |    / \   _ __  _ __|_ _|_ __  / _| ___
     *     | '__/ _ \/ _` |/ _` |   / _ \ | '_ \| '_ \| || '_ \| |_ / _ \
     *     | | |  __/ (_| | (_| |  / ___ \| |_) | |_) | || | | |  _| (_) |
     *     |_|  \___|\__,_|\__,_| /_/   \_\ .__/| .__/___|_| |_|_|  \___/
     *                                    |_|   |_|
     */
    appInfo = new AppInfo();

    /***
     *       ____                                          _   _     _               ___        _   _
     *      / ___|___  _ __ ___  _ __ ___   __ _ _ __   __| | | |   (_)_ __   ___   / _ \ _ __ | |_(_) ___  _ __  ___
     *     | |   / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | |   | | '_ \ / _ \ | | | | '_ \| __| |/ _ \| '_ \/ __|
     *     | |__| (_) | | | | | | | | | | | (_| | | | | (_| | | |___| | | | |  __/ | |_| | |_) | |_| | (_) | | | \__ \
     *      \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_____|_|_| |_|\___|  \___/| .__/ \__|_|\___/|_| |_|___/
     *                                                                                   |_|
     */
    Options opts = new Options();
    opts.addOption("h", "hilfe", false, "Gibt die Hilfeseite fr OPDE aus.");
    opts.addOption("v", "version", false, "Zeigt die Versionsinformationen an.");
    opts.addOption("x", "experimental", false,
            "Schaltet experimentelle Programm-Module fr User frei, die Admin Rechte haben. VORSICHT !!!!");
    opts.addOption("a", "anonym", false,
            "Blendet die Bewohnernamen in allen Ansichten aus. Spezieller Modus fr Schulungsmaterial zu erstellen.");
    opts.addOption("w", "workingdir", true,
            "Damit kannst Du ein anderes Arbeitsverzeichnis setzen. Wenn Du diese Option weglsst, dann ist das Dein Benutzerverzeichnis: "
                    + System.getProperty("user.home"));
    opts.addOption("l", "debug", false,
            "Schaltet alle Ausgaben ein auf der Konsole ein, auch die, die eigentlich nur whrend der Softwareentwicklung angezeigt werden.");
    opts.addOption("t", "training", false,
            "Wird fr Einarbeitungsversionen bentigt. Frbt die Oberflche anders ein und zeigt eine Warnmeldung nach jeder Anmeldung.");
    Option optFTPserver = OptionBuilder.withLongOpt("ftpserver").withArgName("ip or hostname").hasArgs(1)
            .withDescription(lang.getString("cmdline.ftpserver")).create("f");
    opts.addOption(optFTPserver);
    //        opts.addOption("p", "pidfile", false, "Path to the pidfile which needs to be deleted when this application ends properly.");

    Option notification = OptionBuilder.withLongOpt("notification").hasOptionalArg()
            .withDescription("Schickt allen festgelegten Empfngern die jeweilige Benachrichtungs-Mail.")
            .create("n");
    notification.setArgName(
            "Liste der Empfnger (durch Komma getrennt, ohne Leerzeichen. UID verwenden). Damit kannst Du die Benachrichtigungen einschrnken. Fehlt diese Liste, erhalten ALLE Empfnger eine Mail.");
    opts.addOption(notification);

    opts.addOption(OptionBuilder.withLongOpt("jdbc").hasArg().withDescription(lang.getString("cmdline.jdbc"))
            .create("j"));

    Option dfnimport = OptionBuilder //.withArgName("datum")
            .withLongOpt("dfnimport").hasOptionalArg()
            .withDescription("Startet OPDE im DFNImport Modus fr den aktuellen Tag.").create("d");
    dfnimport.setArgName(
            "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden.");
    opts.addOption(dfnimport);

    Option bhpimport = OptionBuilder.withLongOpt("bhpimport").hasOptionalArg()
            .withDescription("Startet OPDE im BHPImport Modus fr den aktuellen Tag.").create("b");
    //        bhpimport.setOptionalArg(true);
    bhpimport.setArgName(
            "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden.");
    opts.addOption(bhpimport);

    BasicParser parser = new BasicParser();
    CommandLine cl = null;
    String footer = "http://www.Offene-Pflege.de";

    /***
     *      _          _
     *     | |__   ___| |_ __    ___  ___ _ __ ___  ___ _ __
     *     | '_ \ / _ \ | '_ \  / __|/ __| '__/ _ \/ _ \ '_ \
     *     | | | |  __/ | |_) | \__ \ (__| | |  __/  __/ | | |
     *     |_| |_|\___|_| .__/  |___/\___|_|  \___|\___|_| |_|
     *                  |_|
     */
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OffenePflege.jar [OPTION]",
                "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts,
                footer);
        System.exit(0);
    }

    // Alternative FTP-Server
    if (cl.hasOption("f")) {
        UPDATE_FTPSERVER = cl.getOptionValue("f");
    }

    if (cl.hasOption("h")) {
        HelpFormatter f = new HelpFormatter();
        f.printHelp("OffenePflege.jar [OPTION]",
                "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts,
                footer);
        System.exit(0);
    }

    String homedir = System.getProperty("user.home");
    // alternatice working dir
    if (cl.hasOption("w")) {
        File dir = new File(cl.getOptionValue("w"));
        if (dir.exists() && dir.isDirectory()) {
            homedir = dir.getAbsolutePath();
        }
    }
    opwd = homedir + sep + AppInfo.dirBase;

    /***
     *                                                                ___
     *       __ _ _ __   ___  _ __  _   _ _ __ ___   ___  _   _ ___  |__ \
     *      / _` | '_ \ / _ \| '_ \| | | | '_ ` _ \ / _ \| | | / __|   / /
     *     | (_| | | | | (_) | | | | |_| | | | | | | (_) | |_| \__ \  |_|
     *      \__,_|_| |_|\___/|_| |_|\__, |_| |_| |_|\___/ \__,_|___/  (_)
     *                              |___/
     */
    if (cl.hasOption("a")) { // anonym Modus
        //localProps.put("anonym", "true");
        anonym = true;
        anonymize = new HashMap[] { SYSConst.getNachnamenAnonym(), SYSConst.getVornamenFrauAnonym(),
                SYSConst.getVornamenMannAnonym() };
    } else {
        anonym = false;
    }

    /***
     *      _       _ _                _       _
     *     (_)_ __ (_) |_   _ __  _ __(_)_ __ | |_ ___ _ __ ___
     *     | | '_ \| | __| | '_ \| '__| | '_ \| __/ _ \ '__/ __|
     *     | | | | | | |_  | |_) | |  | | | | | ||  __/ |  \__ \
     *     |_|_| |_|_|\__| | .__/|_|  |_|_| |_|\__\___|_|  |___/
     *                     |_|
     */
    printers = new LogicalPrinters();

    /***
     *      _                 _   _                 _                                   _   _
     *     | | ___   __ _  __| | | | ___   ___ __ _| |  _ __  _ __ ___  _ __   ___ _ __| |_(_) ___  ___
     *     | |/ _ \ / _` |/ _` | | |/ _ \ / __/ _` | | | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __|
     *     | | (_) | (_| | (_| | | | (_) | (_| (_| | | | |_) | | | (_) | |_) |  __/ |  | |_| |  __/\__ \
     *     |_|\___/ \__,_|\__,_| |_|\___/ \___\__,_|_| | .__/|_|  \___/| .__/ \___|_|   \__|_|\___||___/
     *                                                 |_|             |_|
     */
    if (loadLocalProperties()) {

        //            try {
        //                FileAppender fileAppender = new FileAppender(layout, , true);
        //                logger.addAppender(fileAppender);
        //            } catch (IOException ex) {
        //                fatal(ex);
        //            }

        animation = localProps.containsKey("animation") && localProps.getProperty("animation").equals("true");

        logger.info("######### START ###########  " + OPDE.getAppInfo().getProgname() + ", v"
                + OPDE.getAppInfo().getVersion() + "/" + OPDE.getAppInfo().getBuildnum());
        logger.info(System.getProperty("os.name").toLowerCase());

        /***
         *      _     ____       _                   ___ ___
         *     (_)___|  _ \  ___| |__  _   _  __ _  |__ \__ \
         *     | / __| | | |/ _ \ '_ \| | | |/ _` |   / / / /
         *     | \__ \ |_| |  __/ |_) | |_| | (_| |  |_| |_|
         *     |_|___/____/ \___|_.__/ \__,_|\__, |  (_) (_)
         *                                   |___/
         */
        if (cl.hasOption("l") || SYSTools.catchNull(localProps.getProperty("debug")).equalsIgnoreCase("true")) {
            debug = true;
            logger.setLevel(Level.DEBUG);
        } else {
            debug = false;
            logger.setLevel(Level.INFO);
        }

        Logger.getLogger("org.hibernate").setLevel(Level.OFF);

        if (cl.hasOption("x")
                || SYSTools.catchNull(localProps.getProperty("experimental")).equalsIgnoreCase("true")) {
            experimental = true;

        } else {
            experimental = false;
        }

        if (cl.hasOption("t")
                || SYSTools.catchNull(localProps.getProperty("training")).equalsIgnoreCase("true")) {
            training = true;
        } else {
            training = false;
        }

        /***
         *          _ _                       _                                               _   _ _     _        ___ 
         *       __| | |____   _____ _ __ ___(_) ___  _ __     ___ ___  _ __ ___  _ __   __ _| |_(_) |__ | | ___  |__ \
         *      / _` | '_ \ \ / / _ \ '__/ __| |/ _ \| '_ \   / __/ _ \| '_ ` _ \| '_ \ / _` | __| | '_ \| |/ _ \   / /
         *     | (_| | |_) \ V /  __/ |  \__ \ | (_) | | | | | (_| (_) | | | | | | |_) | (_| | |_| | |_) | |  __/  |_| 
         *      \__,_|_.__/ \_/ \___|_|  |___/_|\___/|_| |_|  \___\___/|_| |_| |_| .__/ \__,_|\__|_|_.__/|_|\___|  (_) 
         *                                                                       |_|                                   
         */
        url = cl.hasOption("j") ? cl.getOptionValue("j") : localProps.getProperty("javax.persistence.jdbc.url");
        String hostkey = OPDE.getLocalProps().getProperty("hostkey");
        String cryptpassword = localProps.getProperty("javax.persistence.jdbc.password");
        DesEncrypter desEncrypter = new DesEncrypter(hostkey);
        Connection jdbcConnection = DriverManager.getConnection(url,
                localProps.getProperty("javax.persistence.jdbc.user"), desEncrypter.decrypt(cryptpassword));
        if (appInfo.getDbversion() != getDBVersion(jdbcConnection)) {
            SYSFilesTools.print(lang.getString("cant.start.with.version.mismatch"), false);
            System.exit(1);
        }
        jdbcConnection.close();

        /***
         *          _ ____   _      ____        _        _
         *         | |  _ \ / \    |  _ \  __ _| |_ __ _| |__   __ _ ___  ___
         *      _  | | |_) / _ \   | | | |/ _` | __/ _` | '_ \ / _` / __|/ _ \
         *     | |_| |  __/ ___ \  | |_| | (_| | || (_| | |_) | (_| \__ \  __/
         *      \___/|_| /_/   \_\ |____/ \__,_|\__\__,_|_.__/ \__,_|___/\___|
         *
         */
        Properties jpaProps = new Properties();
        jpaProps.put("javax.persistence.jdbc.user", localProps.getProperty("javax.persistence.jdbc.user"));

        try {
            jpaProps.put("javax.persistence.jdbc.password", desEncrypter.decrypt(cryptpassword));
        } catch (Exception e) {
            if (Desktop.isDesktopSupported()) {
                JOptionPane.showMessageDialog(null, SYSTools.xx("misc.msg.decryption.failure"),
                        appInfo.getProgname(), JOptionPane.ERROR_MESSAGE);
            } else {
                OPDE.fatal(e);
            }
            System.exit(1);
        }

        jpaProps.put("javax.persistence.jdbc.driver", localProps.getProperty("javax.persistence.jdbc.driver"));
        jpaProps.put("javax.persistence.jdbc.url", url);

        //            if (cl.hasOption("d") || cl.hasOption("d")) {  // not for BHP or DFN
        //                jpaProps.put("eclipselink.cache.shared.default", "false");
        //            } else {
        //                jpaProps.put("eclipselink.cache.shared.default", "true");
        //            }

        jpaProps.put("eclipselink.cache.shared.default", "false");
        jpaProps.put("eclipselink.session.customizer", "entity.JPAEclipseLinkSessionCustomizer");
        emf = Persistence.createEntityManagerFactory("OPDEPU", jpaProps);

        /***
         *     __     __            _
         *     \ \   / /__ _ __ ___(_) ___  _ __
         *      \ \ / / _ \ '__/ __| |/ _ \| '_ \
         *       \ V /  __/ |  \__ \ | (_) | | | |
         *        \_/ \___|_|  |___/_|\___/|_| |_|
         *
         */
        String header = SYSTools.getWindowTitle("");
        if (cl.hasOption("v")) {
            System.out.println(header);
            System.out.println(footer);
            System.exit(0);
        }

        /***
         *       ____                           _         ____  _____ _   _
         *      / ___| ___ _ __   ___ _ __ __ _| |_ ___  |  _ \|  ___| \ | |___
         *     | |  _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ | | | | |_  |  \| / __|
         *     | |_| |  __/ | | |  __/ | | (_| | ||  __/ | |_| |  _| | |\  \__ \
         *      \____|\___|_| |_|\___|_|  \__,_|\__\___| |____/|_|   |_| \_|___/
         *
         */
        if (cl.hasOption("d")) {
            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                // create the new DFNs
                DFNTools.generate(em);
                // move over the floating ones that have not yet been clicked to the current day
                DFNTools.moveFloating(em);

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        /***
         *       ____                           _         ____  _   _ ____
         *      / ___| ___ _ __   ___ _ __ __ _| |_ ___  | __ )| | | |  _ \ ___
         *     | |  _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ |  _ \| |_| | |_) / __|
         *     | |_| |  __/ | | |  __/ | | (_| | ||  __/ | |_) |  _  |  __/\__ \
         *      \____|\___|_| |_|\___|_|  \__,_|\__\___| |____/|_| |_|_|   |___/
         *
         */
        if (cl.hasOption("b")) {

            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                BHPTools.generate(em);

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        /***
         *      _   _       _   _  __ _           _   _
         *     | \ | | ___ | |_(_)/ _(_) ___ __ _| |_(_) ___  _ __
         *     |  \| |/ _ \| __| | |_| |/ __/ _` | __| |/ _ \| '_ \
         *     | |\  | (_) | |_| |  _| | (_| (_| | |_| | (_) | | | |
         *     |_| \_|\___/ \__|_|_| |_|\___\__,_|\__|_|\___/|_| |_|
         *
         */
        if (cl.hasOption("n")) {

            EntityManager em = OPDE.createEM();

            try {
                em.getTransaction().begin();
                Users rootUser = em.find(Users.class, "admin");

                SYSLogin rootLogin = em.merge(new SYSLogin(rootUser));
                OPDE.setLogin(rootLogin);
                initProps();

                EMailSystem.notify(cl.getOptionValue("n"));

                em.getTransaction().commit();
            } catch (Exception ex) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
                fatal(ex);
            } finally {
                em.close();
            }
            System.exit(0);
        }

        // to speed things later. The first connection loads the while JPA system.
        EntityManager em1 = createEM();
        em1.close();

        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        setStandardFont();

        try {
            css = SYSTools.readFileAsString(opwd + sep + AppInfo.dirTemplates + sep + AppInfo.fileStandardCSS);
        } catch (IOException ie) {
            css = "";
        }

        // JideSoft
        Lm.verifyLicense("Torsten Loehr", "Open-Pflege.de", "G9F4JW:Bm44t62pqLzp5woAD4OCSUAr2");
        WizardStyle.setStyle(WizardStyle.JAVA_STYLE);
        // JideSoft

        /***
         *      _____               __  __       _        ____
         *     |  ___| __ _ __ ___ |  \/  | __ _(_)_ __  / /\ \
         *     | |_ | '__| '_ ` _ \| |\/| |/ _` | | '_ \| |  | |
         *     |  _|| |  | | | | | | |  | | (_| | | | | | |  | |
         *     |_|  |_|  |_| |_| |_|_|  |_|\__,_|_|_| |_| |  | |
         *                                               \_\/_/
         */

        //        JFrame frm = new JFrame();
        //            frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //            frm.setLayout(new FlowLayout());
        //
        //                    frm.getContentPane().add(new PnlBodyScheme(new Properties()));
        //
        //                    frm.setVisible(true);

        SYSTools.checkForSoftwareupdates();

        mainframe = new FrmMain();

        mainframe.setVisible(true);

    }
}

From source file:org.datahack.data.uploader.UploadTables.java

public static void main(String[] args) {

    EntityManager em = ParkingDBConnector.getEntityManager();

    try {/*from ww  w . j a v a 2 s  .  com*/
        File output = File.createTempFile("WCC_ParkingStreets", "csv");
        output.deleteOnExit();
        String csvName = "WCC_ParkingStreets.csv";
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 4) {

                    ParkingStreet pS = new ParkingStreet();

                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Integer usrn = Integer.parseInt(str[1]);
                        String streetName = str[2];
                        Integer parkingZoneKey = Integer.parseInt(str[3]);
                        pS.setId(id);
                        pS.setStreetName(streetName);
                        pS.setuSRN(usrn);

                        ParkingZone pZ = em.find(ParkingZone.class, parkingZoneKey);

                        if (pZ == null) {
                            pZ = new ParkingZone();
                            pZ.setId(parkingZoneKey);

                        }

                        pS.setParkingZone(pZ);
                        em.merge(pS);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

    //Uplad Bay data
    String csvName = "bay_table.csv";

    try {
        File output = File.createTempFile("bay_table", "csv");
        output.deleteOnExit();
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 5) {

                    Bay b = new Bay();
                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Double lat = Double.parseDouble(str[1]);
                        Double lon = Double.parseDouble(str[2]);
                        Integer spaces = Integer.parseInt(str[3]);
                        Integer parkingStreetKey = Integer.parseInt(str[4]);

                        b.setId(id);
                        b.setLatitude(lat);
                        b.setLongitude(lon);
                        b.setTotalSpaces(spaces);

                        ParkingStreet find = em.find(ParkingStreet.class, parkingStreetKey);

                        if (find != null) {
                            ParkingZone pZ = find.getParkingZone();

                            if (pZ != null) {
                                Set<Bay> bays = pZ.getBays();

                                if (bays == null) {
                                    bays = new LinkedHashSet();
                                    pZ.setBays(bays);
                                }

                                bays.add(b);
                                b.setParkingZone(pZ);

                                //Calculate parking zone location as mean of lats and lons
                                Iterator<Bay> iterator = bays.iterator();
                                Integer numBays = bays.size();

                                Double latitude = 0.0;
                                Double longitude = 0.0;

                                while (iterator.hasNext()) {
                                    Bay next = iterator.next();
                                    latitude += next.getLatitude() / numBays;
                                    longitude += next.getLongitude() / numBays;

                                }

                                pZ.setLatitude(latitude);
                                pZ.setLongitude(longitude);
                            }

                            em.merge(pZ);

                            System.out.println("Bay added to zone");
                        }

                        em.merge(b);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        File output = File.createTempFile("bay_event_table", "csv");
        output.deleteOnExit();
        csvName = "bay_event_table.csv";
        URL resource = UploadTables.class.getResource("/" + csvName);
        FileUtils.copyURLToFile(resource, output);
        CSVReader reader = new CSVReader(new FileReader(output.getPath()));

        //Headings
        String[] str = reader.readNext();
        em.getTransaction().begin();
        int row = 0;
        while (str != null) {
            row++;
            str = reader.readNext();
            if (str != null) {

                if (str.length == 4) {

                    BayEvent bE = new BayEvent();

                    try {

                        Integer id = Integer.parseInt(str[0]);
                        Integer bayId = Integer.parseInt(str[1]);
                        String eventTimeString = str[2];
                        Double estimatedSpaces = Double.parseDouble(str[3]);

                        bE.setId(id);

                        Bay find = em.find(Bay.class, bayId);
                        bE.setBay(find);

                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
                        java.util.Date d;

                        d = df.parse(eventTimeString);

                        bE.setEventTime(d);

                        bE.setEstimatedSpaces(estimatedSpaces);

                        em.merge(bE);

                    } catch (NumberFormatException e) {
                        System.out.println("Failed to merge row " + row);
                    } catch (ParseException ex) {
                        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (row % 1000 == 0) {
                        em.getTransaction().commit();
                        em.clear();
                        em.getTransaction().begin();
                    }

                }

            }

        }

        em.getTransaction().commit();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(UploadTables.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.mitre.util.jpa.JpaUtil.java

public static <T, I> T saveOrUpdate(I id, EntityManager entityManager, T entity) {
    if (id == null) {
        entityManager.persist(entity);/*from  w w  w.  ja  v  a  2  s .  com*/
        entityManager.flush();
        return entity;
    } else {
        T tmp = entityManager.merge(entity);
        entityManager.flush();
        return tmp;
    }
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.LastHarvested.java

/**
 * Save or update a timestamp.//from  w w  w .  jav a  2s  .c o m
 */
public static void update(PersistenceEnv penv, final LastHarvested entity) {
    penv.tx(new Function<EntityManager, Void>() {
        public Void apply(EntityManager em) {
            LastHarvested existing = em.find(LastHarvested.class, entity.getUrl());
            if (existing != null) {
                em.persist(em.merge(entity));
            } else {
                em.persist(entity);
            }
            return null;
        }
    });
}

From source file:org.opencastproject.oaipmh.harvester.LastHarvested.java

/**
 * Save or update a timestamp.//from   ww w  .jav  a  2s.c  om
 */
public static void update(PersistenceEnv penv, final LastHarvested entity) {
    penv.tx(new Function<EntityManager, Void>() {
        @Override
        public Void apply(EntityManager em) {
            LastHarvested existing = em.find(LastHarvested.class, entity.getUrl());
            if (existing != null) {
                em.persist(em.merge(entity));
            } else {
                em.persist(entity);
            }
            return null;
        }
    });
}

From source file:au.org.ands.vocabs.toolkit.db.TaskUtils.java

/** Set the status and data fields for a task.
 * @param task The task being updated//w w  w.  ja v a 2  s .  com
 * @param status The updated status information
 * @param response The updated response
 */
public static void setTaskStatusAndData(final Task task, final String status, final String response) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    task.setStatus(status);
    task.setResponse(response);
    em.merge(task);
    em.getTransaction().commit();
    em.close();
}

From source file:com.autentia.common.util.ejb.EntityManagerUtils.java

/**
 * Saves an entity in the persistence layer. If the entity doesn't exist, this method inserts the entity. If the
 * entity already exists in the persistence layer, this method updates the entity.
 * <p>/* w ww .j  a v a  2 s.  c o m*/
 * Usage example: <code>save(em, company, company.getId())</code>
 * 
 * @param em the {@link EntityManager} where the inserto or update will be executed.
 * @param entity the entity to save.
 * @param id the primary key of the entity.
 */
public static void save(EntityManager em, Object entity, Object id) {
    if (id == null) {
        em.persist(entity);
    } else if (!em.contains(entity)) {
        em.merge(entity);
    }
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Update an existing access point in the database.
 * @param ap The access point to be update.
 *///from  ww  w  .j a v  a 2 s.c o m
public static void updateAccessPoint(final AccessPoint ap) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    em.merge(ap);
    em.getTransaction().commit();
    em.close();
}