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:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from ww w. ja va 2  s . com*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#init(java.lang.String)
 */
@Override
public String init(final String dataSourceID) throws DeltaIndexingException {
    if (dataSourceID == null) {
        throw new DeltaIndexingException("parameter dataSourceID is null");
    }

    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();
            final DataSourceDao dao = findDataSourceDao(em, dataSourceID);
            if (dao != null && dao.getSessionId() != null) {
                throw new DeltaIndexingException(
                        "data source " + dataSourceID + " is already locked by another session");
            }

            final String sessionId = UUID.randomUUID().toString();

            final DataSourceDao lockedDao = new DataSourceDao(dataSourceID, sessionId);
            // lock the data source
            if (dao == null) {
                em.persist(lockedDao);
            } else {
                em.merge(lockedDao);
            }

            // reset visited and modified flags
            resetFlags(em, dataSourceID);

            transaction.commit();
            if (_log.isTraceEnabled()) {
                _log.trace("created session " + sessionId + " for data source: " + dataSourceID);
            }
            return sessionId;
        } catch (final DeltaIndexingException e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        } catch (final Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw new DeltaIndexingException(
                    "error initializing delta indexing for data source: " + dataSourceID, e);
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }

}

From source file:com.jada.admin.site.SiteLoader.java

public void loadCategory() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from Category where siteId = :siteId";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Category master = (Category) iterator.next();
        Category category = new Category();
        category.setCatNaturalKey(master.getCatNaturalKey());
        category.setSeqNum(master.getSeqNum());
        category.setPublished(master.getPublished());
        category.setSite(site);/*from  w  w  w . j av a2  s. c  o m*/
        category.setCatId(null);
        category.setRecUpdateBy(userId);
        category.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        category.setRecCreateBy(userId);
        category.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        category.setMenus(null);
        category.setCategoryLanguages(null);
        em.persist(category);
    }
}

From source file:nl.b3p.kaartenbalie.service.servlet.GeneralServlet.java

protected static User checkLoginLDAP(HttpServletRequest request, EntityManager em) {
    /* Probeer LDAP bind, ldapUseLdap is param in web.xml */
    User user = null;/*from  w  ww  . j a v a  2s  .co  m*/
    String authorizationHeader = request.getHeader("Authorization");
    if (MyEMFDatabase.getLdapUseLdap() != null && MyEMFDatabase.getLdapUseLdap()
            && authorizationHeader != null) {

        LDAPUtil ldapUtil = new LDAPUtil();

        String decoded = decodeBasicAuthorizationString(authorizationHeader);
        String username = parseUsername(decoded);
        String password = parsePassword(decoded);

        // check if user is in ldap
        boolean inLdap = ldapUtil.userInLdap(MyEMFDatabase.getLdapHost(), MyEMFDatabase.getLdapPort(), username,
                password, MyEMFDatabase.getLdapUserSuffix());

        // check if username already in kaartenbalie database
        user = ldapUtil.getUserByName(em, username);

        /* case 1: wel in ldap, niet in db, return nieuw gebruiker */
        if (inLdap && user == null) {
            user = new User();
            user.setUsername(username);
            user.setPassword(User.createCode());

            List<Roles> gebruikerRol = ldapUtil.getGebruikerRol(em);
            user.getRoles().retainAll(gebruikerRol);
            user.getRoles().addAll(gebruikerRol);

            Set ips = new HashSet(1);
            ips.add("0.0.0.0");
            user.setIps(ips);

            String personalUrl = User.createCode();
            user.setPersonalURL(personalUrl);

            if (MyEMFDatabase.getLdapDefaultGroup() != null && !MyEMFDatabase.getLdapDefaultGroup().isEmpty()) {
                Organization org = ldapUtil.getLDAPOrg(em, MyEMFDatabase.getLdapDefaultGroup());
                user.setMainOrganization(org);
            }

            Date userTimeOut = ldapUtil.getDefaultTimeOut(36);
            user.setTimeout(userTimeOut);

            user.setLastLoginStatus(null);

            em.persist(user);
            em.flush();

            log.debug("Gebruiker " + username + " in Ldap maar nog niet in db.");

            return user;
        }

        /* case 2: wel in ldap, wel in db, return user */
        if (inLdap && user != null) {
            user.setLastLoginStatus(null);
            em.flush();

            log.debug("Gebruiker " + username + " in Ldap en al in db.");

            return user;
        }

        /* case 3: niet in ldap, wel in db, uitroepteken zetten */
        if (!inLdap && user != null) {
            user.setLastLoginStatus(User.LOGIN_STATE_WRONG_PASSW);
            em.flush();

            log.debug("Gebruiker " + username + " niet in Ldap maar wel in db.");

            return null;
        }

        /* case 4: niet in ldap, niet in db, niets doen */
        log.debug("Gebruiker " + username + " niet in Ldap en niet in db.");
    }
    return user;
}

From source file:sf.net.experimaestro.scheduler.Resource.java

public void save(Transaction transaction) {
    final EntityManager em = transaction.em();

    // Lock all the dependencies
    // This avoids to miss any notification
    List<EntityLock> locks = new ArrayList<>();
    lockDependencies: while (true) {
        // We loop until we get all the locks - using a timeout just in case
        for (Dependency dependency : getDependencies()) {
            final EntityLock lock = dependency.from.lock(transaction, false, 100);
            if (lock == null) {
                for (EntityLock _lock : locks) {
                    _lock.close();//from   ww  w . j a  va  2 s  .c o m
                }
                continue lockDependencies;
            }

            locks.add(lock);
        }

        break;
    }

    for (Dependency dependency : getDependencies()) {
        if (!em.contains(dependency.from)) {
            dependency.from = em.find(Resource.class, dependency.from.getId());
        } else {
            em.refresh(dependency.from);
        }
    }

    prepared = true;
    em.persist(this);

    // Update the status
    updateStatus();
}

From source file:org.sigmah.server.dao.impl.FileHibernateDAO.java

/**
 * Saves a new file./*from   w  ww .j a  v  a2  s  . c  o m*/
 * 
 * @param properties
 *          The properties map of the uploaded file (see {@link FileUploadUtils}).
 * @param physicalName
 *          The uploaded file content.
 * @param size
 *          Size of the uploaded file.
 * @param id
 *          The file which gets a new version.
 * @param authorId
 *          The author id.
 * @return The file id (must be the same as the parameter).
 * @throws IOException
 */
@Transactional
protected Integer saveNewVersion(Map<String, String> properties, String physicalName, int size, Integer id,
        int authorId) throws IOException {

    final EntityManager em = em();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[save] New file version.");
    }

    // Gets the details of the name of the file.
    final String fullName = normalizeFileName(properties.get(FileUploadUtils.DOCUMENT_NAME));
    final int index = fullName.indexOf('.');

    final String name = index > 0 ? fullName.substring(0, index) : fullName;
    final String extension = index > 0 && index < fullName.length() ? fullName.substring(index + 1) : null;

    // Creates and adds the new version.
    final File file = em.find(File.class, Integer.valueOf(id));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[save] Found file: " + file.getName() + ".");
    }

    Integer versionNumber;

    Query query = em.createQuery(
            "SELECT max(fv.versionNumber)+1 AS newVersionNumber FROM FileVersion AS fv WHERE parentFile=:parentFile");
    query.setParameter("parentFile", file);
    versionNumber = (Integer) query.getSingleResult();
    if (versionNumber == null) {
        versionNumber = 0;
    }

    final FileVersion version = createVersion(versionNumber, name, extension, authorId, physicalName, size);
    version.setComments(properties.get(FileUploadUtils.DOCUMENT_COMMENTS));
    file.addVersion(version);

    em.persist(file);

    return file.getId();
}

From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java

@FXML
private void cmdUpdateSET(ActionEvent event) {
    Task taskUpdateSET = new Task<Void>() {
        @Override//from w w  w . jav a2  s.c  o m
        public Void call() {
            try {
                EntityManager entityManager = Utils.getInstance().getEntityManagerFactory()
                        .createEntityManager();
                entityManager.getTransaction().begin();
                String temp = "";
                Integer count = 0;
                entityManager.createQuery("delete from TblContribuyentes t").executeUpdate();
                for (Integer i = 0; i <= 9; i++) {
                    URL url = new URL(
                            "http://www.set.gov.py/rest/contents/download/collaboration/sites/PARAGUAY-SET/documents/informes-periodicos/ruc/ruc"
                                    + String.valueOf(i) + ".zip");
                    ZipInputStream zipStream = new ZipInputStream(url.openStream(), StandardCharsets.UTF_8);
                    zipStream.getNextEntry();

                    Scanner sc = new Scanner(zipStream, "UTF-8");

                    while (sc.hasNextLine()) {
                        String[] ruc = sc.nextLine().split("\\|");
                        temp = ruc[0] + " - " + ruc[1] + " - " + ruc[2];
                        if (ruc[0].length() > 0 && ruc[1].length() > 0 && ruc[2].length() == 1) {
                            TblContribuyentes c = new TblContribuyentes();
                            c.setRucSinDv(ruc[0]);
                            c.setRazonSocial(StringEscapeUtils.escapeSql(ruc[1]));
                            c.setDv(ruc[2]);
                            entityManager.persist(c);
                            updateMessage("Descargando listado de RUC con terminacion " + String.valueOf(i)
                                    + " - Cantidad de contribuyentes procesada: " + String.format("%,d", count)
                                    + " de aprox. 850.000.");
                            count++;
                        } else {
                            updateMessage(temp);
                        }
                    }
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                }

                updateMessage("Lista de RUC actualizada...");
                return null;
            } catch (Exception ex) {
                App.showException(this.getClass().getName(), ex.getMessage(), ex);
            }
            return null;
        }
    };
    lblUpdateSET.textProperty().bind(taskUpdateSET.messageProperty());
    new Thread(taskUpdateSET).start();
}

From source file:ec.edu.chyc.manejopersonal.controller.PersonaJpaController.java

public void edit(Persona persona) throws Exception {
    EntityManager em = null;
    try {//from  w  w  w. j  a v  a  2 s  . c o  m
        em = getEntityManager();
        em.getTransaction().begin();

        Persona personaAntigua = em.find(Persona.class, persona.getId());
        Hibernate.initialize(personaAntigua.getPersonaFirmasCollection());

        //quitar los personaTitulo que no existan en la nueva persona editada
        for (PersonaTitulo perTituloAntiguo : personaAntigua.getPersonaTitulosCollection()) {
            if (!persona.getPersonaTitulosCollection().contains(perTituloAntiguo)) {
                em.remove(perTituloAntiguo);
            }
        }
        //poner en null los ids negativos para que se puedan crear
        for (PersonaTitulo perTitulo : persona.getPersonaTitulosCollection()) {
            if (perTitulo.getId() != null && perTitulo.getId() < 0) {
                perTitulo.setId(null);
            }
            if (perTitulo.getPersona() == null) {
                perTitulo.setPersona(persona);
            }
            Titulo titulo = perTitulo.getTitulo();
            if (titulo.getId() == null || titulo.getId() < 0) {
                titulo.setId(null);
                em.persist(titulo);
            }
            if (perTitulo.getUniversidad().getId() == null || perTitulo.getUniversidad().getId() < 0) {
                perTitulo.getUniversidad().setId(null);
                em.persist(perTitulo.getUniversidad());
            }
            em.merge(perTitulo);
        }

        for (PersonaFirma perFirmaAntiguo : personaAntigua.getPersonaFirmasCollection()) {
            //revisar las firmas que estn en el antigua persona pero ya no en el nuevo editado,
            // por lo tanto si ya no estn en el nuevo editado, hay que borrar las relaciones PersonaFirma
            // pero solo si no tiene PersonaArticulo relacionado (significara que esa firma est actualmente 
            // siendo usada en un artculo, por lo tanto no de debe borrar)
            boolean firmaEnEditado = false;

            //primero revisar si la firma que existia antes de la persona, existe en el nuevo editado
            for (PersonaFirma perFirma : persona.getPersonaFirmasCollection()) {
                if (StringUtils.equalsIgnoreCase(perFirmaAntiguo.getFirma().getNombre(),
                        perFirma.getFirma().getNombre())) {
                    firmaEnEditado = true;
                    break;
                }
            }
            if (!firmaEnEditado) {
                //si es que la firma de la persona sin editar ya no existe en la persona editada, quitar la relacin PersonaFirma

                //primero verificar que la firma no sea usada en ninguna PersonaArticulo
                if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                    Firma firmaBorrar = null;
                    if (perFirmaAntiguo.getFirma().getPersonasFirmaCollection().size() == 1) {
                        //si la firma a borrar esta asignada a solo una persona (que sera la persona actual, variable: persona),
                        // colocarla a la variable para borrarla
                        //Siempre las firmas van a estar asignadas al menos a una persona, caso contrario deben ser borradas
                        //Las firmas de personas desconocidas estn ligadas a una persona: la persona con id=0
                        firmaBorrar = perFirmaAntiguo.getFirma();
                    }
                    //borrar la relacin PersonaFirma
                    em.remove(perFirmaAntiguo);
                    if (firmaBorrar != null) {
                        //borrar la firma solo si estaba asignada a una sola persona
                        firmaBorrar.getPersonasFirmaCollection().clear();
                        em.remove(firmaBorrar);
                    }
                }
            }
            /*
            if (!persona.getPersonaFirmasCollection().contains(perFirmaAntiguo)) {
            if (perFirmaAntiguo.getPersonasArticulosCollection().isEmpty()) {
                em.remove(em);
            }
            }*/
        }
        guardarPersonaFirma(em, persona);

        em.merge(persona);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward save(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws Throwable {

    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    boolean insertMode = false;
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    if (form.getMode().equals("C")) {
        insertMode = true;//from   ww w .j  ava  2s .  c  o  m
    }

    AdminBean adminBean = getAdminBean(request);
    Site site = adminBean.getSite();
    initSiteProfiles(form, site);
    CustomAttributeGroup customAttributeGroup = new CustomAttributeGroup();
    if (!insertMode) {
        customAttributeGroup = CustomAttributeGroupDAO.load(site.getSiteId(),
                Format.getLong(form.getCustomAttribGroupId()));
    }

    ActionMessages errors = validate(form, site.getSiteId());
    if (errors.size() != 0) {
        saveMessages(request, errors);
        return mapping.findForward("error");
    }

    if (insertMode) {
        customAttributeGroup.setRecCreateBy(adminBean.getUser().getUserId());
        customAttributeGroup.setRecCreateDatetime(new Date(System.currentTimeMillis()));
    }
    customAttributeGroup.setCustomAttribGroupName(form.getCustomAttribGroupName());
    customAttributeGroup.setSite(site);
    customAttributeGroup.setRecUpdateBy(adminBean.getUser().getUserId());
    customAttributeGroup.setRecUpdateDatetime(new Date(System.currentTimeMillis()));

    if (insertMode) {
        em.persist(customAttributeGroup);
    } else {
        // em.update(customAttributeGroup);
    }
    form.setMode("U");
    form.setCustomAttribGroupId(customAttributeGroup.getCustomAttribGroupId().toString());
    FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
    return mapping.findForward("success");
}

From source file:com.jada.admin.site.SiteLoader.java

public void loadState() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = "from State state where state.country.site.siteId = :siteId order by stateCode";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", Constants.SITE_SYSTEM);
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        State master = (State) iterator.next();
        State state = new State();
        PropertyUtils.copyProperties(state, master);
        state.setStateId(null);//from  w  w  w . ja  v a2s . com
        state.setRecUpdateBy(userId);
        state.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
        state.setRecCreateBy(userId);
        state.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        state.setShippingRegion(null);
        Country mc = master.getCountry();
        Country country = null;
        if (mc != null) {
            country = CountryDAO.loadByCountryName(site.getSiteId(), mc.getCountryName());
        }
        state.setCountry(country);
        state.setTaxes(null);
        em.persist(state);
    }
}

From source file:net.echinopsii.ariane.community.plugin.rabbitmq.directory.RabbitmqDirectoryBootstrap.java

private void plugDirectoryJPAProvider() {
    Company pivotal = null;//from   w w w  .ja v  a 2s.c  o  m
    Application rabbitmq = null;

    directoryJpaProvider.addSubPersistenceBundle(FrameworkUtil.getBundle(RabbitmqDirectoryBootstrap.class));

    EntityManager em = directoryJpaProvider.createEM();
    CriteriaBuilder builder = em.getCriteriaBuilder();

    CriteriaQuery<Company> cmpCriteria = builder.createQuery(Company.class);
    Root<Company> cmpRoot = cmpCriteria.from(Company.class);
    cmpCriteria.select(cmpRoot).where(builder.equal(cmpRoot.<String>get("name"), "Pivotal"));
    TypedQuery<Company> cmpQuery = em.createQuery(cmpCriteria);
    try {
        pivotal = cmpQuery.getSingleResult();
        log.debug("Pivotal company already defined ...");
    } catch (NoResultException e) {
        log.debug("Pivotal company will be defined ...");
    } catch (Exception e) {
        throw e;
    }

    CriteriaQuery<Application> appCriteria = builder.createQuery(Application.class);
    Root<Application> appRoot = appCriteria.from(Application.class);
    appCriteria.select(appRoot).where(builder.equal(appRoot.<String>get("name"), "RabbitMQ"));
    TypedQuery<Application> appQuery = em.createQuery(appCriteria);
    try {
        rabbitmq = appQuery.getSingleResult();
        log.debug("RabbitMQ application already defined ...");
    } catch (NoResultException e) {
        log.debug("RabbitMQ application will be defined ...");
    } catch (Exception e) {
        throw e;
    }

    em.getTransaction().begin();

    if (pivotal == null) {
        pivotal = new Company().setNameR("Pivotal").setDescriptionR("Pivotal");
        em.persist(pivotal);
    }

    if (rabbitmq == null) {
        rabbitmq = new Application().setNameR("RabbitMQ").setCompanyR(pivotal).setShortNameR("RabbitMQ")
                .setColorCodeR("ff6600").setDescriptionR("Robust messaging for applications");
        em.persist(rabbitmq);
    }

    if (!pivotal.getApplications().contains(rabbitmq)) {
        pivotal.getApplications().add(rabbitmq);
    }

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