Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

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

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

From source file:ch.puzzle.itc.mobiliar.test.PersistingEntityBuilder.java

/**
 * @param name/*from  w w  w .  j  a  va2 s  .  co m*/
 *             optional
 * @param installationDate
 *             optional - current date will be set as default
 * @return
 */
public static ReleaseEntity buildReleaseEntity(EntityManager em, String name, Date installationDate) {
    ReleaseEntity rel = new ReleaseEntity();
    if (installationDate != null) {
        rel.setInstallationInProductionAt(installationDate);
    } else {
        rel.setInstallationInProductionAt(new Date());
    }

    if (!StringUtils.isEmpty(name)) {
        rel.setName(name);
    } else {
        rel.setName(rel.getInstallationInProductionAt().toString());
    }
    em.persist(rel);
    return rel;
}

From source file:ch.puzzle.itc.mobiliar.test.PersistingEntityBuilder.java

/**
 * @param type//  w  w  w.j a v a2  s.c  o  m
 * @param name
 * @param group
 *             optional - new group will be created by default
 * @param rel
 *             optional - new release will be created by default
 * @return
 */
public static ResourceEntity buildResourceEntityWithRelease(EntityManager em, ResourceTypeEntity type,
        String name, ResourceGroupEntity group, ReleaseEntity rel) {
    ResourceEntity r = null;
    if (group == null) {
        r = ResourceFactory.createNewResource(name);
    } else {
        r = ResourceFactory.createNewResource(group);
    }
    r.setResourceType(type);
    if (rel == null) {
        rel = PersistingEntityBuilder.buildReleaseEntity(em, null, null);
    }
    r.setRelease(rel);
    em.persist(r);
    return r;
}

From source file:org.apache.oozie.tools.OozieDBImportCLI.java

private static <E> int importFromJSONtoDB(EntityManager entityManager, ZipFile zipFile, String filename,
        Class<E> clazz) throws JPAExecutorException, IOException {
    int wfjSize = 0;
    Gson gson = new Gson();
    ZipEntry entry = zipFile.getEntry(filename);
    if (entry != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(zipFile.getInputStream(entry), "UTF-8"));
        String line;/*from   w ww . j  av a2 s.  c o m*/
        while ((line = reader.readLine()) != null) {
            E workflow = gson.fromJson(line, clazz);
            entityManager.persist(workflow);
            wfjSize++;
        }
        reader.close();
    }
    return wfjSize;
}

From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java

/**
 * //from ww  w . j  av  a 2 s  . c om
 * @param organizationId
 * @return
 */
public synchronized static AccountManager getAccountManager(Integer organizationId) throws Exception {
    AccountManager accountManager = (AccountManager) managers.get(organizationId);
    if (accountManager == null) {
        accountManager = new AccountManager(organizationId);
        if (enableAccounting) {
            log.debug("Getting entity manager ......");
            EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);
            Account account = (Account) em.find(Account.class, organizationId);
            if (account == null) {
                Organization organization = (Organization) em.find(Organization.class, organizationId);
                account = new Account(organization);
                organization.setAccount(account);
                em.persist(account);
                em.flush();
            }
            managers.put(organizationId, accountManager);
        }
    }
    return accountManager;
}

From source file:com.fpuna.preproceso.PreprocesoTS.java

/**
 *
 * @param trainingSetFeatureList//from  w w  w .  j  a v  a2 s . c  om
 */
public static void GuardarFeature(List<TrainingSetFeature> trainingSetFeatureList) {
    EntityManager entityManager = Persistence.createEntityManagerFactory("PreprocesoTSPU")
            .createEntityManager();

    entityManager.getTransaction().begin();

    Iterator<TrainingSetFeature> Iterator = trainingSetFeatureList.iterator();
    while (Iterator.hasNext()) {
        entityManager.persist(Iterator.next());
    }

    entityManager.getTransaction().commit();
    entityManager.close();
}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Create a text message that will be stored in the database. Must be called inside a JPA transaction.
 * //from w  w w.j a v a  2s.  c om
 * @return the JPA message created
 */
static Message createMessage(String textMessage, JobInstance jobInstance, EntityManager em) {
    Message m = new Message();
    m.setTextMessage(textMessage);
    m.setJi(jobInstance.getId());
    em.persist(m);
    return m;
}

From source file:controllers.modules.opinionMiners.base.AspectOpinionMiner.java

public static Result mine(final UUID corpus, final UUID lexicon, String engine) {
    final AspectOpinionMiningEngine miningEngine = getEngine(engine);

    AspectLexicon lexiconObj = fetchResource(lexicon, AspectLexicon.class);
    DocumentCorpus corpusObj = fetchResource(corpus, DocumentCorpus.class);

    // get rid of any old results (for now).
    AspectOpinionMinedCorpus minedCorpus = new AspectOpinionMinedCorpusController().findMinedCorpus(em(),
            corpusObj, lexiconObj, engine);
    if (minedCorpus != null) {
        em().remove(minedCorpus);/*from  w  ww.j  a  va 2 s. c  o m*/
        em().getTransaction().commit();
        em().getTransaction().begin();
    }

    minedCorpus = new AspectOpinionMinedCorpus();

    final ProgressObserverToken poToken = createProgressObserverToken(minedCorpus.getId());
    watchProgress(miningEngine, "mine", poToken.id);

    final Context ctx = Context.current();

    Akka.future(new Callable<AspectOpinionMinedCorpus>() {
        @Override
        public AspectOpinionMinedCorpus call() throws Exception {
            try {
                return execute(new SareTxRunnable<AspectOpinionMinedCorpus>() {
                    @Override
                    public AspectOpinionMinedCorpus run(EntityManager em) throws Throwable {
                        bindEntityManager(em);
                        Context.current.set(ctx);

                        AspectLexicon lexiconObj = fetchResource(lexicon, AspectLexicon.class);
                        DocumentCorpus corpusObj = fetchResource(corpus, DocumentCorpus.class);

                        miningEngine.setAspectLexicon(lexiconObj).setTestCorpus(corpusObj);

                        AspectOpinionMinedCorpus minedCorpus = (AspectOpinionMinedCorpus) miningEngine.mine()
                                .setId(poToken.getId());

                        em.persist(minedCorpus);
                        return minedCorpus;
                    }
                }, ctx);
            } catch (Throwable e) {
                Logger.error(LoggedAction.getLogEntry(ctx, "failed to mine corpus"), e);
                throw new IllegalArgumentException(e);
            } finally {
                setProgressFinished(poToken.id);
            }
        }
    });

    return ok(new ProgressObserverTokenModel(poToken).asJson());
}

From source file:es.uvigo.ei.sing.rubioseq.gui.util.DBInitializer.java

/**
 * This method is responsible for the initializacion of the BD, that is:
 * - Creating the default RUbioSeqConfiguration.
 * - Creating the default users./*from  w  w  w  .  j a v a  2 s  .  c  om*/
 * - Creating a datastore pointing to "/" for the admin user.
 * 
 * This method also plays a key role in the deployment of the application 
 * since it prints the message "[DBInitializer] DB initialized." which is
 * triggered by the launch-rubioseq-gui.sh in order to know that the app. is
 * deployed and launch a browser.
 * 
 * @author hlfernandez
 */
static void initDatabase() {
    System.out.println("[DBInitializer] Initializing DB ...");

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("rubioseq-database");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = null;
    try {
        /*
         * Store Global Configuration
         */
        if (em.createQuery("SELECT u FROM RUbioSeqConfiguration u").getResultList().size() == 0) {
            RUbioSeqConfiguration config = new RUbioSeqConfiguration();
            config.setRubioseqCommand("/opt/RUbioSeq3.7/RUbioSeq.pl");
            config.setPrivateDatastoresRootDirectory("/path/to/private/datastores/root");
            config.setCreatePrivateDatastoresOnUserRegistration(false);

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(config);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Users
         */
        if (em.createQuery("SELECT u FROM User u").getResultList().size() == 0) {
            User user = new User();
            user.setUsername("rubiosequser");
            user.setPassword(DigestUtils.md5Hex("rubioseqpass"));
            user.setAdmin(false);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }

            user = new User();
            user.setUsername("admin");
            user.setPassword(DigestUtils.md5Hex("admin"));
            user.setAdmin(true);
            user.setEmail("rubiosequser@rubioseg.org");

            tx = em.getTransaction();
            try {
                tx.begin();
                em.persist(user);
                tx.commit();
            } finally {
                if (tx != null && tx.isActive()) {
                    tx.rollback();
                }
            }
        }
        /*
         * Create Default Datastores
         */
        boolean createDefaultAdminDatastore = true;
        List<User> adminUsers = getAdminUsers(em);
        @SuppressWarnings("unchecked")
        List<DataStore> datastores = (List<DataStore>) em.createQuery("SELECT d FROM DataStore d")
                .getResultList();
        for (User adminUser : adminUsers) {
            if (datastores.size() == 0) {
                createDefaultAdminDatastore = true;
            } else {
                for (DataStore d : datastores) {
                    if (d.getUser() != null && d.getUser().equals(adminUser) && d.getPath().equals("/")) {
                        createDefaultAdminDatastore = false;
                    }
                }
            }
            if (createDefaultAdminDatastore) {
                DataStore adminDS = new DataStore();
                adminDS.setUser(adminUser);
                adminDS.setPath("/");
                adminDS.setMode(DataStoreMode.Private);
                adminDS.setType(DataStoreType.Input_Output);
                adminDS.setName(adminUser.getUsername() + "_default");

                tx = em.getTransaction();
                try {
                    tx.begin();
                    em.persist(adminDS);
                    tx.commit();
                } finally {
                    if (tx != null && tx.isActive()) {
                        tx.rollback();
                    }
                }
            }
        }
    } finally {
        em.close();
    }

    System.out.println("[DBInitializer] DB initialized.");
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectReportModelHandler.java

/**
 * Save the section whith its sub sections and key questions
 * /*from w ww .  j  a  v  a  2 s. com*/
 * @param section
 *            the section to save
 * @param subSections
 *            the subsections to save.
 * @param keyQuestions
 *            the key question to save.         
 * @param em
 *            the entity manager
 */
private static void saveSectionSubSectionKeyQuestions(ProjectReportModelSection section,
        List<ProjectReportModelSection> subSections, List<KeyQuestion> keyQuestions, EntityManager em) {
    if (keyQuestions != null) {
        saveSectionKeyQuestion(section, keyQuestions, em);
    }
    if (subSections != null) {
        for (ProjectReportModelSection subSection : subSections) {
            subSection.setParentSectionModelId(section.getId());
            List<ProjectReportModelSection> subSubSections = subSection.getSubSections();
            List<KeyQuestion> questions = subSection.getKeyQuestions();
            if (subSubSections != null || keyQuestions != null) {
                // Save sub section before its sub sections and its key questions
                subSection.setSubSections(null);
                subSection.setKeyQuestions(null);
                em.persist(subSection);
                //Save the sub sections and the key questions of the subsection
                saveSectionSubSectionKeyQuestions(subSection, subSubSections, questions, em);
                subSection.setSubSections(subSubSections);
                if (subSection != null) {
                    em.merge(subSection);
                }
            } else {
                if (subSection != null) {
                    em.persist(subSection);
                }
            }
        }
    }

}

From source file:com.enioka.jqm.tools.Helpers.java

/**
 * Create a Deliverable inside the database that will track a file created by a JobInstance Must be called from inside a JPA transaction
 * /*w ww  .j  av  a 2 s.  com*/
 * @param path
 *            FilePath (relative to a root directory - cf. Node)
 * @param originalFileName
 *            FileName
 * @param fileFamily
 *            File family (may be null). E.g.: "daily report"
 * @param jobId
 *            Job Instance ID
 * @param em
 *            the EM to use.
 */
static Deliverable createDeliverable(String path, String originalFileName, String fileFamily, Integer jobId,
        EntityManager em) {
    Deliverable j = new Deliverable();

    j.setFilePath(path);
    j.setRandomId(UUID.randomUUID().toString());
    j.setFileFamily(fileFamily);
    j.setJobId(jobId);
    j.setOriginalFileName(originalFileName);

    em.persist(j);
    return j;
}