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:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Long saveFilter(Filter f, String userName) throws PersistenceException {
    TransactionContext tc = null;/*from  w ww  .  ja v a  2 s  .  c  o m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Long id = null;
        Filter orig = null;
        if (f.getId() != null)
            orig = em.find(Filter.class, f.getId());
        if (orig != null) {
            if (orig.getValues() != null && !orig.getValues().isEmpty()) {
                for (FilterValue fv : orig.getValues()) {
                    em.remove(fv);
                }
                orig.getValues().clear();
            }
            orig.setName(f.getName());
            orig.setClassName(f.getClassName());
            orig.setViewName(f.getViewName());
            orig.setUserName(userName);
            ArrayList<FilterValue> l = new ArrayList<FilterValue>();
            orig.setValues(l);
            for (FilterValue fv : f.getValues()) {
                fv.setId(null);
                fv.setFilter(orig);
                em.persist(fv);
                l.add(fv);
            }
            if (f.getSortAttribute() != null) {
                orig.setSortAttribute(f.getSortAttribute());
                orig.setSortAsc(f.getSortAsc());
            }

            em.merge(orig);
            id = orig.getId();
        } else {
            f.setId(null);
            f.setCreateUser(userName);
            f.setUserName(userName);
            for (FilterValue fv : f.getValues())
                fv.setId(null);
            em.persist(f);
            id = f.getId();
        }

        tx.commit();
        return id;
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * APPROVE endpoint; sends the Metadata of a targeted project to Index.
 *
 * Will return a FORBIDDEN response if the OWNER logged in does not match
 * the record's OWNER.//from  w ww  .j a  v  a2  s .co m
 *
 * @param codeId the CODE ID of the record to APPROVE.
 * @return a Response containing the JSON of the approved record if successful, or
 * error information if not
 * @throws InternalServerErrorException on JSON parsing or other IO errors
 */
@GET
@Path("/approve/{codeId}")
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response approve(@PathParam("codeId") Long codeId) {
    EntityManager em = DoeServletContextListener.createEntityManager();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        DOECodeMetadata md = em.find(DOECodeMetadata.class, codeId);

        if (null == md)
            return ErrorResponse.notFound("Code ID not on file.").build();

        // make sure this is Submitted or Announced
        if (!DOECodeMetadata.Status.Submitted.equals(md.getWorkflowStatus())
                && !DOECodeMetadata.Status.Announced.equals(md.getWorkflowStatus()))
            return ErrorResponse.badRequest("Metadata is not in the Submitted/Announced workflow state.")
                    .build();

        // move Approved Container to downloadable path
        try {
            approveContainerUpload(md);
        } catch (IOException e) {
            log.error("Container move failure: " + e.getMessage());
            return ErrorResponse.internalServerError(e.getMessage()).build();
        }

        // if approving announced, send this to OSTI
        if (DOECodeMetadata.Status.Announced.equals(md.getWorkflowStatus())) {
            sendToOsti(em, md);
        }

        em.getTransaction().begin();
        // set the WORKFLOW STATUS
        md.setWorkflowStatus(Status.Approved);

        // persist this to the database, as validations should already be complete at this stage.
        store(em, md, user);

        // prior to updating snapshot, gather RI List for backfilling
        List<RelatedIdentifier> previousRiList = getPreviousRiList(em, md);

        // store the snapshot copy of Metadata
        MetadataSnapshot snapshot = new MetadataSnapshot();
        snapshot.getSnapshotKey().setCodeId(md.getCodeId());
        snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus());
        snapshot.setDoi(md.getDoi());
        snapshot.setDoiIsMinted(md.getReleaseDate() != null);
        snapshot.setJson(md.toJson().toString());

        em.merge(snapshot);

        // perform RI backfilling
        backfillProjects(em, md, previousRiList);

        // if we make it this far, go ahead and commit the transaction
        em.getTransaction().commit();

        // send it to the indexer
        sendToIndex(em, md);

        // send APPROVAL NOTIFICATION to OWNER
        sendApprovalNotification(md);
        sendPOCNotification(md);

        // and we're happy
        return Response.status(Response.Status.OK)
                .entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()).build();
    } catch (BadRequestException e) {
        return e.getResponse();
    } catch (NotFoundException e) {
        return ErrorResponse.status(Response.Status.NOT_FOUND, e.getMessage()).build();
    } catch (IllegalAccessException e) {
        log.warn("Persistence Error: Invalid owner update attempt: " + user.getEmail());
        log.warn("Message: " + e.getMessage());
        return ErrorResponse
                .status(Response.Status.FORBIDDEN, "Invalid Access:  Unable to edit indicated record.").build();
    } catch (IOException | InvocationTargetException e) {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();

        log.warn("Persistence Error: " + e.getMessage());
        return ErrorResponse
                .status(Response.Status.INTERNAL_SERVER_ERROR, "IO Error approving record: " + e.getMessage())
                .build();
    } finally {
        em.close();
    }
}

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

private JPanel createNPPanel(final NursingProcess np) {
    /***/*from   ww  w  .j  av a  2s.  c  o m*/
     *                          _        ____ ____  _  _     _   _ ____
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |   | \ | |  _ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_  |  \| | |_) |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | |\  |  __/
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_|   |_| \_|_|
     *
     */
    if (!contenPanelMap.containsKey(np)) {
        String title = "<html><table border=\"0\">";

        if (!np.getCommontags().isEmpty()) {
            title += "<tr>" + "    <td colspan=\"2\">"
                    + CommontagsTools.getAsHTML(np.getCommontags(), SYSConst.html_16x16_tagPurple_internal)
                    + "</td>" + "  </tr>";
        }

        title += "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">" + np.getPITAsHTML() + "</td>"
                + "<td width=\"500\" align=\"left\">" + (np.isClosed() ? "<s>" : "") + np.getContentAsHTML()
                + (np.isClosed() ? "</s>" : "") + "</td></tr>";
        title += "</table>" + "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
        cptitle.getButton().setVerticalTextPosition(SwingConstants.TOP);

        if (!np.getAttachedFilesConnections().isEmpty()) {
            /***
             *      _     _         _____ _ _
             *     | |__ | |_ _ __ |  ___(_) | ___  ___
             *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
             *     | |_) | |_| | | |  _| | | |  __/\__ \
             *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
             *
             */
            final JButton btnFiles = new JButton(Integer.toString(np.getAttachedFilesConnections().size()),
                    SYSConst.icon22greenStar);
            btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
            btnFiles.setForeground(Color.BLUE);
            btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnFiles.setFont(SYSConst.ARIAL18BOLD);
            btnFiles.setPressedIcon(SYSConst.icon22Pressed);
            btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
            btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnFiles.setContentAreaFilled(false);
            btnFiles.setBorder(null);
            btnFiles.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    Closure fileHandleClosure = np.isClosed() ? null : new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final NursingProcess myNP = em.find(NursingProcess.class, np.getID());
                            em.close();
                            // Refresh Display
                            valuecache.get(np.getCategory()).remove(np);
                            contenPanelMap.remove(np);
                            valuecache.get(myNP.getCategory()).add(myNP);
                            Collections.sort(valuecache.get(myNP.getCategory()));

                            createCP4(myNP.getCategory());
                            buildPanel();
                        }
                    };
                    new DlgFiles(np, fileHandleClosure);
                }
            });
            btnFiles.setEnabled(OPDE.isFTPworking());
            cptitle.getRight().add(btnFiles);
        }

        if (!np.getAttachedQProcessConnections().isEmpty()) {
            /***
             *      _     _         ____
             *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
             *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
             *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
             *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
             *
             */
            final JButton btnProcess = new JButton(Integer.toString(np.getAttachedQProcessConnections().size()),
                    SYSConst.icon22redStar);
            btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
            btnProcess.setForeground(Color.YELLOW);
            btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
            btnProcess.setFont(SYSConst.ARIAL18BOLD);
            btnProcess.setPressedIcon(SYSConst.icon22Pressed);
            btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
            btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnProcess.setContentAreaFilled(false);
            btnProcess.setBorder(null);
            btnProcess.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgProcessAssign(np, 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);
                                final NursingProcess myNP = em.merge(np);
                                em.lock(myNP, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                ArrayList<SYSNP2PROCESS> attached = new ArrayList<SYSNP2PROCESS>(
                                        myNP.getAttachedQProcessConnections());
                                for (SYSNP2PROCESS linkObject : attached) {
                                    if (unassigned.contains(linkObject.getQProcess())) {
                                        linkObject.getQProcess().getAttachedNReportConnections()
                                                .remove(linkObject);
                                        linkObject.getNursingProcess().getAttachedQProcessConnections()
                                                .remove(linkObject);
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.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(myNP)) {
                                        QProcess myQProcess = em.merge(qProcess);
                                        SYSNP2PROCESS myLinkObject = em
                                                .merge(new SYSNP2PROCESS(myQProcess, myNP));
                                        em.merge(new PReport(
                                                SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                        + myNP.getTitle() + " ID: " + myNP.getID(),
                                                PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                        qProcess.getAttachedNursingProcessesConnections().add(myLinkObject);
                                        myNP.getAttachedQProcessConnections().add(myLinkObject);
                                    }
                                }

                                em.getTransaction().commit();

                                // Refresh Display
                                valuecache.get(np.getCategory()).remove(np);
                                contenPanelMap.remove(np);
                                valuecache.get(myNP.getCategory()).add(myNP);
                                Collections.sort(valuecache.get(myNP.getCategory()));

                                createCP4(myNP.getCategory());
                                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();
                                } else {
                                    reloadDisplay();
                                }
                            } 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(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
            cptitle.getRight().add(btnProcess);
        }

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.PRINT, internalClassID)) {
            /***
             *      _     _         ____       _       _
             *     | |__ | |_ _ __ |  _ \ _ __(_)_ __ | |_
             *     | '_ \| __| '_ \| |_) | '__| | '_ \| __|
             *     | |_) | |_| | | |  __/| |  | | | | | |_
             *     |_.__/ \__|_| |_|_|   |_|  |_|_| |_|\__|
             *
             */
            JButton btnPrint = new JButton(SYSConst.icon22print2);
            btnPrint.setContentAreaFilled(false);
            btnPrint.setBorder(null);
            btnPrint.setPressedIcon(SYSConst.icon22print2Pressed);
            btnPrint.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnPrint.setAlignmentY(Component.TOP_ALIGNMENT);
            btnPrint.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    SYSFilesTools.print(NursingProcessTools.getAsHTML(np, true, true, true, true), true);
                }
            });

            cptitle.getRight().add(btnPrint);
            //                cptitle.getTitleButton().setVerticalTextPosition(SwingConstants.TOP);
        }

        /***
         *      __  __
         *     |  \/  | ___ _ __  _   _
         *     | |\/| |/ _ \ '_ \| | | |
         *     | |  | |  __/ | | | |_| |
         *     |_|  |_|\___|_| |_|\__,_|
         *
         */
        final JButton btnMenu = new JButton(SYSConst.icon22menu);
        btnMenu.setPressedIcon(SYSConst.icon22Pressed);
        btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
        btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnMenu.setContentAreaFilled(false);
        btnMenu.setBorder(null);
        btnMenu.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JidePopup popup = new JidePopup();
                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnMenu);
                popup.removeExcludedComponent(btnMenu);
                JPanel pnl = getMenu(np);
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });

        btnMenu.setEnabled(!np.isClosed());
        cptitle.getButton().setIcon(getIcon(np));

        cptitle.getRight().add(btnMenu);
        cptitle.getMain().setBackground(getColor(np.getCategory())[SYSConst.light2]);
        cptitle.getMain().setOpaque(true);
        contenPanelMap.put(np, cptitle.getMain());
    }

    return contenPanelMap.get(np);
}

From source file:op.care.prescription.PnlPrescription.java

private CollapsiblePane createCP4(final Prescription prescription) {
    /***// ww  w. j a  va 2  s. c  o  m
     *                          _        ____ ____  _  _    ______                          _       _   _           __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /  _ \ _ __ ___  ___  ___ _ __(_)_ __ | |_(_) ___  _ __\ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| || |_) | '__/ _ \/ __|/ __| '__| | '_ \| __| |/ _ \| '_ \| |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| ||  __/| | |  __/\__ \ (__| |  | | |_) | |_| | (_) | | | | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||_|   |_|  \___||___/\___|_|  |_| .__/ \__|_|\___/|_| |_| |
     *                                                     \_\                               |_|                    /_/
     */
    final String key = prescription.getID() + ".xprescription";
    if (!cpMap.containsKey(key)) {
        cpMap.put(key, new CollapsiblePane());
        try {
            cpMap.get(key).setCollapsed(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    }
    final CollapsiblePane cpPres = cpMap.get(key);

    String title = "<html><table border=\"0\">" + "<tr valign=\"top\">" + "<td width=\"280\" align=\"left\">"
            + prescription.getPITAsHTML() + "</td>" + "<td width=\"380\" align=\"left\">" + "<font size=+1>"
            + PrescriptionTools.getShortDescription(prescription) + "</font>"
            + PrescriptionTools.getDoseAsHTML(prescription)
            + PrescriptionTools.getInventoryInformationAsHTML(prescription) + "</td>"
            + "<td width=\"200\" align=\"left\">" + PrescriptionTools.getOriginalPrescription(prescription)
            + PrescriptionTools.getRemark(prescription) + "</td>";

    if (!prescription.getCommontags().isEmpty()) {
        title += "<tr>" + "    <td colspan=\"3\">" + CommontagsTools.getAsHTML(prescription.getCommontags(),
                SYSConst.html_16x16_tagPurple_internal) + "</td>" + "  </tr>";
    }

    if (PrescriptionTools.isAnnotationNecessary(prescription)) {
        title += "<tr>" + "    <td colspan=\"3\">" + PrescriptionTools.getAnnontationsAsHTML(prescription)
                + "</td>" + "  </tr>";
    }

    title += "</table>" + "</html>";

    DefaultCPTitle cptitle = new DefaultCPTitle(title, null);
    cpPres.setCollapsible(false);
    cptitle.getButton().setIcon(getIcon(prescription));

    cpPres.setTitleLabelComponent(cptitle.getMain());
    cpPres.setSlidingDirection(SwingConstants.SOUTH);

    if (!prescription.getAttachedFilesConnections().isEmpty()) {
        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */
        final JButton btnFiles = new JButton(
                Integer.toString(prescription.getAttachedFilesConnections().size()), SYSConst.icon22greenStar);
        btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
        btnFiles.setForeground(Color.BLUE);
        btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnFiles.setFont(SYSConst.ARIAL18BOLD);
        btnFiles.setPressedIcon(SYSConst.icon22Pressed);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
        btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnFiles.setContentAreaFilled(false);
        btnFiles.setBorder(null);

        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                // checked for acls
                Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                        internalClassID) ? null : new Closure() {
                            @Override
                            public void execute(Object o) {
                                EntityManager em = OPDE.createEM();
                                final Prescription myPrescription = em.find(Prescription.class,
                                        prescription.getID());
                                em.close();
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                        };
                new DlgFiles(prescription, fileHandleClosure);
            }
        });
        btnFiles.setEnabled(OPDE.isFTPworking());
        cptitle.getRight().add(btnFiles);
    }

    if (!prescription.getAttachedProcessConnections().isEmpty()) {
        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = new JButton(
                Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon22redStar);
        btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
        btnProcess.setForeground(Color.YELLOW);
        btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
        btnProcess.setFont(SYSConst.ARIAL18BOLD);
        btnProcess.setPressedIcon(SYSConst.icon22Pressed);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
        btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        btnProcess.setContentAreaFilled(false);
        btnProcess.setBorder(null);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, 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);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

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

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

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            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 (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();
                        }

                    }
                });
            }
        });
        // checked for acls
        btnProcess.setEnabled(OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
        cptitle.getRight().add(btnProcess);
    }

    /***
     *      __  __
     *     |  \/  | ___ _ __  _   _
     *     | |\/| |/ _ \ '_ \| | | |
     *     | |  | |  __/ | | | |_| |
     *     |_|  |_|\___|_| |_|\__,_|
     *
     */
    final JButton btnMenu = new JButton(SYSConst.icon22menu);
    btnMenu.setPressedIcon(SYSConst.icon22Pressed);
    btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
    btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
    btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    btnMenu.setContentAreaFilled(false);
    btnMenu.setBorder(null);
    btnMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JidePopup popup = new JidePopup();
            popup.setMovable(false);
            popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
            popup.setOwner(btnMenu);
            popup.removeExcludedComponent(btnMenu);
            JPanel pnl = getMenu(prescription);
            popup.getContentPane().add(pnl);
            popup.setDefaultFocusComponent(pnl);

            GUITools.showPopup(popup, SwingConstants.WEST);
        }
    });
    cptitle.getRight().add(btnMenu);

    cpPres.setHorizontalAlignment(SwingConstants.LEADING);
    cpPres.setOpaque(false);

    return cpPres;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public void saveConfiguration(String viewName, String className, int nbRows, List<HeaderInfo> headers,
        ScreenLabels sl, String connectedUser, LanguageEnum language) throws PersistenceException {
    TransactionContext tc = null;/*from www.java  2  s  .c o m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        List<ScreenConfig> l = em.createQuery(
                "select o from ScreenConfig o where o.viewName = :vN and o.className = :clazz and o.createUser = :user")
                .setParameter("vN", viewName).setParameter("clazz", className)
                .setParameter("user", connectedUser).getResultList();
        ScreenConfig sc = null;
        Map<String, ScreenHeaderInfo> headerByAttribute = new HashMap<String, ScreenHeaderInfo>();
        if (l != null && !l.isEmpty()) {
            sc = l.get(0);
            if (l.size() > 1) {
                for (int i = 1; i < l.size(); i++) {
                    em.remove(l.get(i));
                }
            }
            for (ScreenHeaderInfo hi : sc.getHeaders()) {
                headerByAttribute.put(hi.getAttribute(), hi);
            }
        } else {
            sc = new ScreenConfig();
            sc.setViewName(viewName);
            sc.setClassName(className);
            sc.setCreateUser(connectedUser);
            em.persist(sc);
        }
        sc.setNbRows(nbRows);

        if (sl != null) {
            boolean found = false;
            if (sc.getLabels() != null && !sc.getLabels().isEmpty()) {
                for (ScreenLabels lb : sc.getLabels()) {
                    if (lb.getLanguage().equals(language)) {
                        if (sl.getCreateLabel() != null)
                            lb.setCreateLabel(sl.getCreateLabel());
                        if (sl.getEditLabel() != null)
                            lb.setEditLabel(sl.getEditLabel());
                        if (sl.getFormLabel() != null)
                            lb.setFormLabel(sl.getFormLabel());
                        if (sl.getSelectLabel() != null)
                            lb.setSelectLabel(sl.getSelectLabel());
                        if (sl.getTableLabel() != null)
                            lb.setTableLabel(sl.getTableLabel());
                        if (sl.getViewLabel() != null)
                            lb.setViewLabel(sl.getViewLabel());
                        em.merge(lb);
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                sl.setScreenConfig(sc);
                em.persist(sl);
            }
        }
        for (HeaderInfo hi : headers) {
            ScreenHeaderInfo shi = headerByAttribute.get(hi.getAttribute());
            if (shi == null) {
                shi = new ScreenHeaderInfo();
                shi.setAttribute(hi.getAttribute());
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.persist(shi);
            } else {
                shi.setDisplayed(hi.isDisplayed());
                shi.setScreenConfig(sc);
                shi.setIndex(hi.getIndex());
                em.merge(shi);
            }
            if (hi.getLabel() != null) {
                boolean found = false;
                List<Label> labels = shi.getLabels();
                if (labels != null && !labels.isEmpty()) {
                    Iterator<Label> it = labels.iterator();
                    while (it.hasNext()) {
                        Label lbl = it.next();
                        if (lbl.getLanguage().equals(language)) {
                            if (hi.getLabel().length() > 0) {
                                lbl.setLabel(hi.getLabel());
                                em.merge(lbl);
                            } else {
                                em.remove(lbl);
                                it.remove();
                            }
                            found = true;
                            break;
                        }
                    }
                }
                if (!found) {
                    Label lbl = new Label();
                    lbl.setLanguage(language);
                    lbl.setLabel(hi.getLabel());
                    lbl.setHeader(shi);
                    em.persist(lbl);
                }
            }
        }
        tx.commit();
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

From source file:op.care.med.inventory.PnlInventory.java

private CollapsiblePane createCP4(final MedInventory inventory) {
    /***//from   ww  w  .j a  va  2  s  .  c om
     *                          _        ____ ____  _  _    _____                      _                 __
     *       ___ _ __ ___  __ _| |_ ___ / ___|  _ \| || |  / /_ _|_ ____   _____ _ __ | |_ ___  _ __ _   \ \
     *      / __| '__/ _ \/ _` | __/ _ \ |   | |_) | || |_| | | || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | | |
     *     | (__| | |  __/ (_| | ||  __/ |___|  __/|__   _| | | || | | \ V /  __/ | | | || (_) | |  | |_| | |
     *      \___|_|  \___|\__,_|\__\___|\____|_|      |_| | ||___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, | |
     *                                                     \_\                                       |___/_/
     */
    final String key = inventory.getID() + ".xinventory";
    synchronized (cpMap) {
        if (!cpMap.containsKey(key)) {
            cpMap.put(key, new CollapsiblePane());
            try {
                cpMap.get(key).setCollapsed(true);
            } catch (PropertyVetoException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }

        }

        cpMap.get(key).setName("inventory");

        //            final CollapsiblePane cpInventory = cpMap.get(key);

        BigDecimal sumInventory = BigDecimal.ZERO;
        try {
            EntityManager em = OPDE.createEM();
            sumInventory = MedInventoryTools.getSum(em, inventory);
            em.close();
        } catch (Exception e) {
            OPDE.fatal(e);
        }

        String title = "<html><table border=\"0\">" + "<tr>" +

                "<td width=\"520\" align=\"left\"><font size=+1>" + inventory.getText() + "</font></td>"
                + "<td width=\"200\" align=\"right\"><font size=+1>"
                + NumberFormat.getNumberInstance().format(sumInventory) + " "
                + DosageFormTools.getPackageText(MedInventoryTools.getForm(inventory)) + "</font></td>" +

                "</tr>" + "</table>" +

                "</html>";

        DefaultCPTitle cptitle = new DefaultCPTitle(title, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    cpMap.get(key).setCollapsed(!cpMap.get(key).isCollapsed());
                } catch (PropertyVetoException pve) {
                    // BAH!
                }
            }
        });
        cpMap.get(key).setTitleLabelComponent(cptitle.getMain());
        cpMap.get(key).setSlidingDirection(SwingConstants.SOUTH);
        cptitle.getButton().setIcon(inventory.isClosed() ? SYSConst.icon22stopSign : null);

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.MANAGER, "nursingrecords.inventory")) {
            /***
             *       ____ _                ___                      _
             *      / ___| | ___  ___  ___|_ _|_ ____   _____ _ __ | |_ ___  _ __ _   _
             *     | |   | |/ _ \/ __|/ _ \| || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | |
             *     | |___| | (_) \__ \  __/| || | | \ V /  __/ | | | || (_) | |  | |_| |
             *      \____|_|\___/|___/\___|___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, |
             *                                                                    |___/
             */
            final JButton btnCloseInventory = new JButton(SYSConst.icon22playerStop);
            btnCloseInventory.setPressedIcon(SYSConst.icon22playerStopPressed);
            btnCloseInventory.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnCloseInventory.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnCloseInventory.setContentAreaFilled(false);
            btnCloseInventory.setBorder(null);
            btnCloseInventory.setToolTipText(SYSTools.xx("nursingrecords.inventory.btncloseinventory.tooltip"));
            btnCloseInventory.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgYesNo(
                            SYSTools.xx("nursingrecords.inventory.question.close1") + "<br/><b>"
                                    + inventory.getText() + "</b>" + "<br/>"
                                    + SYSTools.xx("nursingrecords.inventory.question.close2"),
                            SYSConst.icon48playerStop, new Closure() {
                                @Override
                                public void execute(Object answer) {
                                    if (answer.equals(JOptionPane.YES_OPTION)) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            MedInventory myInventory = em.merge(inventory);
                                            em.lock(myInventory, LockModeType.OPTIMISTIC);
                                            em.lock(myInventory.getResident(), LockModeType.OPTIMISTIC);

                                            // close all stocks
                                            for (MedStock stock : MedStockTools.getAll(myInventory)) {
                                                if (!stock.isClosed()) {
                                                    MedStock mystock = em.merge(stock);
                                                    em.lock(mystock, LockModeType.OPTIMISTIC);
                                                    mystock.setNextStock(null);
                                                    MedStockTools.close(em, mystock, SYSTools.xx(
                                                            "nursingrecords.inventory.stock.msg.inventory_closed"),
                                                            MedStockTransactionTools.STATE_EDIT_INVENTORY_CLOSED);
                                                }
                                            }
                                            // close inventory
                                            myInventory.setTo(new Date());

                                            em.getTransaction().commit();

                                            createCP4(myInventory);
                                            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();
                                        }
                                    }
                                }
                            });
                }
            });
            btnCloseInventory.setEnabled(!inventory.isClosed());
            cptitle.getRight().add(btnCloseInventory);
        }
        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, "nursingrecords.inventory")) {
            /***
             *      ____       _ ___                      _
             *     |  _ \  ___| |_ _|_ ____   _____ _ __ | |_ ___  _ __ _   _
             *     | | | |/ _ \ || || '_ \ \ / / _ \ '_ \| __/ _ \| '__| | | |
             *     | |_| |  __/ || || | | \ V /  __/ | | | || (_) | |  | |_| |
             *     |____/ \___|_|___|_| |_|\_/ \___|_| |_|\__\___/|_|   \__, |
             *                                                          |___/
             */
            final JButton btnDelInventory = new JButton(SYSConst.icon22delete);
            btnDelInventory.setPressedIcon(SYSConst.icon22deletePressed);
            btnDelInventory.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnDelInventory.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            btnDelInventory.setContentAreaFilled(false);
            btnDelInventory.setBorder(null);
            btnDelInventory.setToolTipText(SYSTools.xx("nursingrecords.inventory.btndelinventory.tooltip"));
            btnDelInventory.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    new DlgYesNo(
                            SYSTools.xx("nursingrecords.inventory.question.delete1") + "<br/><b>"
                                    + inventory.getText() + "</b>" + "<br/>"
                                    + SYSTools.xx("nursingrecords.inventory.question.delete2"),
                            SYSConst.icon48delete, new Closure() {
                                @Override
                                public void execute(Object answer) {
                                    if (answer.equals(JOptionPane.YES_OPTION)) {
                                        EntityManager em = OPDE.createEM();
                                        try {
                                            em.getTransaction().begin();

                                            MedInventory myInventory = em.merge(inventory);
                                            em.lock(myInventory, LockModeType.OPTIMISTIC);
                                            em.lock(myInventory.getResident(), LockModeType.OPTIMISTIC);

                                            em.remove(myInventory);

                                            em.getTransaction().commit();

                                            //                                        lstInventories.remove(inventory);
                                            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();
                                        }
                                    }
                                }
                            });
                }
            });
            cptitle.getRight().add(btnDelInventory);
        }

        final JToggleButton tbClosedStock = GUITools.getNiceToggleButton(null);
        tbClosedStock.setToolTipText(SYSTools.xx("nursingrecords.inventory.showclosedstocks"));
        if (!inventory.isClosed()) {
            tbClosedStock.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
                }
            });
        }
        tbClosedStock.setSelected(inventory.isClosed());
        tbClosedStock.setEnabled(!inventory.isClosed());

        mapKey2ClosedToggleButton.put(key, tbClosedStock);

        cptitle.getRight().add(tbClosedStock);

        CollapsiblePaneAdapter adapter = new CollapsiblePaneAdapter() {
            @Override
            public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
                cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
            }
        };
        synchronized (cpListener) {
            if (cpListener.containsKey(key)) {
                cpMap.get(key).removeCollapsiblePaneListener(cpListener.get(key));
            }
            cpListener.put(key, adapter);
            cpMap.get(key).addCollapsiblePaneListener(adapter);
        }

        if (!cpMap.get(key).isCollapsed()) {
            cpMap.get(key).setContentPane(createContentPanel4(inventory, tbClosedStock.isSelected()));
        }

        cpMap.get(key).setHorizontalAlignment(SwingConstants.LEADING);
        cpMap.get(key).setOpaque(false);
        cpMap.get(key).setBackground(getColor(SYSConst.medium2, lstInventories.indexOf(inventory) % 2 != 0));

        return cpMap.get(key);
    }
}

From source file:com.thejustdo.servlet.CargaMasivaServlet.java

/**
 * Processes requests for both HTTP/*  w  w  w . j  a  va  2 s . c om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    log.info(String.format("Welcome to the MULTI-PART!!!"));
    ResourceBundle messages = ResourceBundle.getBundle("com.thejustdo.resources.messages");
    // 0. If no user logged, nothing can be done.
    if (!SecureValidator.checkUserLogged(request, response)) {
        return;
    }

    // 1. Check that we have a file upload request.
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    log.info(String.format("Is multipart?: %s", isMultipart));

    // 2. Getting all the parameters.
    String social_reason = request.getParameter("razon_social");
    String nit = request.getParameter("nit");
    String name = request.getParameter("name");
    String phone = request.getParameter("phone");
    String email = request.getParameter("email");
    String office = (String) request.getSession().getAttribute("actualOffice");
    String open_amount = (String) request.getParameter("valor_tarjeta");
    String open_user = (String) request.getSession().getAttribute("actualUser");

    List<String> errors = new ArrayList<String>();

    // 6. Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // 7. Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    log.info(String.format("Temporal repository: %s", repository.getAbsolutePath()));
    factory.setRepository(repository);

    // 8. Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        utx.begin();
        EntityManager em = emf.createEntityManager();
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // 8.0 A set of generated box codes must be maintained.
        Map<String, String> matrix = new HashMap<String, String>();
        // ADDED: Validation 'o file extension.
        String filename = null;

        // Runing through the parameters.
        for (FileItem fi : items) {
            if (fi.isFormField()) {
                if ("razon_social".equalsIgnoreCase(fi.getFieldName())) {
                    social_reason = fi.getString();
                    continue;
                }

                if ("nit".equalsIgnoreCase(fi.getFieldName())) {
                    nit = fi.getString();
                    continue;
                }

                if ("name".equalsIgnoreCase(fi.getFieldName())) {
                    name = fi.getString();
                    continue;
                }

                if ("phone".equalsIgnoreCase(fi.getFieldName())) {
                    phone = fi.getString();
                    continue;
                }

                if ("email".equalsIgnoreCase(fi.getFieldName())) {
                    email = fi.getString();
                    continue;
                }

                if ("valor_tarjeta".equalsIgnoreCase(fi.getFieldName())) {
                    open_amount = fi.getString();
                    continue;
                }
            } else {
                filename = fi.getName();
            }
        }

        // 3. If we got no file, then a error is generated and re-directed to the exact same page.
        if (!isMultipart) {
            errors.add(messages.getString("error.massive.no_file"));
            log.log(Level.SEVERE, errors.toString());
        }

        // 4. If any of the others paramaeters are missing, then a error must be issued.
        if ((social_reason == null) || ("".equalsIgnoreCase(social_reason.trim()))) {
            errors.add(messages.getString("error.massive.no_social_reason"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((nit == null) || ("".equalsIgnoreCase(nit.trim()))) {
            errors.add(messages.getString("error.massive.no_nit"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((name == null) || ("".equalsIgnoreCase(name.trim()))) {
            errors.add(messages.getString("error.massive.no_name"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((phone == null) || ("".equalsIgnoreCase(phone.trim()))) {
            errors.add(messages.getString("error.massive.no_phone"));
            log.log(Level.SEVERE, errors.toString());
        }

        if ((email == null) || ("".equalsIgnoreCase(email.trim()))) {
            errors.add(messages.getString("error.massive.no_email"));
            log.log(Level.SEVERE, errors.toString());
        }

        // If no filename or incorrect extension.
        if ((filename == null) || (!(filename.endsWith(Constants.MASSIVE_EXT.toLowerCase(Locale.FRENCH)))
                && !(filename.endsWith(Constants.MASSIVE_EXT.toUpperCase())))) {
            errors.add(messages.getString("error.massive.invalid_ext"));
            log.log(Level.SEVERE, errors.toString());
        }

        // 5. If any errors found, we must break the flow.
        if (errors.size() > 0) {
            request.setAttribute(Constants.ERROR, errors);
            //Redirect the response
            request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
        }

        for (FileItem fi : items) {
            if (!fi.isFormField()) {
                // 8.1 Processing the file and building the Beneficiaries.
                List<Beneficiary> beneficiaries = processFile(fi);
                log.info(String.format("Beneficiaries built: %d", beneficiaries.size()));

                // 8.2 If any beneficiaries, then an error is generated.
                if ((beneficiaries == null) || (beneficiaries.size() < 0)) {
                    errors.add(messages.getString("error.massive.empty_file"));
                    log.log(Level.SEVERE, errors.toString());
                    request.setAttribute(Constants.ERROR, errors);
                    //Redirect the response
                    request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
                }

                // 8.3 Building main parts.
                Buyer b = buildGeneralBuyer(em, social_reason, nit, name, phone, email);
                // 8.3.1 The DreamBox has to be re-newed per beneficiary.
                DreamBox db;
                for (Beneficiary _b : beneficiaries) {
                    // 8.3.2 Completing each beneficiary.
                    log.info(String.format("Completying the beneficiary: %d", _b.getIdNumber()));
                    db = buildDreamBox(em, b, office, open_amount, open_user);
                    matrix.put(db.getNumber() + "", _b.getGivenNames() + " " + _b.getLastName());
                    _b.setOwner(b);
                    _b.setBox(db);
                    em.merge(_b);
                }

            }
        }

        // 8.4 Commiting to persistence layer.
        utx.commit();

        // 8.5 Re-directing to the right jsp.
        request.getSession().setAttribute("boxes", matrix);
        request.getSession().setAttribute("boxamount", open_amount + "");
        //Redirect the response
        generateZIP(request, response);
    } catch (Exception ex) {
        errors.add(messages.getString("error.massive.couldnot_process"));
        log.log(Level.SEVERE, errors.toString());
        request.setAttribute(Constants.ERROR, errors);
        request.getRequestDispatcher("/WEB-INF/jsp/carga_masiva.jsp").forward(request, response);
    }
}

From source file:op.care.reports.PnlReport.java

private JPanel createContentPanel4Day(LocalDate day) {
    //        OPDE.getDisplayManager().setProgressBarMessage(new DisplayMessage("misc.msg.wait", progress, progressMax));
    //        progress++;

    final String key = DateFormat.getDateInstance().format(day.toDate());
    synchronized (contentmap) {
        if (contentmap.containsKey(key)) {
            return contentmap.get(key);
        }/*from   w  ww  . ja  va2 s.  co m*/
    }
    final JPanel dayPanel = new JPanel(new VerticalLayout());
    dayPanel.setOpaque(false);
    synchronized (valuecache) {
        if (!valuecache.containsKey(key)) {
            valuecache.put(key, NReportTools.getNReports4Day(resident, day));
        }

        int i = 0; // for zebra pattern
        for (final NReport nreport : valuecache.get(key)) {

            if (tbShowReplaced.isSelected() || !nreport.isObsolete()) {

                String title = SYSTools.toHTMLForScreen(SYSConst.html_table(SYSConst
                        .html_table_tr("<td width=\"800\" align=\"left\">" + "<b><p>"
                                + (nreport.isObsolete() ? SYSConst.html_16x16_Eraser_internal : "")
                                + (nreport.isReplacement() ? SYSConst.html_16x16_Edited_internal : "")
                                + DateFormat.getTimeInstance(DateFormat.SHORT).format(nreport.getPit()) + " "
                                + SYSTools.xx("misc.msg.Time.short") + ", " + nreport.getMinutes() + " "
                                + SYSTools.xx("misc.msg.Minute(s)") + ", " + nreport.getUser().getFullname()
                                + (nreport.getCommontags().isEmpty() ? ""
                                        : " " + CommontagsTools.getAsHTML(nreport.getCommontags(),
                                                SYSConst.html_16x16_tagPurple_internal))
                                + "</p></b></td>")
                        + SYSConst.html_table_tr("<td width=\"800\" align=\"left\">"
                                + SYSTools.replace(nreport.getText(), "\n", "<br/>", false) + "</td>"),
                        "0"));

                final DefaultCPTitle pnlSingle = new DefaultCPTitle(SYSTools.toHTMLForScreen(title), null);
                pnlSingle.getButton().addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        GUITools.showPopup(GUITools.getHTMLPopup(pnlSingle.getButton(),
                                NReportTools.getInfoAsHTML(nreport)), SwingConstants.NORTH);
                    }
                });

                if (!nreport.getAttachedFilesConnections().isEmpty()) {
                    /***
                     *      _     _         _____ _ _
                     *     | |__ | |_ _ __ |  ___(_) | ___  ___
                     *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
                     *     | |_) | |_| | | |  _| | | |  __/\__ \
                     *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
                     *
                     */
                    final JButton btnFiles = new JButton(
                            Integer.toString(nreport.getAttachedFilesConnections().size()),
                            SYSConst.icon22greenStar);
                    btnFiles.setToolTipText(SYSTools.xx("misc.btnfiles.tooltip"));
                    btnFiles.setForeground(Color.BLUE);
                    btnFiles.setHorizontalTextPosition(SwingUtilities.CENTER);
                    btnFiles.setFont(SYSConst.ARIAL18BOLD);
                    btnFiles.setPressedIcon(SYSConst.icon22Pressed);
                    btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnFiles.setAlignmentY(Component.TOP_ALIGNMENT);
                    btnFiles.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnFiles.setContentAreaFilled(false);
                    btnFiles.setBorder(null);

                    btnFiles.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            Closure fileHandleClosure = OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE,
                                    internalClassID) ? null : new Closure() {
                                        @Override
                                        public void execute(Object o) {
                                            EntityManager em = OPDE.createEM();
                                            final NReport myReport = em.find(NReport.class, nreport.getID());
                                            em.close();

                                            final String keyNewDay = DateFormat.getDateInstance()
                                                    .format(myReport.getPit());

                                            synchronized (contentmap) {
                                                contentmap.remove(keyNewDay);
                                            }
                                            synchronized (linemap) {
                                                linemap.remove(nreport);
                                            }

                                            synchronized (valuecache) {
                                                valuecache.get(keyNewDay).remove(nreport);
                                                valuecache.get(keyNewDay).add(myReport);
                                                Collections.sort(valuecache.get(keyNewDay));
                                            }

                                            createCP4Day(new LocalDate(myReport.getPit()));

                                            buildPanel();
                                            GUITools.flashBackground(linemap.get(myReport), Color.YELLOW, 2);
                                        }
                                    };
                            new DlgFiles(nreport, fileHandleClosure);
                        }
                    });
                    btnFiles.setEnabled(OPDE.isFTPworking());
                    pnlSingle.getRight().add(btnFiles);
                }

                if (!nreport.getAttachedQProcessConnections().isEmpty()) {
                    /***
                     *      _     _         ____
                     *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
                     *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
                     *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
                     *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
                     *
                     */
                    final JButton btnProcess = new JButton(
                            Integer.toString(nreport.getAttachedQProcessConnections().size()),
                            SYSConst.icon22redStar);
                    btnProcess.setToolTipText(SYSTools.xx("misc.btnprocess.tooltip"));
                    btnProcess.setForeground(Color.YELLOW);
                    btnProcess.setHorizontalTextPosition(SwingUtilities.CENTER);
                    btnProcess.setFont(SYSConst.ARIAL18BOLD);
                    btnProcess.setPressedIcon(SYSConst.icon22Pressed);
                    btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
                    btnProcess.setAlignmentY(Component.TOP_ALIGNMENT);
                    btnProcess.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                    btnProcess.setContentAreaFilled(false);
                    btnProcess.setBorder(null);
                    btnProcess.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            new DlgProcessAssign(nreport, 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);
                                        NReport myReport = em.merge(nreport);
                                        em.lock(myReport, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                        ArrayList<SYSNR2PROCESS> attached = new ArrayList<SYSNR2PROCESS>(
                                                myReport.getAttachedQProcessConnections());
                                        for (SYSNR2PROCESS linkObject : attached) {
                                            if (unassigned.contains(linkObject.getQProcess())) {
                                                linkObject.getQProcess().getAttachedNReportConnections()
                                                        .remove(linkObject);
                                                linkObject.getNReport().getAttachedQProcessConnections()
                                                        .remove(linkObject);
                                                em.merge(new PReport(
                                                        SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT)
                                                                + ": " + nreport.getTitle() + " ID: "
                                                                + nreport.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(myReport)) {
                                                QProcess myQProcess = em.merge(qProcess);
                                                SYSNR2PROCESS myLinkObject = em
                                                        .merge(new SYSNR2PROCESS(myQProcess, myReport));
                                                em.merge(new PReport(
                                                        SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT)
                                                                + ": " + nreport.getTitle() + " ID: "
                                                                + nreport.getID(),
                                                        PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                                qProcess.getAttachedNReportConnections().add(myLinkObject);
                                                myReport.getAttachedQProcessConnections().add(myLinkObject);
                                            }
                                        }

                                        em.getTransaction().commit();

                                        final String keyNewDay = DateFormat.getDateInstance()
                                                .format(myReport.getPit());

                                        synchronized (contentmap) {
                                            contentmap.remove(keyNewDay);
                                        }
                                        synchronized (linemap) {
                                            linemap.remove(nreport);
                                        }

                                        synchronized (valuecache) {
                                            valuecache.get(keyNewDay).remove(nreport);
                                            valuecache.get(keyNewDay).add(myReport);
                                            Collections.sort(valuecache.get(keyNewDay));
                                        }

                                        createCP4Day(new LocalDate(myReport.getPit()));

                                        buildPanel();
                                        GUITools.flashBackground(linemap.get(myReport), 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();
                                        } else {
                                            reloadDisplay(true);
                                        }
                                    } 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(
                            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID));
                    pnlSingle.getRight().add(btnProcess);
                }

                /***
                 *      __  __
                 *     |  \/  | ___ _ __  _   _
                 *     | |\/| |/ _ \ '_ \| | | |
                 *     | |  | |  __/ | | | |_| |
                 *     |_|  |_|\___|_| |_|\__,_|
                 *
                 */
                final JButton btnMenu = new JButton(SYSConst.icon22menu);
                btnMenu.setPressedIcon(SYSConst.icon22Pressed);
                btnMenu.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnMenu.setAlignmentY(Component.TOP_ALIGNMENT);
                btnMenu.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                btnMenu.setContentAreaFilled(false);
                btnMenu.setBorder(null);
                btnMenu.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JidePopup popup = new JidePopup();
                        popup.setMovable(false);
                        popup.getContentPane()
                                .setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                        popup.setOwner(btnMenu);
                        popup.removeExcludedComponent(btnMenu);
                        JPanel pnl = getMenu(nreport);
                        popup.getContentPane().add(pnl);
                        popup.setDefaultFocusComponent(pnl);

                        GUITools.showPopup(popup, SwingConstants.WEST);
                    }
                });
                btnMenu.setEnabled(!nreport.isObsolete());
                pnlSingle.getRight().add(btnMenu);

                JPanel zebra = new JPanel();
                zebra.setLayout(new BoxLayout(zebra, BoxLayout.LINE_AXIS));
                zebra.setOpaque(true);
                if (i % 2 == 0) {
                    zebra.setBackground(SYSConst.orange1[SYSConst.light2]);
                } else {
                    zebra.setBackground(Color.WHITE);
                }
                zebra.add(pnlSingle.getMain());
                i++;

                dayPanel.add(zebra);
                linemap.put(nreport, pnlSingle.getMain());
            }
        }
    }
    synchronized (contentmap) {
        contentmap.put(key, dayPanel);
    }
    return dayPanel;
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

private void processRemovedManyToMany(ObjectsToPersist toPersist,
        Map<com.hiperf.common.ui.shared.util.Id, INakedObject> res, Map<Object, IdHolder> newIdByOldId,
        EntityManager em) throws ClassNotFoundException, IntrospectionException, PersistenceException,
        IllegalAccessException, InvocationTargetException, NoSuchFieldException {
    Map<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> manyToManyRemoved = toPersist
            .getManyToManyRemovedByClassName();
    if (manyToManyRemoved != null && !manyToManyRemoved.isEmpty()) {
        for (Entry<String, Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>>> e : manyToManyRemoved
                .entrySet()) {//  www . java  2  s .  co m
            String className = e.getKey();
            Map<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> map = e
                    .getValue();
            if (map != null && !map.isEmpty()) {
                Class<?> clazz = Class.forName(className);
                for (Entry<com.hiperf.common.ui.shared.util.Id, Map<String, List<com.hiperf.common.ui.shared.util.Id>>> entry : map
                        .entrySet()) {
                    com.hiperf.common.ui.shared.util.Id id = entry.getKey();
                    Map<String, List<com.hiperf.common.ui.shared.util.Id>> m = entry.getValue();
                    if (m != null && !m.isEmpty()) {
                        Object objId = id.getFieldValues().get(0);
                        if (newIdByOldId.containsKey(objId))
                            objId = newIdByOldId.get(objId).getId();
                        Object o = em.find(clazz, objId);
                        if (o != null) {
                            PropertyDescriptor[] pds = propertyDescriptorsByClassName.get(className);
                            for (Entry<String, List<com.hiperf.common.ui.shared.util.Id>> ee : m.entrySet()) {
                                String attr = ee.getKey();
                                List<com.hiperf.common.ui.shared.util.Id> ll = ee.getValue();
                                if (ll != null && !ll.isEmpty()) {
                                    Collection coll = null;
                                    Class classInColl = null;
                                    PropertyDescriptor myPd = null;
                                    for (PropertyDescriptor pd : pds) {
                                        if (pd.getName().equals(attr)) {
                                            myPd = pd;
                                            coll = (Collection) pd.getReadMethod().invoke(o,
                                                    StorageService.emptyArg);
                                            break;
                                        }
                                    }
                                    if (coll != null) {
                                        ParameterizedType genericType = (ParameterizedType) clazz
                                                .getDeclaredField(myPd.getName()).getGenericType();
                                        if (genericType != null) {
                                            for (Type t : genericType.getActualTypeArguments()) {

                                                if (t instanceof Class
                                                        && INakedObject.class.isAssignableFrom((Class) t)) {
                                                    classInColl = (Class) t;
                                                    break;
                                                }
                                            }
                                        }
                                        for (com.hiperf.common.ui.shared.util.Id i : ll) {
                                            Object idObj = i.getFieldValues().get(0);
                                            if (newIdByOldId.containsKey(idObj))
                                                idObj = newIdByOldId.get(idObj);
                                            Object linkedObj = em.find(classInColl, idObj);
                                            coll.remove(linkedObj);
                                        }
                                    }
                                }
                            }
                            res.put(id, (INakedObject) em.merge(o));
                        }
                    }

                }
            }
        }
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Perform ANNOUNCE workflow operation, optionally with associated file uploads.
 *
 * @param json String containing JSON of the Metadata to ANNOUNCE
 * @param file the FILE (if any) to attach to this metadata
 * @param fileInfo file disposition information if FILE present
 * @return a Response containing the JSON of the submitted record if successful, or
 * error information if not/*from  w  w w  .j a va2  s.  c  o  m*/
 */
private Response doAnnounce(String json, InputStream file, FormDataContentDisposition fileInfo,
        InputStream container, FormDataContentDisposition containerInfo) {
    EntityManager em = DoeServletContextListener.createEntityManager();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        validateUploads(fileInfo, containerInfo);

        DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(json));

        Long currentCodeId = md.getCodeId();
        boolean previouslySaved = false;
        if (currentCodeId != null) {
            DOECodeMetadata emd = em.find(DOECodeMetadata.class, currentCodeId);

            if (emd != null)
                previouslySaved = Status.Saved.equals(emd.getWorkflowStatus());
        }

        em.getTransaction().begin();

        performDataNormalization(md);

        // set the OWNER
        md.setOwner(user.getEmail());
        // set the WORKFLOW STATUS
        md.setWorkflowStatus(Status.Announced);
        // set the SITE
        md.setSiteOwnershipCode(user.getSiteId());
        // if there is NO DOI set, get one
        if (StringUtils.isEmpty(md.getDoi())) {
            DoiReservation reservation = getReservedDoi();
            if (null == reservation)
                throw new IOException("DOI reservation failure.");
            // set it
            md.setDoi(reservation.getReservedDoi());
        }

        // persist this to the database
        store(em, md, user);

        // re-attach metadata to transaction in order to store any changes beyond this point
        md = em.find(DOECodeMetadata.class, md.getCodeId());

        // if there's a FILE associated here, store it
        String fullFileName = "";
        if (null != file && null != fileInfo) {
            try {
                fullFileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS);
                md.setFileName(fullFileName);
            } catch (IOException e) {
                log.error("File Upload Failed: " + e.getMessage());
                return ErrorResponse.internalServerError("File upload failed.").build();
            }
        }

        // if there's a CONTAINER IMAGE associated here, store it
        String fullContainerName = "";
        if (null != container && null != containerInfo) {
            try {
                fullContainerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(),
                        CONTAINER_UPLOADS);
                md.setContainerName(fullContainerName);
            } catch (IOException e) {
                log.error("Container Image Upload Failed: " + e.getMessage());
                return ErrorResponse.internalServerError("Container Image upload failed.").build();
            }
        }

        // check validations
        List<String> errors = validateAnnounce(md);
        if (!errors.isEmpty()) {
            return ErrorResponse.badRequest(errors).build();
        }

        // create OSTI Hosted project, as needed
        try {
            // process local GitLab, if needed
            processOSTIGitLab(md);
        } catch (Exception e) {
            log.error("OSTI GitLab failure: " + e.getMessage());
            return ErrorResponse.internalServerError("Unable to create OSTI Hosted project: " + e.getMessage())
                    .build();
        }

        // send this file upload along to archiver if configured
        try {
            // if no file/container, but previously Saved with a file/container, we need to attach to those streams and send to Archiver
            if (previouslySaved) {
                if (null == file && !StringUtils.isBlank(md.getFileName())) {
                    java.nio.file.Path destination = Paths.get(FILE_UPLOADS, String.valueOf(md.getCodeId()),
                            md.getFileName());
                    fullFileName = destination.toString();
                    file = Files.newInputStream(destination);
                }
                if (null == container && !StringUtils.isBlank(md.getContainerName())) {
                    java.nio.file.Path destination = Paths.get(CONTAINER_UPLOADS,
                            String.valueOf(md.getCodeId()), md.getContainerName());
                    fullContainerName = destination.toString();
                    container = Files.newInputStream(destination);
                }
            }

            // if a FILE or CONTAINER was sent, create a File Object from it
            File archiveFile = (null == file) ? null : new File(fullFileName);
            File archiveContainer = null; //(null==container) ? null : new File(fullContainerName);
            if (DOECodeMetadata.Accessibility.CO.equals(md.getAccessibility()))
                // if CO project type, no need to archive the repo because it is local GitLab
                sendToArchiver(md.getCodeId(), null, archiveFile, archiveContainer);
            else
                sendToArchiver(md.getCodeId(), md.getRepositoryLink(), archiveFile, archiveContainer);
        } catch (IOException e) {
            log.error("Archiver call failure: " + e.getMessage());
            return ErrorResponse.internalServerError("Unable to archive project.").build();
        }

        // send any updates to DataCite as well (if RELEASE DATE is set)
        if (StringUtils.isNotEmpty(md.getDoi()) && null != md.getReleaseDate()) {
            try {
                DataCite.register(md);
            } catch (IOException e) {
                // if DataCite registration failed, say why
                log.warn("DataCite ERROR: " + e.getMessage());
                return ErrorResponse.internalServerError(
                        "The DOI registration service is currently unavailable, please try to submit your record later. If the issue persists, please contact doecode@osti.gov.")
                        .build();
            }
        }
        // store the snapshot copy of Metadata in SPECIAL STATUS
        MetadataSnapshot snapshot = new MetadataSnapshot();
        snapshot.getSnapshotKey().setCodeId(md.getCodeId());
        snapshot.getSnapshotKey().setSnapshotStatus(md.getWorkflowStatus());
        snapshot.setDoi(md.getDoi());
        snapshot.setDoiIsMinted(md.getReleaseDate() != null);
        snapshot.setJson(md.toJson().toString());

        em.merge(snapshot);

        // if we make it this far, go ahead and commit the transaction
        em.getTransaction().commit();

        // send NOTIFICATION if configured
        sendStatusNotification(md);

        // and we're happy
        return Response.ok().entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString())
                .build();
    } catch (BadRequestException e) {
        return e.getResponse();
    } catch (NotFoundException e) {
        return ErrorResponse.notFound(e.getMessage()).build();
    } catch (IllegalAccessException e) {
        log.warn("Persistence Error: Invalid owner update attempt: " + user.getEmail());
        log.warn("Message: " + e.getMessage());
        return ErrorResponse.forbidden("Invalid Access: Unable to edit indicated record.").build();
    } catch (ValidationException e) {
        log.warn("Validation Error: " + e.getMessage());
        return ErrorResponse.badRequest(e.getMessage()).build();
    } catch (IOException | InvocationTargetException e) {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();

        log.warn("Persistence Error: " + e.getMessage());
        return ErrorResponse.internalServerError("IO Error announcing record.").build();
    } finally {
        em.close();
    }
}