Example usage for org.hibernate Session merge

List of usage examples for org.hibernate Session merge

Introduction

In this page you can find the example usage for org.hibernate Session merge.

Prototype

Object merge(Object object);

Source Link

Document

Copy the state of the given object onto the persistent object with the same identifier.

Usage

From source file:org.exoplatform.services.organization.hibernate.UserDAOImpl.java

License:Open Source License

/**
 * {@inheritDoc}//w w  w . j  a  v  a  2s  .c om
 */
public void saveUser(User user, boolean broadcast) throws Exception {
    if (user != null && !user.isEnabled())
        throw new DisabledUserException(user.getUserName());
    if (broadcast)
        preSave(user, false);

    Session session = service_.openSession();

    session.merge(user);
    session.flush();
    cache_.put(user.getUserName(), user);

    if (broadcast)
        postSave(user, false);
}

From source file:org.exoplatform.services.organization.hibernate.UserDAOImpl.java

License:Open Source License

/**
 * {@inheritDoc}// ww  w.jav a  2  s . com
 */
public User setEnabled(String userName, boolean enabled, boolean broadcast) throws Exception {
    Session session = service_.openSession();
    User foundUser = findUserByName(userName, session);

    if (foundUser == null || foundUser.isEnabled() == enabled) {
        return foundUser;
    }
    ((UserImpl) foundUser).setEnabled(enabled);
    if (broadcast)
        preSetEnabled(foundUser);

    session.merge(foundUser);
    session.flush();

    if (broadcast)
        postSetEnabled(foundUser);

    cache_.put(foundUser.getUserName(), foundUser);
    return foundUser;
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

License:Open Source License

/**
 * (nkef) Inserts vocabulary attribute into the database by searching for
 * already existing entries; if found, the corresponding ID is returned. If
 * not found, the vocabulary is extended if "insertmissingvoc" is true;
 * otherwise an SQLException is thrown/*from  w  ww.  ja  v a 2  s. c o  m*/
 * 
 * @param tableName
 *            The name of the vocabulary table.
 * @param uri
 *            The vocabulary adapting the URI to be inserted into the
 *            vocabulary table.
 * @return The ID of an already existing vocabulary table with the given
 *         uri.
 * @throws UnsupportedOperationException
 *             If we are not allowed to insert a missing vocabulary.
 */
public VocabularyAttributeElement getOrEditVocabularyAttributeElement(Session session, String vocabularyType,
        Long vocabularyElementID, String vocabularyAttributeElement, String vocabularyAttributeElementValue,
        String mode) throws SAXException {

    boolean deleteAttribute = false;

    if (mode.equals("3")) {
        deleteAttribute = true;
    }
    Class<?> c = vocAttributeClassMap.get(vocabularyType);
    Criteria c0 = session.createCriteria(c);
    c0.setCacheable(true);

    VocabularyAttrCiD vocabularyAttrCiD = new VocabularyAttrCiD();
    vocabularyAttrCiD.setAttribute(vocabularyAttributeElement);
    vocabularyAttrCiD.setId(vocabularyElementID);

    c0.add(Restrictions.idEq(vocabularyAttrCiD));

    VocabularyAttributeElement vocAttributeElement = null;

    try {
        vocAttributeElement = (VocabularyAttributeElement) c0.uniqueResult();
    } catch (ObjectNotFoundException e) {
        vocAttributeElement = null;
        e.printStackTrace();
    }

    if (vocAttributeElement == null || (deleteAttribute && (vocAttributeElement != null))
            || vocAttributeElement != null) {
        // the uri does not yet exist: insert it if allowed. According to
        // the specs, some vocabulary is not allowed to be extended; this is
        // currently ignored here
        if (!insertMissingVoc) {
            throw new UnsupportedOperationException(
                    "Not allowed to add new vocabulary - use existing vocabulary");
        } else {
            // VocabularyAttributeElement subclasses should always have
            // public zero-arg constructor to avoid problems here
            try {
                vocAttributeElement = (VocabularyAttributeElement) c.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            vocAttributeElement.setVocabularyAttrCiD(vocabularyAttrCiD);
            vocAttributeElement.setValue(vocabularyAttributeElementValue);

            if (vocAttributeElement == null) {
                session.save(vocAttributeElement);
            }

            else if (deleteAttribute) {
                Object vocabularyAttr = session.get(c, vocabularyAttrCiD);
                if (vocabularyAttr != null)
                    session.delete(vocabularyAttr);
                session.flush();
                return null;
            } else {
                session.merge(vocAttributeElement);
            }

            session.flush();
        }
    }

    return vocAttributeElement;
}

From source file:org.geomajas.layer.hibernate.HibernateLayer.java

License:Open Source License

@Override
public Object saveOrUpdate(Object feature) throws LayerException {
    // force the srid value
    enforceSrid(feature);//  w  ww .  ja  va 2  s .c om
    Session session = getSessionFactory().getCurrentSession();
    // using merge to allow detached objects, although Geomajas avoids them
    return session.merge(feature);
}

From source file:org.geoserver.hibernate.AbstractHibFacade.java

License:Open Source License

protected void delete(Info entity) {
    Session session = sessionFactory.getCurrentSession();
    Info attached = (Info) session.merge(entity);
    session.delete(attached);/*from w  ww . jav  a2  s . c  om*/
}

From source file:org.headsupdev.agile.app.files.BrowseScmUpdater.java

License:Open Source License

private void loadChangeSets(String projectId) {
    Project project = getProject(projectId);
    String scm = project.getScm();
    File working = Manager.getStorageInstance().getWorkingDirectory(project);
    boolean importing = false;
    boolean first = false;

    UpdateScmResult result;/*www. ja  va 2s. c o m*/
    // this date is set in the future so we get all changes from any timezone
    // TODO maybe there is a better way of knowing when the last change for the changeLog is?...
    Date end = new Date(System.currentTimeMillis() + (24 * 60 * 60 * 1000));
    String previousId = project.getRevision();
    try {
        result = scmManager.update(scmManager.makeScmRepository(scm), new ScmFileSet(working), false);

        if (previousId == null || previousId.equals("0")) {
            importing = true;
            first = true;
        } else if (result.getUpdatedFiles() == null || result.getUpdatedFiles().size() == 0) {
            return;
        }
    } catch (Exception e) {
        log.error("Error updating scm copy", e);
        return;
    }

    Task updateTask = new UpdateTask(project);
    try {
        Manager.getInstance().addTask(updateTask);

        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        org.headsupdev.agile.api.service.ChangeSet lastChanges = getChangeSet(project, previousId);
        Date start;
        if (lastChanges != null) {
            start = lastChanges.getDate();
        } else {
            start = new Date(0);
        }

        ScmRepository repository = scmManager.makeScmRepository(scm);
        ScmVariant variant = HeadsUpScmManager.getInstance().getScmVariant(repository.getProvider());

        ChangeLogSet changes = scmManager.changeLog(repository, new ScmFileSet(working), start, end, 0, null)
                .getChangeLog();
        File loadedWorking = new File(Manager.getStorageInstance().getApplicationDataDirectory(application),
                project.getId());
        List<ScmFile> checkedOutFiles = null;
        // create a checkout at the latest version we have recorded
        if (!loadedWorking.exists()) {
            repository.getProviderRepository().setPersistCheckout(true);
            if (!StringUtil.isEmpty(project.getScmUsername())) {
                repository.getProviderRepository().setUser(project.getScmUsername());
            }
            if (!StringUtil.isEmpty(project.getScmPassword())) {
                repository.getProviderRepository().setPassword(project.getScmPassword());
            }

            loadedWorking.mkdirs();
            if (changes == null || changes.getChangeSets() == null || changes.getChangeSets().size() == 0) {
                return;
            }

            org.apache.maven.scm.ChangeSet firstChange;
            if (!variant.isLogOldestFirst()) {
                firstChange = (org.apache.maven.scm.ChangeSet) changes.getChangeSets()
                        .get(changes.getChangeSets().size() - 1);
            } else {
                firstChange = (org.apache.maven.scm.ChangeSet) changes.getChangeSets().get(0);
            }
            ScmRevision firstRevision = new ScmRevision(
                    ((ChangeFile) firstChange.getFiles().get(0)).getRevision());
            checkedOutFiles = scmManager.checkOut(repository, new ScmFileSet(loadedWorking), firstRevision)
                    .getCheckedOutFiles();
        }
        tx.commit();
        session.close();

        if (changes == null || changes.getChangeSets() == null) {
            return;
        }

        log.info("Found " + (variant.isTransactional() ? "" : "non") + "transactional changeset with "
                + changes.getChangeSets().size() + " changes");

        List changeListings = changes.getChangeSets();
        if (!variant.isLogOldestFirst()) {
            log.info("reversing list for provider " + repository.getProvider());
            Collections.reverse(changeListings);
        }
        ListIterator changeList = changeListings.listIterator();
        while (changeList.hasNext()) {
            org.apache.maven.scm.ChangeSet changeSet = (org.apache.maven.scm.ChangeSet) changeList.next();

            String revision;
            Date current = changeSet.getDate();
            if (variant.isTransactional()) {
                revision = changeSet.getRevision();

                if (revision == null) {
                    // Compatibility code with maven-scm bugs - TODO remove
                    revision = ((ChangeFile) changeSet.getFiles().get(0)).getRevision();
                }
            } else {
                revision = changeSet.getAuthor() + ":" + changeSet.getDate();
            }

            // some scms return the revision before this time for completeness...
            if (getChangeSet(project, revision) != null) {
                // note that here we may have updated info if the scm supports duplicates - i.e. 2 merges into 1 commit...
                continue;
            }

            // get the status of each updated file. For the first revision this is from a checkout, others an update
            List<ScmChange> changedFiles = new LinkedList<ScmChange>();
            List<ScmFile> updatedFiles = null;
            boolean moved = false;
            if (first) {
                updatedFiles = checkedOutFiles;
            } else {
                if (variant.isTransactional()) {
                    UpdateScmResult updateResult = scmManager.update(repository, new ScmFileSet(loadedWorking),
                            new ScmRevision(revision), false);

                    if (updateResult.isSuccess()) {
                        updatedFiles = updateResult.getUpdatedFiles();
                    } else {
                        if (shutdown) {
                            log.warn("Terminating update, not all changes imported");
                            return;
                        }
                        moved = true;

                        log.warn(
                                "Failed to update, perhaps the repository has moved - re-checking out at the current revision");
                        FileUtil.delete(loadedWorking, true);
                        scmManager.checkOut(repository, new ScmFileSet(loadedWorking),
                                new ScmRevision(revision));
                    }
                } else {
                    // TODO fix maven-scm bug for update using Date... (then we can remove the if above)
                    UpdateScmResult updateResult = scmManager.update(repository, new ScmFileSet(loadedWorking),
                            current);
                    updatedFiles = updateResult.getUpdatedFiles();
                }
            }

            org.headsupdev.agile.api.service.ChangeSet set;
            if (variant.isTransactional()) {
                set = new TransactionalScmChangeSet(revision, changeSet.getAuthor(), changeSet.getComment(),
                        current, project);
            } else {
                set = new ScmChangeSet(changeSet.getAuthor(), changeSet.getComment(), current, project);
            }

            log.info("Requesting diff from " + previousId + " to " + revision);
            Set<Project> affected = new HashSet<Project>();
            DiffScmResult diff = null;
            if (variant.isTransactional()) {
                diff = scmManager.diff(scmManager.makeScmRepository(scm), new ScmFileSet(working),
                        variant.getStartRevisionForDiff(previousId, revision),
                        variant.getEndRevisionForDiff(previousId, revision));
            } else {
                // TODO fix glaring omission in maven-scm where the diff( Date...Date ) is not supported...
            }
            log.info("Found " + diff.getChangedFiles() + " file diffs");

            boolean shouldNotify = !importing || !changeList.hasNext();
            session = HibernateUtil.openSession();
            tx = session.beginTransaction();
            try {
                project = (Project) session.merge(project);
                ((ScmChangeSet) set).setPrevious(lastChanges);

                // enter the changes with diffs to the database
                List<ScmFile> scmFiles;
                if (moved || (!StringUtil.isEmpty(previousId) && variant.useDiffForFileListing())) {
                    // using extended diff is much richer than the update results (but provides nonsense for #1)
                    scmFiles = diff.getChangedFiles();
                } else {
                    scmFiles = updatedFiles;
                }

                if (scmFiles != null) {
                    for (ScmFile scmFile : scmFiles) {
                        int type;
                        if (scmFile.getStatus().equals(ScmFileStatus.ADDED)) {
                            type = ScmChange.TYPE_ADDED;
                        } else if (scmFile.getStatus().equals(ScmFileStatus.DELETED)) {
                            type = ScmChange.TYPE_REMOVED;
                        } else {
                            type = ScmChange.TYPE_CHANGED;
                        }

                        ScmChange adding;
                        // a small hack to match the maven-scm output
                        String path = scmFile.getPath().replace(File.separatorChar, '/');
                        String difference = null;
                        if (diff != null && diff.getDifferences() != null
                                && diff.getDifferences().containsKey(path)) {
                            difference = diff.getDifferences().get(path).toString();
                        }
                        if (variant.isTransactional()) {
                            adding = new ScmChange(path, type, difference, set);
                        } else {
                            adding = new ScmChange(path, findRevisionForScmFile(changeSet, scmFile), type,
                                    difference, set);
                        }
                        changedFiles.add(adding);
                        set.getChanges().add(adding);
                        session.save(adding);
                    }
                }

                session.save(set);
                log.info("Saved changeset " + set.getId() + " with " + set.getChanges().size() + " files");

                if (lastChanges != null) {
                    ((ScmChangeSet) lastChanges).setNext(set);
                    session.merge(lastChanges);
                }

                // update the file revision links
                for (ScmChange file : changedFiles) {
                    if (variant.isTransactional()) {
                        affected.add(updateFile(project, file.getName(), revision, session, shouldNotify));
                    } else {
                        affected.add(
                                updateFile(project, file.getName(), file.getRevision(), session, shouldNotify));
                    }
                }

                if (affected.isEmpty()) {
                    affected.add(project);
                }

                for (Project affect : affected) {
                    log.info("Setting revision to " + revision + " for project " + affect.getId());
                    setRevision(affect, set.getId(), session);
                }

                ScmCommentParser.parseComment(set.getComment(), set);

                tx.commit();
            } catch (Exception e) {
                // something failed in the database, log it and try again
                // TODO find the real cause and remove this (previous(); continue) hack...
                log.error("Failed to load project change set", e);
                e.printStackTrace();
                tx.rollback();
                //                    changeList.previous();

                continue;
            } finally {
                session.close();
            }

            previousId = set.getId();
            lastChanges = set;
            first = false;

            for (Project affect : affected) {
                application.addEvent(new FileChangeSetEvent(set, affect), shouldNotify);
            }
        }
    } catch (Throwable t) {
        log.error("Error updating projects", t);
    } finally {
        Manager.getInstance().removeTask(updateTask);
    }
}

From source file:org.headsupdev.agile.app.files.BrowseScmUpdater.java

License:Open Source License

protected Project updateFile(Project project, String path, String revision, Session session,
        boolean shouldNotify) {
    File file = new File(path);
    session.merge(new org.headsupdev.agile.storage.files.File(path, revision, project));

    while (file.getParentFile() != null) {
        file = file.getParentFile();//from  ww  w.ja  v a 2 s.  co m

        session.merge(new org.headsupdev.agile.storage.files.File(file.getPath(), revision, project));
    }

    return getChangedProjects(path, project, "", session, shouldNotify);
}

From source file:org.headsupdev.agile.app.milestones.EditMilestoneGroupForm.java

License:Open Source License

public EditMilestoneGroupForm(String id, final MilestoneGroup milestoneGroup, final boolean creating,
        final HeadsUpPage owner) {
    super(id);/*from   w  w  w . ja  v  a 2 s.co m*/

    this.group = milestoneGroup;
    this.creating = creating;

    Form<MilestoneGroup> form = new Form<MilestoneGroup>("edit") {
        public void onSubmit() {
            Session session = HibernateUtil.getCurrentSession();

            for (Milestone milestone : getMilestones()) {
                if (group.getMilestones().contains(milestone)) {
                    milestone.setGroup(group);
                } else {
                    milestone.setGroup(null);
                }

                session.merge(milestone);
            }

            if (!creating) {
                group = (MilestoneGroup) session.merge(group);
            }

            group.setUpdated(new Date());
            group.updateDueDate();
            MilestoneGroupsDAO dao = new MilestoneGroupsDAO();

            if (creating) {
                boolean alreadyExists = dao.find(group.getName(), group.getProject()) != null;
                if (alreadyExists) {
                    warn("Cannot create milestone group. A milestone group with that name already exists.");
                    return;
                }
            }
            submitParent();

            PageParameters params = new PageParameters();
            params.add("project", group.getProject().getId());
            params.add("id", group.getName());
            setResponsePage(owner.getPageClass("milestones/viewgroup"), params);
        }
    };

    form.add(setupFilter());
    form.add(new OnePressSubmitButton("submitGroup"));
    layout(form);
    add(form);
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

private List<Event> doGetEventsForProject(Project project, Application app, Date start, Date end,
        boolean tree) {
    String query = "from StoredEvent e where project.id = :pid";
    if (tree) {//from w w  w  .  j  ava2 s  . com
        query = "from StoredEvent e where project.id in (:pids)";
    }

    if (app != null) {
        query += " and applicationId = :appId";
    }

    if (start != null) {
        query += " and time >= :start and time < :end";
    }
    query += " order by time desc";

    Session session = getHibernateSession();
    Transaction tx = session.beginTransaction();
    Query q = session.createQuery(query);

    if (tree) {
        project = (Project) session.merge(project);
        List<String> projects = new LinkedList<String>();
        doListProjectIds(project, projects);
        q.setParameterList("pids", projects);
    } else {
        q.setString("pid", project.getId());
    }

    if (app != null) {
        q.setString("appId", app.getApplicationId());
    }

    if (start != null) {
        q.setTimestamp("start", start);
        q.setTimestamp("end", end);
    }

    q.setReadOnly(true);
    List<Event> list = q.list();
    tx.commit();

    return list;
}

From source file:org.headsupdev.agile.storage.HibernateStorage.java

License:Open Source License

public Object merge(Object o) {
    Session session = getHibernateSession();
    Transaction tx = session.beginTransaction();
    Object ret = session.merge(o);
    tx.commit();/*from   ww w .  j a  va 2s  .c o m*/

    return ret;
}