Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

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

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public DublinCoreCatalog storeSeries(DublinCoreCatalog dc)
        throws SeriesServiceDatabaseException, UnauthorizedException {
    if (dc == null) {
        throw new SeriesServiceDatabaseException("Invalid value for Dublin core catalog: null");
    }/*from   w w w .j a  v a  2 s . co  m*/
    String seriesId = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER);
    String seriesXML;
    try {
        seriesXML = serializeDublinCore(dc);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SeriesServiceDatabaseException(e1);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    DublinCoreCatalog newSeries = null;
    try {
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            // no series stored, create new entity
            entity = new SeriesEntity();
            entity.setOrganization(securityService.getOrganization().getId());
            entity.setSeriesId(seriesId);
            entity.setSeries(seriesXML);
            em.persist(entity);
            newSeries = dc;
        } else {
            // Ensure this user is allowed to update this series
            String accessControlXml = entity.getAccessControl();
            if (accessControlXml != null) {
                AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
                User currentUser = securityService.getUser();
                Organization currentOrg = securityService.getOrganization();
                if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                    throw new UnauthorizedException(
                            currentUser + " is not authorized to update series " + seriesId);
                }
            }
            entity.setSeries(seriesXML);
            em.merge(entity);
        }
        tx.commit();
        return newSeries;
    } catch (Exception e) {
        logger.error("Could not update series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }

}

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 {//  ww w .ja  va  2s  .co  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:org.sigmah.server.servlet.exporter.models.ProjectModelHandler.java

/**
 * Save the category element of a question choice element.
 * /*w w w  . ja v a  2 s  .c om*/
 * @param categoryElement
 *          the category element to save.
 * @param em
 *          the entity manager.
 */
private void saveProjectModelCategoryElement(CategoryElement categoryElement, EntityManager em,
        HashMap<Object, Object> modelesReset, HashSet<Object> modelesImport) {
    if (!modelesImport.contains(categoryElement)) {
        modelesImport.add(categoryElement);

        if (!modelesReset.containsKey(categoryElement)) {
            CategoryElement key = categoryElement;
            modelesReset.put(key, categoryElement);
            categoryElement.setId(null);

            CategoryType parentType = categoryElement.getParentType();
            if (!modelesImport.contains(parentType)) {
                modelesImport.add(parentType);

                if (!modelesReset.containsKey(parentType)) {
                    CategoryType parentKey = parentType;
                    modelesReset.put(parentKey, parentType);
                    parentType.setId(null);

                    List<CategoryElement> elements = parentType.getElements();
                    if (elements != null) {
                        parentType.setElements(null);
                        em.persist(parentType);
                        for (CategoryElement element : elements) {
                            categoryElement.setParentType(parentType);
                            saveProjectModelCategoryElement(element, em, modelesReset, modelesImport);
                        }
                        parentType.setElements(elements);
                        em.merge(parentType);
                    } else {
                        em.persist(parentType);
                    }
                } else {
                    parentType = (CategoryType) modelesReset.get(parentType);
                }
            }
            categoryElement.setParentType(parentType);
            em.persist(categoryElement);
        } else {
            categoryElement = (CategoryElement) modelesReset.get(categoryElement);
        }
    }
}

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

public boolean addActivity(Widgetprofile widgetProfile, String body) {
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();

    entityManager.getTransaction().begin();

    // check if activity exists
    int activity_id = Integer.parseInt(body);
    Activity activity = entityManager.find(Activity.class, activity_id);

    if (activity == null) {
        logger.error("error - activity with id:" + activity_id + " does not exist");
        return false;
    }// w ww .j a va  2s. com

    List<Activity> widget_activities = widgetProfile.getActivities();

    boolean contains = false;
    for (Activity a : widget_activities) {
        if (a.getActivitytext().equals(activity.getActivitytext()) && (a.getId() == activity.getId())) {
            contains = true;
        }
    }

    if (contains) {
        logger.warn("Widget:" + widgetProfile.getId() + " already has activity:" + activity.getActivitytext());
        return false;
    } else {
        widget_activities.add(activity);
    }

    entityManager.persist(entityManager.merge(widgetProfile));
    entityManager.getTransaction().commit();
    entityManager.close();
    return true;
}

From source file:elaborate.editor.publish.PublishTask.java

private void fixPageBreaks(Transcription transcription) {
    EntityManager entityManager = HibernateUtil.getEntityManager();
    String body = transcription.getBody();
    String fixed = body//
            .replace("<strong>", "<b>")//
            .replace("</strong>", "</b>")//
            .replaceAll("(?s)<b>([^<]*?)([^<]*?)([^<]*?)([^<]*?)</b>",
                    "$1<b></b>$2<b></b>$3<b></b>$4")//
            .replaceAll("(?s)<b>([^<]*?)([^<]*?)([^<]*?)</b>", "$1<b></b>$2<b></b>$3")//
            .replaceAll("(?s)<b>([^<]*?)([^<]*?)</b>", "$1<b></b>$2")//
            .replaceAll("", "<b></b>")//
            .replaceAll("<b><b></b></b>", "<b></b>")//
            .replaceAll("<b><b></b></b>", "<b></b>")//
            .replaceAll("<b><b></b></b>", "<b></b>");
    transcription.setBody(fixed);//from  w ww. ja  va2  s .  c om
    if (!fixed.equals(body)) {
        Log.info("fixed transcription {}:\nraw={}\nfix={}", transcription.getId(), fixed);
    }
    entityManager.merge(transcription);
    entityManager.close();
}

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

@Override
public PropValue savePropValue(PropValue propValue) {
    EntityManager em = this.emf.createEntityManager();
    try {/*from w  w  w .j  a  v  a2 s.  c om*/
        PropField tmpPropField = getPropField(propValue.getPropField().getId());
        for (PropValue value : tmpPropField.getPropValues()) {
            if (propValue.getPropValue().equals(value.getPropValue())) {
                throw new ApaException("Field [" + tmpPropField.getId() + "] already has a value set of ["
                        + value.getPropValue() + "]");
            }
        }

        em.getTransaction().begin();
        if (tmpPropField != null) {
            tmpPropField.setId(LongUserType.massageToLong(tmpPropField.getId()));
            propValue.setPropField(tmpPropField);
        }
        propValue.setId(LongUserType.massageToLong(propValue.getId()));
        propValue = (PropValue) em.merge(propValue);
        em.getTransaction().commit();
        return propValue;
    } finally {
        cleanup(em);
    }
}

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

private JpaRecord saveRecord(JpaRecord t, EntityManager em) {
    boolean useTransaction = (em == null);

    if (em == null) {
        em = this.emf.createEntityManager();
    }//w ww .jav a  2 s  .  com
    try {
        if (useTransaction) {
            em.getTransaction().begin();
        }
        t.setId(LongUserType.massageToLong(t.getId()));
        // Make sure the TicketProps are set to this existingTicket
        // If the caller forgets to do it, and we don't do it here, then JPA
        // will bonk
        if (t.getTicketProps() != null) {
            for (TicketProp prop : t.getTicketProps()) {
                enforceStrict(prop.getPropField(), prop.getValueAsString());
                enforceCorrectValueType(prop.getPropField(), prop, em);
                prop.setTicket(t);
            }
        }
        t = (JpaRecord) em.merge(t);
        if (useTransaction) {

            em.getTransaction().commit();
        }
        return t;
    } catch (ApaException e) {
        if (useTransaction) {
            em.getTransaction().rollback();
        }
        throw e;
    } finally {
        if (useTransaction) {
            cleanup(em);
        }
    }
}

From source file:op.care.nursingprocess.PnlNursingProcess.java

private List<Component> addCommands() {
    List<Component> list = new ArrayList<Component>();

    /***//  w w w  .  j av a  2  s  .  c o m
     *      _   _
     *     | \ | | _____      __
     *     |  \| |/ _ \ \ /\ / /
     *     | |\  |  __/\ V  V /
     *     |_| \_|\___| \_/\_/
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addButton = GUITools.createHyperlinkButton(SYSTools.xx("misc.commands.new"),
                SYSConst.icon22add, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgNursingProcess(new NursingProcess(resident), new Closure() {
                            @Override
                            public void execute(Object np) {
                                if (np != null) {
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        Unique unique = UniqueTools.getNewUID(em, NursingProcessTools.UNIQUEID);
                                        final NursingProcess newNP = em.merge(
                                                ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) np)
                                                        .getFirst());
                                        newNP.setNPSeries(unique.getUid());
                                        DFNTools.generate(em, newNP.getInterventionSchedule(), new LocalDate(),
                                                true);
                                        em.getTransaction().commit();

                                        // Refresh Display
                                        if (!valuecache.containsKey(newNP.getCategory())) {
                                            valuecache.put(newNP.getCategory(),
                                                    new ArrayList<NursingProcess>());
                                        }
                                        valuecache.get(newNP.getCategory()).add(newNP);
                                        Collections.sort(valuecache.get(newNP.getCategory()));
                                        createCP4(newNP.getCategory());

                                        boolean reloadSearch = false;
                                        for (Commontags ctag : newNP.getCommontags()) {
                                            if (!listUsedCommontags.contains(ctag)) {
                                                listUsedCommontags.add(ctag);
                                                reloadSearch = true;
                                            }
                                        }
                                        if (reloadSearch) {
                                            prepareSearchArea();
                                        }

                                        buildPanel();

                                        SwingUtilities.invokeLater(new Runnable() {
                                            @Override
                                            public void run() {
                                                expandCat(newNP.getCategory());
                                                GUITools.scroll2show(jspNP,
                                                        contenPanelMap.get(newNP).getLocation().y,
                                                        new Closure() {
                                                            @Override
                                                            public void execute(Object o) {
                                                                GUITools.flashBackground(
                                                                        contenPanelMap.get(newNP), 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 (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
                    }
                });
        list.add(addButton);

        /***
         *      _   _                  _______                    _       _     __
         *     | \ | | _____      __  / /_   _|__ _ __ ___  _ __ | | __ _| |_ __\ \
         *     |  \| |/ _ \ \ /\ / / | |  | |/ _ \ '_ ` _ \| '_ \| |/ _` | __/ _ \ |
         *     | |\  |  __/\ V  V /  | |  | |  __/ | | | | | |_) | | (_| | ||  __/ |
         *     |_| \_|\___| \_/\_/   | |  |_|\___|_| |_| |_| .__/|_|\__,_|\__\___| |
         *                            \_\                  |_|                  /_/
         */
        final JideButton addTemplate = GUITools
                .createHyperlinkButton(SYSTools.xx("misc.commands.newfromtemplate"), SYSConst.icon22add, null);
        addTemplate.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (!resident.isActive()) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                    return;
                }
                //                    final JidePopup popup = new JidePopup();

                // first a template is selected
                MyJDialog dlg = new PnlTemplate(new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            //                                popup.hidePopup();

                            // that selected template is cloned and handed over to the DlgNursingProcess for further editing
                            NursingProcess template = ((NursingProcess) o).clone();
                            template.setNPSeries(-2); // so the next dialog knows thats a template
                            template.setResident(resident);
                            template.setFrom(new Date());
                            template.setTo(SYSConst.DATE_UNTIL_FURTHER_NOTICE);
                            template.setUserOFF(null);
                            template.setUserON(OPDE.getLogin().getUser());
                            template.setNextEval(new DateTime().plusWeeks(4).toDate());

                            new DlgNursingProcess(template, new Closure() {
                                @Override
                                public void execute(Object np) {
                                    if (np != null) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();
                                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                            Unique unique = UniqueTools.getNewUID(em,
                                                    NursingProcessTools.UNIQUEID);
                                            final NursingProcess newNP = em.merge(
                                                    ((Pair<NursingProcess, ArrayList<InterventionSchedule>>) np)
                                                            .getFirst());
                                            newNP.setNPSeries(unique.getUid());
                                            DFNTools.generate(em, newNP.getInterventionSchedule(),
                                                    new LocalDate(), true);
                                            em.getTransaction().commit();

                                            boolean reloadSearch = false;
                                            for (Commontags ctag : newNP.getCommontags()) {
                                                if (!listUsedCommontags.contains(ctag)) {
                                                    listUsedCommontags.add(ctag);
                                                    reloadSearch = true;
                                                }
                                            }
                                            if (reloadSearch) {
                                                prepareSearchArea();
                                            }

                                            // Refresh Display
                                            if (!valuecache.containsKey(newNP.getCategory())) {
                                                valuecache.put(newNP.getCategory(),
                                                        new ArrayList<NursingProcess>());
                                            }
                                            valuecache.get(newNP.getCategory()).add(newNP);
                                            Collections.sort(valuecache.get(newNP.getCategory()));
                                            createCP4(newNP.getCategory());
                                            buildPanel();

                                            SwingUtilities.invokeLater(new Runnable() {
                                                @Override
                                                public void run() {
                                                    expandCat(newNP.getCategory());
                                                    GUITools.scroll2show(jspNP,
                                                            contenPanelMap.get(newNP).getLocation().y,
                                                            new Closure() {
                                                                @Override
                                                                public void execute(Object o) {
                                                                    GUITools.flashBackground(
                                                                            contenPanelMap.get(newNP),
                                                                            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 (Exception e) {
                                            if (em.getTransaction().isActive()) {
                                                em.getTransaction().rollback();
                                            }
                                            OPDE.fatal(e);
                                        } finally {
                                            em.close();
                                        }
                                    }
                                }
                            });

                        }
                    }
                });

                dlg.setVisible(true);
            }
        });

        list.add(addTemplate);
    }

    final JideButton btnExpandAll = GUITools.createHyperlinkButton(SYSTools.xx("misc.msg.expandall"),
            SYSConst.icon22expand, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    try {
                        GUITools.setCollapsed(cpsPlan, false);
                    } catch (PropertyVetoException e) {
                        // bah!
                    }
                }
            });
    list.add(btnExpandAll);

    final JideButton btnCollapseAll = GUITools.createHyperlinkButton(SYSTools.xx("misc.msg.collapseall"),
            SYSConst.icon22collapse, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    try {
                        GUITools.setCollapsed(cpsPlan, true);
                    } catch (PropertyVetoException e) {
                        // bah!
                    }
                }
            });
    list.add(btnCollapseAll);

    return list;
}

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  .jav 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:op.care.prescription.PnlPrescription.java

private java.util.List<Component> addCommands() {
    java.util.List<Component> list = new ArrayList<Component>();

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addRegular = GUITools.createHyperlinkButton("nursingrecords.prescription.btnNewRegular",
                SYSConst.icon22add, new ActionListener() {
                    @Override/*  w w w. ja v a2s  . c o m*/
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgRegular(new Prescription(resident), DlgRegular.MODE_NEW, new Closure() {
                            @Override
                            public void execute(Object o) {
                                if (o != null) {
                                    Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;
                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        Prescription myPrescription = em.merge(returnPackage.getFirst());
                                        myPrescription
                                                .setRelation(UniqueTools.getNewUID(em, "__verkenn").getUid());
                                        BHPTools.generate(em, myPrescription.getPrescriptionSchedule(),
                                                new LocalDate(), true);
                                        em.getTransaction().commit();

                                        lstPrescriptions.add(myPrescription);
                                        Collections.sort(lstPrescriptions);
                                        final CollapsiblePane myCP = createCP4(myPrescription);
                                        buildPanel();
                                        SwingUtilities.invokeLater(new Runnable() {
                                            @Override
                                            public void run() {
                                                GUITools.scroll2show(jspPrescription,
                                                        myCP.getLocation().y - 100, new Closure() {
                                                            @Override
                                                            public void execute(Object o) {
                                                                GUITools.flashBackground(myCP, 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 (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                    buildPanel();
                                }
                            }
                        });
                    }
                });
        list.add(addRegular);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton addNewOnDemand = GUITools.createHyperlinkButton("nursingrecords.prescription.btnNewOnDemand",
                SYSConst.icon22add, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgOnDemand(new Prescription(resident), 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);
                                        Prescription myPrescription = em.merge((Prescription) o);
                                        myPrescription
                                                .setRelation(UniqueTools.getNewUID(em, "__verkenn").getUid());
                                        em.getTransaction().commit();

                                        lstPrescriptions.add(myPrescription);
                                        Collections.sort(lstPrescriptions);
                                        final CollapsiblePane myCP = createCP4(myPrescription);
                                        buildPanel();

                                        SwingUtilities.invokeLater(new Runnable() {
                                            @Override
                                            public void run() {
                                                GUITools.scroll2show(jspPrescription,
                                                        myCP.getLocation().y - 100, new Closure() {
                                                            @Override
                                                            public void execute(Object o) {
                                                                GUITools.flashBackground(myCP, 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 (Exception e) {
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                    buildPanel();
                                }
                            }
                        });
                    }
                });
        list.add(addNewOnDemand);
    }

    // checked for acls
    if (resident.isCalcMediUPR1() && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        JideButton buchenButton = GUITools.createHyperlinkButton("nursingrecords.prescription.newstocks",
                new ImageIcon(getClass().getResource("/artwork/22x22/shetaddrow.png")), new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (!resident.isActive()) {
                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                            return;
                        }
                        new DlgNewStocks(resident);
                        reload();
                    }
                });
        list.add(buchenButton);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
        JideButton printPrescription = GUITools.createHyperlinkButton("nursingrecords.prescription.print",
                SYSConst.icon22print2, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        SYSFilesTools.print(PrescriptionTools.getPrescriptionsAsHTML(lstPrescriptions, true,
                                true, false, tbClosed.isSelected(), true), true);
                    }
                });
        list.add(printPrescription);

        //            JideButton printDaily = GUITools.createHyperlinkButton("nursingrecords.prescription.printdailyplan", SYSConst.icon22print2, new ActionListener() {
        //                @Override
        //                public void actionPerformed(ActionEvent actionEvent) {
        //                    SYSFilesTools.print(PrescriptionTools.printDailyPlan(resident.getStation().getHome()), true);
        //                }
        //            });
        //            list.add(printDaily);
    }

    return list;
}