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:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();// w w  w  . j a v  a2 s.c om

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:fr.amapj.service.services.saisiepermanence.PermanenceService.java

@DbWrite
public void updateorCreateDistribution(PermanenceDTO dto, boolean create) {
    EntityManager em = TransactionHelper.getEm();

    DatePermanence d = null;/* w w  w. jav a2 s  .  com*/

    if (create) {
        d = new DatePermanence();
        d.setDatePermanence(dto.datePermanence);
        em.persist(d);
    } else {
        d = em.find(DatePermanence.class, dto.id);

        List<DatePermanenceUtilisateur> dus = getAllDateDistriUtilisateur(em, d);
        for (DatePermanenceUtilisateur du : dus) {
            em.remove(du);
        }
    }

    for (PermanenceUtilisateurDTO distriUtilisateur : dto.permanenceUtilisateurs) {
        DatePermanenceUtilisateur du = new DatePermanenceUtilisateur();
        du.setDatePermanence(d);
        du.setUtilisateur(em.find(Utilisateur.class, distriUtilisateur.idUtilisateur));
        du.setNumSession(distriUtilisateur.numSession);
        em.persist(du);
    }

}

From source file:com.chiralbehaviors.CoRE.product.Product.java

@Override
public void link(Relationship r, Product child, Agency updatedBy, Agency inverseSoftware, EntityManager em) {
    ProductNetwork link = new ProductNetwork(this, r, child, updatedBy);
    em.persist(link);
    ProductNetwork inverse = new ProductNetwork(child, r.getInverse(), this, inverseSoftware);
    em.persist(inverse);/*  w  w  w.  ja  va 2s  . c o  m*/
}

From source file:de.zib.gndms.infra.tests.FileTransferActionTest.java

@BeforeClass(groups = { "net", "db", "sys", "action", "task" })
public void beforeClass() throws ServerException, IOException, ClientException {

    PropertyConfigurator.configure(logFileConfig);
    runDatabase();//from   w ww . j  a v a  2  s .  com
    transferData.initialize();

    // create orq
    FileTransferORQ orq = new FileTransferORQ();
    orq.setSourceURI(transferData.getSourceURI());
    orq.setTargetURI(transferData.getDestinationURI());
    orq.setFileMap(transferData.getFileMap());

    // create orq-calc
    FileTransferORQCalculator calc = new FileTransferORQCalculator();
    calc.setORQArguments(orq);
    // calc.setNetAux( getSys().getNetAux() );

    TransientContract con = calc.createOffer();
    PersistentContract pcon = con.acceptAt(new DateTime());

    // creating offertype
    OfferType ot;
    EntityManager em = null;
    try {
        em = getSys().getEntityManagerFactory().createEntityManager();
        ot = em.find(OfferType.class, "http://gndms.zib.de/ORQTypes/FileTransfer");
        if (ot == null) {
            ot = createFTOfferType();
            em.getTransaction().begin();
            em.persist(ot);
            em.getTransaction().commit();
        }

    } finally {
        if (em != null && em.isOpen())
            em.close();
        ot = createFTOfferType();
    }

    // create task
    task = new Task();
    task.setId(getSys().nextUUID());
    task.setDescription(orq.getDescription());
    task.setTerminationTime(pcon.getCurrentTerminationTime());
    task.setOfferType(ot);
    task.setOrq(orq);
    task.setContract(pcon);
    Calendar tt = pcon.getDeadline();
    tt.add(Calendar.YEAR, 10);
    task.setTerminationTime(tt);
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}//  ww  w. j a v  a2s  .c o m
 */
@Override
public void saveUser(User user) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    em.persist(user);
    tx.commit();
}

From source file:streaming.test.StreamingTest.java

public void creationSerie() {
    Serie serie = new Serie("Dexter", "Synopsis");

    for (Long i = 1L; i <= 8L; i++) {
        Saison saison = new Saison(i, 2005L + i);
        serie.getSaison().add(saison);//from   w w  w .j av  a  2 s . c  om
        saison.setSerie(serie);
        for (Long j = 1L; j <= i; j++) {
            Episode episode = new Episode(j, "E" + j);
            saison.getEpisode().add(episode);
            episode.setSaison(saison);
            for (Long k = 1L; k <= i; k++) {
                Lien lien = new Lien("URL" + k);
                episode.getLiens().add(lien);
                lien.setEpisode(episode);
            }
        }
    }
    EntityManager em = Persistence.createEntityManagerFactory("StreamingPU").createEntityManager();
    em.getTransaction().begin();
    em.persist(serie);
    em.getTransaction().commit();

}

From source file:com.headissue.pigeon.survey.answer.AnswerSurveyTest.java

void setUpPersistence() {
    survey = new Survey();
    survey.setName("vvk");
    survey.setStatus(SurveyStatus.ENABLED);
    survey.setCreateAt(createDate(2012, 8, 23, 12, 33));
    survey.setUpdateAt(createDate(2012, 8, 23, 12, 34));

    Question q1 = new Question();
    q1.setType(QuestionType.BOOL);/*from ww  w  .j  ava 2s . c o m*/
    q1.setTitle("allgemein");
    q1.setText("Gefllt Ihnen die neue Suche nach Vorverkaufsstellen?");
    q1.addAnswer("Ja", 1);
    q1.addAnswer("Nein", 2);
    q1.setOrderBy(1);
    survey.addQuestion(q1);

    Question q2 = new Question();
    q2.setType(QuestionType.CHOICE);
    q2.setTitle("allgemein");
    q2.setText("Bewerten Sie das Buttondesign:");
    q2.addAnswer("Eins", 1);
    q2.addAnswer("Zwei", 2);
    q2.addAnswer("Drei", 3);
    q2.addAnswer("Vier", 4);
    q2.addAnswer("Fnf", 5);
    q2.addAnswer("Sechs", 6);
    q2.setOrderBy(2);
    survey.addQuestion(q2);

    Question q3 = new Question();
    q3.setType(QuestionType.MULTIPLE);
    q3.setTitle("allgemein");
    q3.setText("Kreuzen Sie Zutreffendes an.");
    q3.addAnswer("Ich wnsche mir mehr Optionen", 1);
    q3.addAnswer("Ich wnsche mir einen Share-Button", 2);
    q3.addAnswer("Ich wnsche mir einen Drucken-Button", 3);
    q3.addAnswer("Was ist das denn? Amnesiestaub! Fantastisch!", 4);
    q3.addAnswer("Ich bin vollends zufrieden", 5);
    q3.setOrderBy(3);
    survey.addQuestion(q3);

    Question q4 = new Question();
    q4.setType(QuestionType.FREE);
    q4.setTitle("allgemein");
    q4.setText("Haben Sie noch einen Verbesserungsvorschlag?");
    q4.setOrderBy(4);
    survey.addQuestion(q4);

    EntityManager manager = factory.createEntityManager();
    manager.getTransaction().begin();
    manager.persist(survey);
    manager.persist(q1);
    manager.persist(q2);
    manager.persist(q3);
    manager.persist(q4);
    manager.getTransaction().commit();
    //manager.close();

    question1 = createValues(q1);
    question2 = createValues(q2);
    question3 = createValues(q3);
    question4 = createValues(q4);

    LogUtils.debug(log, "question 1: %s", question1);
    LogUtils.debug(log, "question 2: %s", question2);
    LogUtils.debug(log, "question 3: %s", question3);
    LogUtils.debug(log, "question 4: %s", question4);
}

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

/**
 * Creates or updates a node.<br>/*from  w ww. ja  va 2  s . c  om*/
 * This method makes the assumption metadata is valid. e.g. there MUST be a single default queue.<br>
 * Call {@link #updateConfiguration(EntityManager)} before to be sure if necessary.
 * 
 * @param nodeName
 *            name of the node that should be created or updated (if incompletely defined only)
 * @param em
 *            an EntityManager on which a transaction will be opened.
 */
static void updateNodeConfiguration(String nodeName, EntityManager em) {
    // Node
    Node n = null;
    try {
        n = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
                .getSingleResult();
    } catch (NoResultException e) {
        jqmlogger.info("Node " + nodeName
                + " does not exist in the configuration and will be created with default values");
        em.getTransaction().begin();

        n = new Node();
        n.setDlRepo(System.getProperty("user.dir") + "/outputfiles/");
        n.setName(nodeName);
        n.setPort(0);
        n.setRepo(System.getProperty("user.dir") + "/jobs/");
        n.setTmpDirectory(System.getProperty("user.dir") + "/tmp/");
        n.setRootLogLevel("INFO");
        em.persist(n);
        em.getTransaction().commit();
    }

    // Deployment parameters
    DeploymentParameter dp = null;
    long i = (Long) em.createQuery("SELECT COUNT(dp) FROM DeploymentParameter dp WHERE dp.node = :localnode")
            .setParameter("localnode", n).getSingleResult();
    if (i == 0) {
        jqmlogger.info(
                "As this node is not bound to any queue, it will be set to poll from the default queue with default parameters");
        Queue q = em.createQuery("SELECT q FROM Queue q WHERE q.defaultQueue = true", Queue.class)
                .getSingleResult();
        em.getTransaction().begin();
        dp = new DeploymentParameter();
        dp.setNbThread(5);
        dp.setNode(n);
        dp.setPollingInterval(1000);
        dp.setQueue(q);
        em.persist(dp);

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

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/*from   w  w  w. ja v a2s  .  c om*/
 */
@Override
public void storeLicenses(Set<License> licenses) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    for (License l : licenses) {
        em.persist(l);
    }
    tx.commit();
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * @see//from  w  ww.ja v a2s.co  m
 * org.apache.james.user.lib.AbstractUsersRepository#doAddUser(java.lang.String, java.lang.String)
 */
protected void doAddUser(String username, String password) throws UsersRepositoryException {
    String lowerCasedUsername = username.toLowerCase();
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername, password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        getLogger().debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username, e);
    } finally {
        entityManager.close();
    }
}