Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:Professor.java

public static void main(String[] a) throws Exception {
        JPAUtil util = new JPAUtil();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
        EntityManager em = emf.createEntityManager();
        ProfessorService service = new ProfessorService(em);

        em.getTransaction().begin();/*w  ww  .  j a  v a  2 s.c om*/

        Professor emp = service.createProfessor(1, "name", 100);
        emp = service.createProfessor(2, "name 2", 100);

        Integer userId = 1;

        emp = em.find(Professor.class, userId);
        if (emp == null) {
            System.out.println(userId + " not found! ");
        } else {
            System.out.println("Found " + emp);
        }

        for (Object o : em.createQuery("SELECT u FROM Professor u").getResultList()) {
            System.out.println(o);
        }

        util.checkData("select * from Professor");

        em.getTransaction().commit();
        em.close();
        emf.close();
    }

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   www .j  a  va2s  .com
 * <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 {//  www .jav  a  2s . 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.apache.juddi.validation.ValidateUDDIApi.java

public static boolean isUniqueKey(EntityManager em, String entityKey) {
    Object obj = em.find(UddiEntity.class, entityKey);
    if (obj != null)
        return false;

    obj = em.find(Subscription.class, entityKey);
    if (obj != null)
        return false;

    return true;//from   www.java2 s .  com
}

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

/**
 * Save or update a timestamp.//  w  w  w.j av a2 s . co 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./* w  ww  .  j  ava  2s.  co  m*/
 */
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

/** Get a task by ID.
 * @param id task id//from  ww w  .java 2s . c om
 * @return The task
 */
public static Task getTaskById(final int id) {
    EntityManager em = DBContext.getEntityManager();
    Task t = em.find(Task.class, id);
    em.close();
    return t;
}

From source file:org.ejbca.core.ejb.log.LogEntryData.java

/** @return the found entity instance or null if the entity does not exist */
public static LogEntryData findById(EntityManager entityManager, Integer id) {
    return entityManager.find(LogEntryData.class, id);
}

From source file:nl.b3p.viewer.util.FlamingoCQL.java

private static String getUnionedFeatures(String filter, Long appLayerId, EntityManager em) throws CQLException {
    try {/*from w w  w. ja v a2 s . c  om*/
        ApplicationLayer al = em.find(ApplicationLayer.class, appLayerId);

        GeoService gs = al.getService();
        Layer l = gs.getLayer(al.getLayerName(), em);

        if (l.getFeatureType() == null) {
            throw new Exception("Layer has no feature type");
        }

        FeatureSource fs = l.getFeatureType().openGeoToolsFeatureSource();
        GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992);

        Query q = new Query(fs.getName().toString());
        if (filter != null && !filter.isEmpty()) {
            Filter attributeFilter = ECQL.toFilter(filter);
            attributeFilter = (Filter) attributeFilter.accept(new ChangeMatchCase(false), null);

            q.setFilter(attributeFilter);
        }

        q.setMaxFeatures(MAX_FEATURES);

        FeatureIterator<SimpleFeature> it = fs.getFeatures(q).features();

        try {
            Geometry gc = new GeometryCollection(null, gf);
            while (it.hasNext()) {
                SimpleFeature f = it.next();
                Geometry g = (Geometry) f.getDefaultGeometry();
                if (g != null) {
                    gc = gc.union(g);
                }
            }

            return gc.union().toText();

        } finally {
            it.close();
            fs.getDataStore().dispose();
        }
    } catch (Exception ex) {
        LOG.error("retrieving geometry for intersects filter in flamingoCQL failed: " + ex);
    }
    return null;
}

From source file:com.impetus.kvapps.runner.ExecutorService.java

/**
 * On find by user id./*from www.  j a v a  2  s.co  m*/
 * 
 * @param em         entity manager instance.
 * @param userId     user id.
 */
static User findByKey(final EntityManager em, final String userId) {
    User user = em.find(User.class, userId);
    logger.info("[On Find by key]");
    System.out.println("#######################START##########################################");
    logger.info("\n");
    logger.info("\t\t User's first name:" + user.getFirstName());
    logger.info("\t\t User's emailId:" + user.getEmailId());
    logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getName());
    logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getPassword());
    logger.info("\t\t User's total tweets:" + user.getTweets().size());
    logger.info("\n");
    System.out.println("#######################END############################################");
    logger.info("\n");
    return user;
}