Example usage for javax.persistence EntityManager remove

List of usage examples for javax.persistence EntityManager remove

Introduction

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

Prototype

public void remove(Object entity);

Source Link

Document

Remove the entity instance.

Usage

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Adds client subscription information. This effectively links a server to
 * serverr subscription to clerk/*  w  w w .  j a  va  2 s.c  o m*/
 * Administrative privilege required.
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
public ClientSubscriptionInfoDetail saveClientSubscriptionInfo(SaveClientSubscriptionInfo body)
        throws DispositionReportFaultMessage, RemoteException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClientSubscriptionInfo(publisher).validateSaveClientSubscriptionInfo(em, body);

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<org.apache.juddi.api_v3.ClientSubscriptionInfo> apiClientSubscriptionInfoList = body
                .getClientSubscriptionInfo();
        for (org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo : apiClientSubscriptionInfoList) {

            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = new org.apache.juddi.model.ClientSubscriptionInfo();

            MappingApiToModel.mapClientSubscriptionInfo(apiClientSubscriptionInfo, modelClientSubscriptionInfo);

            Object existingUddiEntity = em.find(modelClientSubscriptionInfo.getClass(),
                    modelClientSubscriptionInfo.getSubscriptionKey());
            if (existingUddiEntity != null) {
                em.remove(existingUddiEntity);
            }

            em.persist(modelClientSubscriptionInfo);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);//from  w w  w  . j a v  a2  s . c  o  m
    uddiEntity.setModifiedIncludingChildren(now);

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:org.sigmah.server.schedule.export.AutoDeleteJob.java

public void execute(JobExecutionContext executionContext) throws JobExecutionException {
    final JobDataMap dataMap = executionContext.getJobDetail().getJobDataMap();
    final EntityManager em = (EntityManager) dataMap.get("em");
    final Log log = (Log) dataMap.get("log");
    final Injector injector = (Injector) dataMap.get("injector");
    EntityTransaction tx = null;/*from   w  w  w . j ava2  s  .co  m*/

    try {

        // Open transaction
        /*
         *  NOTE: it is impossible to use @Transactional for this method
         *  The reason is link{TransactionalInterceptor} gets EntityManager 
         *  from the injector; this is server thread, so, EM is out of scope 
         */
        tx = em.getTransaction();
        tx.begin();

        final GlobalExportDAO exportDAO = new GlobalExportHibernateDAO(em);

        final List<GlobalExportSettings> settings = exportDAO.getGlobalExportSettings();
        for (final GlobalExportSettings setting : settings) {

            /*
             * Check for auto delete schedule 
             */

            //skip if no delete schedule is specified
            if (setting.getAutoDeleteFrequency() == null || setting.getAutoDeleteFrequency() < 1)
                continue;

            final Calendar scheduledCalendar = Calendar.getInstance();
            // subtract months from current date 
            scheduledCalendar.add(Calendar.MONTH, 0 - setting.getAutoDeleteFrequency().intValue());

            // get older exports
            List<GlobalExport> exports = exportDAO.getOlderExports(scheduledCalendar.getTime(),
                    setting.getOrganization());
            //delete exports and their contents
            for (final GlobalExport export : exports) {
                final List<GlobalExportContent> contents = export.getContents();
                for (GlobalExportContent content : contents) {
                    em.remove(content);
                }
                em.remove(export);
            }

        }
        tx.commit();

        log.info("Scheduled DELETE of global exports fired");

    } catch (Exception ex) {
        if (tx != null && tx.isActive())
            tx.rollback();
        log.error("Scheduled global export job failed : " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

public void transferEntities(TransferEntities body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  ww  w .j a va 2  s .co  m
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateTransferEntities(em, body);

        // Once validated, the ownership transfer is as simple as switching the publisher
        KeyBag keyBag = body.getKeyBag();
        List<String> keyList = keyBag.getKey();
        for (String key : keyList) {
            UddiEntity uddiEntity = em.find(UddiEntity.class, key);
            uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

            if (uddiEntity instanceof BusinessEntity) {
                BusinessEntity be = (BusinessEntity) uddiEntity;

                List<BusinessService> bsList = be.getBusinessServices();
                for (BusinessService bs : bsList) {
                    bs.setAuthorizedName(publisher.getAuthorizedName());

                    List<BindingTemplate> btList = bs.getBindingTemplates();
                    for (BindingTemplate bt : btList)
                        bt.setAuthorizedName(publisher.getAuthorizedName());
                }
            }
        }

        // After transfer is finished, the token can be removed
        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        String transferTokenId = new String(apiTransferToken.getOpaqueToken());
        org.apache.juddi.model.TransferToken modelTransferToken = em
                .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
        em.remove(modelTransferToken);

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.TRANSFER_ENTITIES, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }

}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
@Transactional/*w w w  .j av  a2 s . co  m*/
public synchronized int createHotelRatePlan(HotelRatePlan hotelRatePlan) {
    int retCode = 0;

    List<HotelRatePlan> ratePlans = null;
    EntityManager em = getEm();
    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] begin: ");
    try {
        ratePlans = em.createQuery(
                "select o from HotelRatePlan o where o.ratePlanCode = :ratePlanCode and o.hotelInfo = :hotelInfo")
                .setParameter("ratePlanCode", hotelRatePlan.getRatePlanCode())
                .setParameter("hotelInfo", hotelRatePlan.getHotelInfo()).getResultList();
        if (ratePlans.size() > 0) {
            retCode = 2;
            HotelRatePlan plan0 = ratePlans.get(0);

            //booking rule
            List<HotelRatePlanBookingRule> rules0 = em
                    .createQuery("select o from HotelRatePlanBookingRule o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanBookingRule rule0 : rules0) {
                em.remove(rule0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanBookingRules() != null) {
                for (HotelRatePlanBookingRule rule : hotelRatePlan.getHotelRatePlanBookingRules()) {
                    rule.setHotelRatePlan(plan0);
                    em.persist(rule);
                }
            }

            //offer
            List<HotelRatePlanOffer> offers0 = em
                    .createQuery("select o from HotelRatePlanOffer o where o.hotelRatePlan = :plan")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanOffer offer0 : offers0) {
                em.remove(offer0);
                em.flush();
            }
            if (hotelRatePlan.getHotelRatePlanOffers() != null) {
                for (HotelRatePlanOffer offer : hotelRatePlan.getHotelRatePlanOffers()) {
                    offer.setHotelRatePlan(plan0);
                    em.persist(offer);
                }
            }

            //rate
            List<HotelRatePlanRate> rates0 = em.createQuery(
                    "select o from HotelRatePlanRate o where o.hotelRatePlan = :plan order by o.startDate")
                    .setParameter("plan", plan0).getResultList();
            for (HotelRatePlanRate rate0 : rates0) {
                for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                    if (rate0.getStartDate().getTime() == rate.getStartDate().getTime()) {
                        em.remove(rate0);
                        em.flush();
                        break;
                    }
                }
            }

            for (HotelRatePlanRate rate : hotelRatePlan.getHotelRatePlanRates()) {
                rate.setHotelRatePlan(plan0);
                em.persist(rate);
            }
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] updated. ");
        } else {
            em.persist(hotelRatePlan);
            retCode = 1;
            logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
                    + hotelRatePlan.getHotelInfo().getHotelCode() + "] created. ");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        retCode = -1;
        logger.error(Thread.currentThread().getName() + ", createHotelRatePlan["
                + hotelRatePlan.getHotelInfo().getHotelCode() + "]: " + ex.getMessage());
    }

    getEm().detach(hotelRatePlan);
    if (ratePlans != null) {
        for (HotelRatePlan ratePlan : ratePlans) {
            getEm().detach(ratePlan);
        }
    }

    logger.debug(Thread.currentThread().getName() + ", createHotelRatePlan["
            + hotelRatePlan.getHotelInfo().getHotelCode() + "] end. ");
    return retCode;
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public PTicket patchRecord(Object idToPatch, String type, PTicket patchRecord) {

    EntityManager em = this.emf.createEntityManager();

    try {/*from   w w  w.  ja  va2  s. c o  m*/
        JpaRecord existingRecord = getTicket(type, idToPatch);
        if (existingRecord == null) {
            throw new ApaException("Record with id [" + idToPatch + "] was not found to patch");
        }
        if (patchRecord == null) {
            return existingRecord.toClientTicket();
        }

        em.getTransaction().begin();

        //delete properties on the patch
        for (Entry<String, List<String>> entry : patchRecord.getProps().entrySet()) {
            TicketProp prop = getTicketProp(entry.getKey(), type, idToPatch);
            if (prop != null) {
                prop = em.merge(prop);
                existingRecord.getTicketProps().remove(prop);
                em.remove(prop);
                existingRecord = em.merge(existingRecord);
            }
        }

        //Now patch the records
        List<TicketProp> propsToSave = buildProps(type, existingRecord, patchRecord, em);
        for (TicketProp prop : propsToSave) {

            //TODO: This should be done when we're building the prop
            enforceStrict(prop.getPropField(), prop.getValueAsString());
            prop = (TicketProp) em.merge(prop);
            existingRecord.addTicketProp(prop);
        }
        existingRecord = saveRecord(existingRecord, em);
        em.getTransaction().commit();
        return existingRecord.toClientTicket();
    } finally {
        cleanup(em);
    }
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();//from  w  w  w .  j  av a2s .  c o  m
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

From source file:org.apache.juddi.api.impl.UDDIPublicationImpl.java

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessEntity uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);//w  w  w  .  j  a v a 2 s.c om
    uddiEntity.setModifiedIncludingChildren(now);

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BusinessEntity existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    List<org.apache.juddi.model.BusinessService> serviceList = uddiEntity.getBusinessServices();
    for (org.apache.juddi.model.BusinessService service : serviceList)
        setOperationalInfo(em, service, publisher, true);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:op.care.values.PnlValues.java

private JPanel getMenu(final ResValue resValue) {

    final ResValueTypes vtype = resValue.getType();

    JPanel pnlMenu = new JPanel(new VerticalLayout());

    boolean doesNotBelongToResInfos = ResInfoTools.getInfosFor(resValue).isEmpty();

    if (doesNotBelongToResInfos && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***//from  www .  j  av  a  2 s  .c o m
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__|
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.vitalparameters.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgValue(resValue.clone(), DlgValue.MODE_EDIT, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            EntityManager em = OPDE.createEM();
                            try {

                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                final ResValue newValue = em.merge((ResValue) o);
                                ResValue oldValue = em.merge(resValue);

                                em.lock(oldValue, LockModeType.OPTIMISTIC);
                                newValue.setReplacementFor(oldValue);

                                for (SYSVAL2FILE oldAssignment : oldValue.getAttachedFilesConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedFilesConnections().clear();
                                for (SYSVAL2PROCESS oldAssignment : oldValue.getAttachedProcessConnections()) {
                                    em.remove(oldAssignment);
                                }
                                oldValue.getAttachedProcessConnections().clear();

                                oldValue.setEditedBy(em.merge(OPDE.getLogin().getUser()));
                                oldValue.setEditDate(new Date());
                                oldValue.setReplacedBy(newValue);

                                em.getTransaction().commit();

                                DateTime dt = new DateTime(newValue.getPit());
                                final String keyType = vtype.getID() + ".xtypes";
                                final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                        + ".year";

                                synchronized (mapType2Values) {
                                    mapType2Values.get(key).remove(resValue);
                                    mapType2Values.get(key).add(oldValue);
                                    mapType2Values.get(key).add(newValue);
                                    Collections.sort(mapType2Values.get(key));
                                }

                                createCP4Year(vtype, dt.getYear());

                                try {
                                    synchronized (cpMap) {
                                        cpMap.get(keyType).setCollapsed(false);
                                        cpMap.get(key).setCollapsed(false);
                                    }
                                } catch (PropertyVetoException e) {
                                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                }

                                buildPanel();

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                        }
                    }
                });
            }
        });
        btnEdit.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnEdit);

        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.vitalparameters.btnDelete.tooltip", SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/><i>"
                        + DateFormat.getDateTimeInstance().format(resValue.getPit()) + "</i><br/>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o.equals(JOptionPane.YES_OPTION)) {

                                    EntityManager em = OPDE.createEM();
                                    try {

                                        em.getTransaction().begin();

                                        ResValue myValue = em.merge(resValue);
                                        myValue.setDeletedBy(em.merge(OPDE.getLogin().getUser()));

                                        for (SYSVAL2FILE file : myValue.getAttachedFilesConnections()) {
                                            em.remove(file);
                                        }
                                        myValue.getAttachedFilesConnections().clear();

                                        // Vorgangszuordnungen entfernen
                                        for (SYSVAL2PROCESS connObj : myValue.getAttachedProcessConnections()) {
                                            em.remove(connObj);
                                        }
                                        myValue.getAttachedProcessConnections().clear();
                                        myValue.getAttachedProcesses().clear();
                                        em.getTransaction().commit();

                                        DateTime dt = new DateTime(myValue.getPit());
                                        final String keyType = vtype.getID() + ".xtypes";

                                        final String key = vtype.getID() + ".xtypes."
                                                + Integer.toString(dt.getYear()) + ".year";

                                        synchronized (mapType2Values) {
                                            mapType2Values.get(key).remove(resValue);
                                            mapType2Values.get(key).add(myValue);
                                            Collections.sort(mapType2Values.get(key));
                                        }

                                        createCP4Year(vtype, dt.getYear());

                                        try {
                                            synchronized (cpMap) {
                                                cpMap.get(keyType).setCollapsed(false);
                                                cpMap.get(key).setCollapsed(false);
                                            }
                                        } catch (PropertyVetoException e) {
                                            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                                        }

                                        buildPanel();

                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }

                                }
                            }
                        });
            }
        });
        btnDelete.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnDelete);

        pnlMenu.add(new JSeparator());
        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */

        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgFiles(resValue, new Closure() {
                    @Override
                    public void execute(Object o) {
                        EntityManager em = OPDE.createEM();
                        final ResValue myValue = em.find(ResValue.class, resValue.getID());
                        em.close();

                        DateTime dt = new DateTime(myValue.getPit());
                        final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                + ".year";

                        synchronized (mapType2Values) {
                            mapType2Values.get(key).remove(resValue);
                            mapType2Values.get(key).add(myValue);
                            Collections.sort(mapType2Values.get(key));
                        }

                        buildPanel();
                    }
                });
            }
        });
        btnFiles.setEnabled(!resValue.isObsolete() && OPDE.isFTPworking());
        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(resValue, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            ResValue myValue = em.merge(resValue);
                            em.lock(myValue, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSVAL2PROCESS> attached = new ArrayList<SYSVAL2PROCESS>(
                                    resValue.getAttachedProcessConnections());
                            for (SYSVAL2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getResValue().getAttachedProcessConnections().remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myValue.getTitle() + " ID: " + myValue.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                java.util.List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myValue)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSVAL2PROCESS myLinkObject = em
                                            .merge(new SYSVAL2PROCESS(myQProcess, myValue));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myValue.getTitle() + " ID: " + myValue.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedResValueConnections().add(myLinkObject);
                                    myValue.getAttachedProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            DateTime dt = new DateTime(myValue.getPit());
                            final String key = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                                    + ".year";

                            synchronized (mapType2Values) {
                                mapType2Values.get(key).remove(resValue);
                                mapType2Values.get(key).add(myValue);
                                Collections.sort(mapType2Values.get(key));
                            }

                            createCP4Year(vtype, dt.getYear());

                            buildPanel();
                            //GUITools.flashBackground(contentmap.get(keyMonth), Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });
            }
        });
        btnProcess.setEnabled(!resValue.isObsolete());
        pnlMenu.add(btnProcess);
    }
    return pnlMenu;
}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

@Override
public ActionForward delete(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();

    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*from   w  w w.jav  a  2 s.c o  m*/

    User user = getUser(dynaForm, request, false);
    if (user == null) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, NOTFOUND_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    User sessionUser = (User) request.getUserPrincipal();
    if (sessionUser.getId().equals(user.getId())) {
        prepareMethod(dynaForm, request, LIST, EDIT);
        addAlternateMessage(mapping, request, DELETE_ADMIN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    /* 
     * Als je een gebruiker probeert te verwijderen waarvan de main organization
     * null is geeft hij een fout. Wellicht als in het verleden handmatig een
     * aanpassing is gedaan in de database. Tijdelijk even op de beheerder org zetten
     * waarna de gebruiker gewist kan worden.
     *
     * TODO: Nagaan op welke plekken die main org null zou kunnen worden.
    */
    if (user.getMainOrganization() == null) {
        user.setMainOrganization(sessionUser.getMainOrganization());
        em.merge(user);
        em.flush();
    }

    em.remove(user);
    em.flush();

    dynaForm.initialize(mapping);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}