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.opencastproject.search.impl.persistence.SearchServiceDatabaseImpl.java

/**
 * {@inheritDoc}//from  ww w.ja  va 2s .  c  om
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#storeMediaPackage(MediaPackage,
 *      AccessControlList, Date)
 */
@Override
public void storeMediaPackage(MediaPackage mediaPackage, AccessControlList acl, Date now)
        throws SearchServiceDatabaseException, UnauthorizedException {
    String mediaPackageXML = MediaPackageParser.getAsXml(mediaPackage);
    String mediaPackageId = mediaPackage.getIdentifier().toString();
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity entity = getSearchEntity(mediaPackageId, em);
        if (entity == null) {
            // Create new search entity
            SearchEntity searchEntity = new SearchEntity();
            searchEntity.setOrganization(securityService.getOrganization().getId());
            searchEntity.setMediaPackageId(mediaPackageId);
            searchEntity.setMediaPackageXML(mediaPackageXML);
            searchEntity.setAccessControl(AccessControlParser.toXml(acl));
            searchEntity.setModificationDate(now);
            searchEntity.setSeriesId(mediaPackage.getSeries());
            em.persist(searchEntity);
        } else {
            // Ensure this user is allowed to update this media package
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList accessList = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(accessList, currentUser, currentOrg, WRITE.toString())) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update media package " + mediaPackageId);
                }
            }
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setMediaPackageId(mediaPackageId);
            entity.setMediaPackageXML(mediaPackageXML);
            entity.setAccessControl(AccessControlParser.toXml(acl));
            entity.setModificationDate(now);
            entity.setSeriesId(mediaPackage.getSeries());
            em.merge(entity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update media package: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public Message toggleFeatured(String widgetId) {
    Message msg = new Message();
    EntityManager em = this.getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();/*from www.  j  a  v a 2  s . c om*/
    Widgetprofile widgetProfile = em.find(Widgetprofile.class, widgetId);
    Byte featured = widgetProfile.getFeatured();
    if (featured.intValue() == 0) {
        msg.setMessage("true");
        widgetProfile.setFeatured((byte) 1);
    } else {
        msg.setMessage("false");
        widgetProfile.setFeatured((byte) 0);
    }
    em.persist(widgetProfile);
    em.getTransaction().commit();
    em.close();
    return msg;
}

From source file:nl.b3p.viewer.util.databaseupdate.DatabaseSynchronizerEM.java

void updateAttributeOrder(ApplicationLayer applicationLayer, final SimpleFeatureType layerSft,
        EntityManager em) {
    List<ConfiguredAttribute> cas = applicationLayer.getAttributes();
    log.info("Sorting layer " + applicationLayer.getLayerName());
    //Sort the attributes, by featuretype: neccessary for related featuretypes
    Collections.sort(cas, new Comparator<ConfiguredAttribute>() {
        @Override/*w  w w  .j  a v a  2  s  . co m*/
        public int compare(ConfiguredAttribute o1, ConfiguredAttribute o2) {
            if (layerSft == null) {
                return -1;
            }
            if (o1.getFeatureType() == null) {
                return -1;
            }
            if (o2.getFeatureType() == null) {
                return 1;
            }
            if (o1.getFeatureType().getId().equals(layerSft.getId())) {
                return -1;
            }
            if (o2.getFeatureType().getId().equals(layerSft.getId())) {
                return 1;
            }
            return o1.getFeatureType().getId().compareTo(o2.getFeatureType().getId());
        }
    });

    if (layerSft != null) {
        // Sort the attributes by name (per featuretype)
        sortPerFeatureType(layerSft, cas);
    }

    applicationLayer.setAttributes(cas);
    em.persist(applicationLayer);

}

From source file:com.jada.order.document.CreditEngine.java

public void saveHeader() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String userId = user == null ? Constants.USERNAME_SYSTEM : user.getUserId();
    Date current = new Date();
    if (creditHeader.getCreditNum() == null) {
        creditHeader/* w w  w. ja  v a2  s.  c  om*/
                .setCreditNum(generateNumber(orderHeader.getSiteDomain().getSite(), Constants.SEQUENCE_CREDIT));
        creditHeader.setCreditDate(new Date());
        creditHeader.setRecCreateBy(userId);
        creditHeader.setRecCreateDatetime(current);
    }
    creditHeader.setRecUpdateBy(userId);
    creditHeader.setRecUpdateDatetime(current);
    if (creditHeader.getCreditHeaderId() == null) {
        em.persist(creditHeader);
    }
}

From source file:de.iai.ilcd.model.dao.SourceDao.java

/**
 * Concrete implementation required for saving of digital files
 *///from   w ww  . j  av a  2  s . c  om
@Override
public boolean checkAndPersist(Source source, PersistType pType, PrintWriter out) {
    EntityManager em = PersistenceUtil.getEntityManager();

    Source existingSource = this.getByUuid(source.getUuid().getUuid());
    if (existingSource != null) {
        if (pType == PersistType.ONLYNEW) {
            out.println(
                    "Warning: source data set with this uuid already exists in database; will ignore this data set");
            return false;
        }
    }

    EntityTransaction t = em.getTransaction();
    try {
        t.begin();
        if (existingSource != null && (pType == PersistType.MERGE)) {
            // delete first the existing one, we will use the new one
            if (out != null) {
                out.println(
                        "Notice: source data set with this uuid already exists in database; will merge this data set");
            }
            em.remove(existingSource);
            this.deleteDigitalFiles(source);
        }

        em.persist(source);

        t.commit();

        if (!super.setMostRecentVersionFlags(source.getUuidAsString())) {
            return false;
        }

        if (source != null && source.getId() != null) {
            if (!this.saveDigitalFiles(source, out)) {
                if (out != null) {
                    out.println(
                            "Warning: couldn't save all files of this source data set into database file directory: see messages above");
                }
            }
        }
        return true;

    } catch (Exception e) {
        if (out != null) {
            out.println("Can't save source data file to database because of: " + e.getMessage());
        }
        t.rollback();
        return false;
    }
}

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

/**
 * Saves a new file./*from w ww  .j a v  a  2s  . c om*/
 * 
 * @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 authorId
 *          The author id.
 * @return The id of the just saved file.
 * @throws IOException
 */
@Transactional
protected Integer saveNewFile(Map<String, String> properties, String physicalName, int size, int authorId)
        throws IOException {

    final EntityManager em = em();

    LOGGER.debug("[saveNewFile] New file.");

    // --------------------------------------------------------------------
    // STEP 1 : saves the file.
    // --------------------------------------------------------------------
    LOGGER.debug("[saveNewFile] Saves the new file.");
    final File file = new File();

    // Gets the details of the name of the file.
    final String fullName = ValueResultUtils.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;

    file.setName(name);

    // Creates and adds the new version.
    file.addVersion(createVersion(1, name, extension, authorId, physicalName, size));

    em.persist(file);

    // --------------------------------------------------------------------
    // STEP 2 : gets the current value for this list of files.
    // --------------------------------------------------------------------

    // Element id.
    final int elementId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_FLEXIBLE_ELEMENT), 0);

    // Project id.
    final int projectId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_PROJECT), 0);

    // Retrieving the current value
    final TypedQuery<Value> query = em.createQuery(
            "SELECT v FROM Value v WHERE v.containerId = :projectId and v.element.id = :elementId",
            Value.class);
    query.setParameter("projectId", projectId);
    query.setParameter("elementId", elementId);

    Value currentValue = null;

    try {
        currentValue = query.getSingleResult();
    } catch (NoResultException nre) {
        // No current value
    }

    // --------------------------------------------------------------------
    // STEP 3 : creates or updates the value with the new file id.
    // --------------------------------------------------------------------

    // The value already exists, must update it.
    if (currentValue != null) {
        currentValue.setLastModificationAction('U');

        // Sets the value (adds a new file id).
        currentValue.setValue(currentValue.getValue() + ValueResultUtils.DEFAULT_VALUE_SEPARATOR
                + String.valueOf(file.getId()));
    }
    // The value for this list of files doesn't exist already, must
    // create it.
    else {
        currentValue = new Value();

        // Creation of the value
        currentValue.setLastModificationAction('C');

        // Parent element
        final FlexibleElement element = em.find(FlexibleElement.class, elementId);
        currentValue.setElement(element);

        // Container
        currentValue.setContainerId(projectId);

        // Sets the value (one file id).
        currentValue.setValue(String.valueOf(file.getId()));
    }

    // Modifier
    final User user = em.find(User.class, authorId);
    currentValue.setLastModificationUser(user);

    // Last update date
    currentValue.setLastModificationDate(new Date());

    // Saves or updates the new value.
    em.merge(currentValue);

    return file.getId();
}

From source file:org.apache.juddi.config.Install.java

private static String installBusinessEntity(boolean isRoot, EntityManager em,
        org.uddi.api_v3.BusinessEntity rootBusinessEntity, UddiEntityPublisher rootPublisher,
        String rootPartition, Configuration config)
        throws JAXBException, DispositionReportFaultMessage, IOException {

    if (isRoot)//from  w  w  w  .  jav  a2s.co m
        validateRootBusinessEntity(rootBusinessEntity, rootPublisher, rootPartition, config);

    org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity();
    MappingApiToModel.mapBusinessEntity(rootBusinessEntity, modelBusinessEntity);

    modelBusinessEntity.setAuthorizedName(rootPublisher.getAuthorizedName());

    Date now = new Date();
    modelBusinessEntity.setCreated(now);
    modelBusinessEntity.setModified(now);
    modelBusinessEntity.setModifiedIncludingChildren(now);
    modelBusinessEntity.setNodeId(modelBusinessEntity.getEntityKey());

    for (org.apache.juddi.model.BusinessService service : modelBusinessEntity.getBusinessServices()) {
        service.setAuthorizedName(rootPublisher.getAuthorizedName());

        service.setCreated(now);
        service.setModified(now);
        service.setModifiedIncludingChildren(now);
        service.setNodeId(modelBusinessEntity.getEntityKey());

        for (org.apache.juddi.model.BindingTemplate binding : service.getBindingTemplates()) {
            binding.setAuthorizedName(rootPublisher.getAuthorizedName());

            binding.setCreated(now);
            binding.setModified(now);
            binding.setModifiedIncludingChildren(now);
            binding.setNodeId(modelBusinessEntity.getEntityKey());
        }
    }

    em.persist(modelBusinessEntity);

    return modelBusinessEntity.getEntityKey();

}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem// w w  w .  j a  va  2  s .  c o m
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java

/**
 * saves or update a newsdrilldown.//from  ww  w .ja  v a2 s  . com
 *
 * @param news the newsdrilldown to save
 * @param em   the em
 * @return the saved newsdrilldown, the new db id will be set
 * @throws Exception the exception
 */
private News saveNews(News news, EntityManager em) throws Exception {

    News n = getNews(news.getFs_id(), news.getLanguage());
    // newsdrilldown with FirstSpirit-ID exists

    if (n != null) {
        // update newsdrilldown

        n.setFs_id(news.getFs_id());
        n.setContent(news.getContent());
        n.setDate(news.getDate());
        n.setHeadline(news.getHeadline());
        n.setSubheadline(news.getSubheadline());
        n.setTeaser(news.getTeaser());
        n.setLanguage(news.getLanguage());
        n.setUrl(news.getUrl());
        n.setVersion(1);
        n.setLastmodified(news.getLastmodified());

        n.setCategories(news.getCategories());

        news = em.merge(n);
    } else {
        // save new newsdrilldown
        em.persist(news);
    }

    return news;

}

From source file:org.traccar.web.server.model.DataServiceImpl.java

private ApplicationSettings getApplicationSettings() {
    if (applicationSettings == null) {
        EntityManager entityManager = getServletEntityManager();
        synchronized (entityManager) {
            TypedQuery<ApplicationSettings> query = entityManager
                    .createQuery("SELECT x FROM ApplicationSettings x", ApplicationSettings.class);
            List<ApplicationSettings> resultList = query.getResultList();
            if (resultList == null || resultList.isEmpty()) {
                applicationSettings = new ApplicationSettings();
                entityManager.getTransaction().begin();
                try {
                    entityManager.persist(applicationSettings);
                    entityManager.getTransaction().commit();
                } catch (RuntimeException e) {
                    entityManager.getTransaction().rollback();
                    throw e;
                }/*from w ww .j  a v  a  2 s .c o  m*/
            } else {
                applicationSettings = resultList.get(0);
            }
        }
    }
    return applicationSettings;
}