Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

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

/**
 * Acquire a List of records in pending ("Submitted") state, to be approved
 * for indexing and searching.//  w  w w .j a  v  a  2 s . c om
 *
 * JSON response is of the form:
 *
 * {"records":[{"code_id":n, ...} ],
 *  "start":0, "rows":20, "total":100}
 *
 * Where records is an array of DOECodeMetadata JSON, start is the beginning
 * row number, rows is the number requested (or total if less available),
 * and total is the total number of rows matching the filter.
 *
 * Return Codes:
 * 200 - OK, JSON is returned as above
 * 401 - Unauthorized, login is required
 * 403 - Forbidden, insufficient privileges (role required)
 * 500 - unexpected error
 *
 * @param start the starting row number (from 0)
 * @param rows number of rows desired (0 is unlimited)
 * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site
 * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of
 * Approved, Saved, Submitted, or Announced, if supplied.
 * @return JSON of a records response
 */
@GET
@Path("/projects/pending")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows,
        @QueryParam("site") String siteCode, @QueryParam("state") String state) {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        // get a JPA CriteriaBuilder instance
        CriteriaBuilder cb = em.getCriteriaBuilder();
        // create a CriteriaQuery for the COUNT
        CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
        Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class);
        countQuery.select(cb.count(md));

        Expression<String> workflowStatus = md.get("workflowStatus");
        Expression<String> siteOwnershipCode = md.get("siteOwnershipCode");

        // default requested STATE; take Submitted and Announced as the default values if not supplied
        List<DOECodeMetadata.Status> requestedStates = new ArrayList();
        String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase();
        switch (queryState) {
        case "approved":
            requestedStates.add(DOECodeMetadata.Status.Approved);
            break;
        case "saved":
            requestedStates.add(DOECodeMetadata.Status.Saved);
            break;
        case "submitted":
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            break;
        case "announced":
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        default:
            requestedStates.add(DOECodeMetadata.Status.Submitted);
            requestedStates.add(DOECodeMetadata.Status.Announced);
            break;
        }

        Predicate statusPredicate = workflowStatus.in(requestedStates);
        ParameterExpression<String> site = cb.parameter(String.class, "site");

        if (null == siteCode) {
            countQuery.where(statusPredicate);
        } else {
            countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }
        // query for the COUNT
        TypedQuery<Long> cq = em.createQuery(countQuery);
        cq.setParameter("status", requestedStates);
        if (null != siteCode)
            cq.setParameter("site", siteCode);

        long rowCount = cq.getSingleResult();
        // rows count should be less than 100 for pagination; 0 is a special case
        rows = (rows > 100) ? 100 : rows;

        // create a CriteriaQuery for the ROWS
        CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class);
        rowQuery.select(md);

        if (null == siteCode) {
            rowQuery.where(statusPredicate);
        } else {
            rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site)));
        }

        TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery);
        rq.setParameter("status", requestedStates);
        if (null != siteCode)
            rq.setParameter("site", siteCode);
        rq.setFirstResult(start);
        if (0 != rows)
            rq.setMaxResults(rows);

        RecordsList records = new RecordsList(rq.getResultList());
        records.setTotal(rowCount);
        records.setStart(start);

        return Response.ok().entity(mapper.valueToTree(records).toString()).build();
    } finally {
        em.close();
    }
}

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./*www  .  ja  v  a  2s. c  o 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:entity.files.SYSFilesTools.java

public static List<SYSFiles> putFiles(File[] files, Object attachable) {
    ArrayList<SYSFiles> successful = new ArrayList<SYSFiles>(files.length);
    FileTransferClient ftp = getFTPClient();

    if (ftp != null) {
        EntityManager em = OPDE.createEM();
        try {/*from   w w w . ja v  a  2 s.  c  o m*/
            em.getTransaction().begin();

            for (File file : files) {
                if (file.isFile()) { // prevents exceptions if somebody has the bright idea to include directories.
                    SYSFiles sysfile = putFile(em, ftp, file);
                    if (attachable != null) {
                        if (attachable instanceof NReport) {
                            SYSNR2FILE link = em.merge(new SYSNR2FILE(sysfile, (NReport) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNrAssignCollection().add(link);
                            ((NReport) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Prescription) {
                            SYSPRE2FILE link = em.merge(new SYSPRE2FILE(sysfile, (Prescription) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getPreAssignCollection().add(link);
                            ((Prescription) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResInfo) {
                            SYSINF2FILE link = em.merge(new SYSINF2FILE(sysfile, (ResInfo) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getBwiAssignCollection().add(link);
                            ((ResInfo) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof ResValue) {
                            SYSVAL2FILE link = em.merge(new SYSVAL2FILE(sysfile, (ResValue) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getValAssignCollection().add(link);
                            ((ResValue) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof NursingProcess) {
                            SYSNP2FILE link = em.merge(new SYSNP2FILE(sysfile, (NursingProcess) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getNpAssignCollection().add(link);
                            ((NursingProcess) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Users) {
                            User2File link = em.merge(new User2File(sysfile, (Users) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getUsersAssignCollection().add(link);
                            ((Users) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Resident) {
                            Resident2File link = em.merge(new Resident2File(sysfile, (Resident) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getResidentAssignCollection().add(link);
                            ((Resident) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qmsplan) {
                            Qmsplan2File link = em.merge(new Qmsplan2File(sysfile, (Qmsplan) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsplanAssignCollection().add(link);
                            ((Qmsplan) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Qms) {
                            Qms2File link = em.merge(new Qms2File(sysfile, (Qms) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getQmsAssignCollection().add(link);
                            ((Qms) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training) {
                            Training2File link = em.merge(new Training2File(sysfile, (Training) attachable,
                                    OPDE.getLogin().getUser(), new Date()));
                            sysfile.getTrainingAssignCollection().add(link);
                            ((Training) attachable).getAttachedFilesConnections().add(link);
                        } else if (attachable instanceof Training2Users) {
                            em.merge(((SYSFilesContainer) attachable).attachFile(sysfile));
                        }
                    }
                    successful.add(sysfile);
                }
                if (successful.size() != files.length) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage(SYSTools.xx("misc.msg.nodirectories")));
                }
            }
            em.getTransaction().commit();
        } 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();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
        } catch (Exception ex) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            // Bereits gespeicherte wieder lschen
            //                for (SYSFiles sysfile : successful) {
            //                    try {
            //                        ftp.deleteFile(sysfile.getRemoteFilename());
            //                    } catch (IOException e) {
            //                        OPDE.fatal(e);
            //                    }
            //                }
            OPDE.fatal(ex);
        } finally {
            em.close();
            try {
                ftp.disconnect();
            } catch (Exception e) {
                OPDE.error(e);
            }
        }
    }
    return successful;
}

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

/**
 * Acquire a listing of all records by OWNER.
 *
 * @param rows the number of rows desired (if present)
 * @param start the starting row number (from 0)
 * @return the Metadata information in the desired format
 * @throws JsonProcessingException/*from w w w.  j  a v  a2 s  .  co m*/
 */
@GET
@Path("/projects")
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
public Response listProjects(@QueryParam("rows") int rows, @QueryParam("start") int start)
        throws JsonProcessingException {
    EntityManager em = DoeServletContextListener.createEntityManager();

    // get the security user in context
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    try {
        Set<String> roles = user.getRoles();
        String rolecode = (null == roles) ? "" : (roles.isEmpty()) ? "" : roles.iterator().next();

        TypedQuery<DOECodeMetadata> query;
        // admins see ALL PROJECTS
        if ("OSTI".equals(rolecode)) {
            query = em.createQuery("SELECT md FROM DOECodeMetadata md", DOECodeMetadata.class);
        } else if (StringUtils.isNotEmpty(rolecode)) {
            // if you have another ROLE, it is assumed to be a SITE ADMIN; see all those records
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.siteOwnershipCode = :site",
                    DOECodeMetadata.class).setParameter("site", rolecode);
        } else {
            // no roles, you see only YOUR OWN projects
            query = em.createQuery("SELECT md FROM DOECodeMetadata md WHERE md.owner = lower(:owner)",
                    DOECodeMetadata.class).setParameter("owner", user.getEmail());
        }

        // if rows specified, and greater than 100, cap it there
        rows = (rows > 100) ? 100 : rows;

        // if pagination elements are present, set them on the query
        if (0 != rows)
            query.setMaxResults(rows);
        if (0 != start)
            query.setFirstResult(start);

        // get a List of records
        RecordsList records = new RecordsList(query.getResultList());
        records.setStart(start);
        ObjectNode recordsObject = mapper.valueToTree(records);

        // lookup previous Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        // lookup system Snapshot status info for each item
        TypedQuery<MetadataSnapshot> querySystemSnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdAsSystemStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);

        JsonNode recordNode = recordsObject.get("records");
        if (recordNode.isArray()) {
            int rowCount = 0;
            for (JsonNode objNode : recordNode) {
                rowCount++;

                // skip non-approved records
                String currentStatus = objNode.get("workflow_status").asText();
                if (!currentStatus.equalsIgnoreCase("Approved"))
                    continue;

                // get code_id to find Snapshot
                long codeId = objNode.get("code_id").asLong();
                querySnapshot.setParameter("codeId", codeId);
                querySystemSnapshot.setParameter("codeId", codeId);

                String lastApprovalFor = "";
                List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : results) {
                    lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "approve as" status indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("approved_as", lastApprovalFor);

                String systemStatus = "";
                List<MetadataSnapshot> resultsSystem = querySystemSnapshot.setMaxResults(1).getResultList();
                for (MetadataSnapshot ms : resultsSystem) {
                    systemStatus = ms.getSnapshotKey().getSnapshotStatus().toString();
                }

                // add "system status" indicator to response record, if not blank
                if (!StringUtils.isBlank(lastApprovalFor))
                    ((ObjectNode) objNode).put("system_status", systemStatus);
            }

            recordsObject.put("total", rowCount);
        }

        return Response.status(Response.Status.OK).entity(recordsObject.toString()).build();
    } finally {
        em.close();
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Register a new registry profile./*w w  w. ja v  a2 s.c o  m*/
 * @param profile
 * @return
 * @throws Exception
 */
public AckType register(PersonRegistryProfileType profile) {

    EntityManager em = null;
    PersistentServiceFactory psf = null;
    StringBuffer exceptionMsg = new StringBuffer();

    AckType ack = new AckType();
    ack.setResponseCode(_APPLICATION_ERROR);

    if (profile != null && profile.getPerson() != null && profile.getRegistry() != null
            && !profile.getRegistry().isEmpty() && profile.getDataSource() != null) {
        //------------------------------------------------------------------------
        // Registry type must be valid.
        //------------------------------------------------------------------------
        Map<Integer, DzType> toBeRegisterDzTypes = Collections.synchronizedMap(new HashMap<Integer, DzType>());
        for (RegistryType r : profile.getRegistry()) {
            try {
                DzType dzType = this.validRegistryType(r);
                if (dzType != null) {
                    toBeRegisterDzTypes.put(Integer.valueOf(dzType.getDztypeId()), dzType);
                } else {
                    exceptionMsg.append("Invalid/Unknown registy type specified - " + r.getRegistryId() + ";");
                }
            } catch (Exception ex) {
                exceptionMsg.append(ex.getMessage() + ";");
            }
        }

        //----------------------------------------------------------------------
        // Person info must have following elements:
        //   1. Identifer
        //   2. Name
        //   3. Date of birth
        //   4. Data Source
        //----------------------------------------------------------------------
        PersonType person = profile.getPerson();

        if (person.getName() == null || person.getName().isEmpty()
                || (person.getDataSource() == null && profile.getDataSource() == null)) {
            ack.setDetectedIssueText("Missing required metadata (person identifier or name or data source);");
            return ack;
        }

        //------------------------------------------------------------------------
        // Check to see if this person already registered.
        //------------------------------------------------------------------------
        DzPatients registeredPatient = null;

        try {
            registeredPatient = validPerson(person);
        } catch (javax.persistence.NoResultException nre) {
        } catch (Exception ex) {
            ack.setDetectedIssueText("Failed to register patient - " + ex.getMessage());
            return ack;
        }

        try {
            psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
            em = psf.getEntityManager();

            em.getTransaction().begin();

            // Get the date today using Calendar object.
            Calendar cal = Calendar.getInstance();
            Timestamp today = new Timestamp(cal.getTimeInMillis());

            //----------------------------------------------------------------------
            // If yes, only need to add a record to table DZ_REG for each new
            // registry type.
            //----------------------------------------------------------------------
            if (registeredPatient != null) {
                // remove any registry type (from request) that is already assigned to
                // this person
                Collection<DzReg> registries = registeredPatient.getDzRegCollection();
                for (DzReg r : registries) {
                    Integer intDzTypeId = Integer.valueOf(r.getDzType().getDztypeId());
                    if (toBeRegisterDzTypes.containsKey(intDzTypeId)) {
                        toBeRegisterDzTypes.remove(intDzTypeId);

                        log.debug("Already registered in Registry " + intDzTypeId + "!");
                        exceptionMsg.append("Already registered in Registry " + intDzTypeId + ";");
                    }
                }

                // what we have left is new registry type to be add to person registry
                // profile
                Collection<DzType> toBeRegisterColl = toBeRegisterDzTypes.values();
                for (DzType d : toBeRegisterColl) {
                    // only need to add a record to table DZ_REG
                    DzRegPK pk = new DzRegPK(person.getId(), d.getDztypeId());
                    DzReg newDzreg = new DzReg();
                    newDzreg.setDzRegPK(pk);
                    newDzreg.setActive(_ACTIVE);
                    newDzreg.setDataSource(person.getDataSource());
                    newDzreg.setRegisteredDt(today);
                    newDzreg.setInsertedDt(today);

                    em.persist(newDzreg);
                }
            } //----------------------------------------------------------------------
              // If no, need to insert a new record in DZ_PATIENTS table and a new
              // record in table DZ_REG for each new registry type.
              //----------------------------------------------------------------------
            else {
                DzPatients newDzPatient = map(person);
                newDzPatient.setInsertedDt(today);
                newDzPatient.setUpdatedDt(today);
                if (person.getDataSource() == null) {
                    if (profile.getDataSource() != null) {
                        newDzPatient.setDataSource(profile.getDataSource());
                    } else {
                        // cannot insert record
                        throw new Exception("Missing required metadata (data source);");
                    }
                } else {
                    newDzPatient.setDataSource(profile.getDataSource());
                }

                Collection<DzType> dzTypes = toBeRegisterDzTypes.values();
                Collection<DzReg> newDzregList = new ArrayList<DzReg>(dzTypes.size());
                for (DzType dzType : dzTypes) {
                    DzRegPK pk = new DzRegPK(person.getId(), dzType.getDztypeId());
                    DzReg newDzreg = new DzReg();
                    newDzreg.setDzRegPK(pk);
                    newDzreg.setActive(_ACTIVE);
                    newDzreg.setRegisteredDt(today);
                    newDzreg.setInsertedDt(today);

                    if (person.getDataSource() == null) {
                        newDzreg.setDataSource(profile.getDataSource());
                    } else {
                        newDzreg.setDataSource(person.getDataSource());
                    }

                    newDzregList.add(newDzreg);
                }

                newDzPatient.setDzRegCollection(newDzregList);
                em.persist(newDzPatient);
            }

            em.getTransaction().commit();

            ack.setResponseCode(_OK);
            ack.setDetectedIssueText(exceptionMsg.toString());

            return ack;
        } catch (Exception ex) {
            ex.printStackTrace();
            em.getTransaction().rollback();
            log.error("Failed to create new records in table DZ_PATIENTS/DZ_REG for profile=" + profile);

            ack.setDetectedIssueText(
                    "Failed to register patient " + profile.getPerson().getId() + "-" + ex.getMessage());
            return ack;
        } finally {
            em.close();
        }
    } else {
        ack.setDetectedIssueText("Invalid registry profile");
        return ack;
    }
}

From source file:op.care.bhp.PnlBHP.java

private CollapsiblePane createCP4(final BHP bhp) {
    final CollapsiblePane bhpPane = new CollapsiblePane();
    bhpPane.setCollapseOnTitleClick(false);

    ActionListener applyActionListener = new ActionListener() {
        @Override/*from   ww  w. j  a  v a2 s .  co  m*/
        public void actionPerformed(ActionEvent actionEvent) {
            if (bhp.getState() != BHPTools.STATE_OPEN) {
                return;
            }
            if (bhp.getPrescription().isClosed()) {
                return;
            }

            if (BHPTools.isChangeable(bhp)) {
                outcomeText = null;
                if (bhp.getNeedsText()) {
                    new DlgYesNo(SYSConst.icon48comment, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                outcomeText = null;
                            } else {
                                outcomeText = o.toString();
                            }
                        }
                    }, "nursingrecords.bhp.describe.outcome", null, null);

                }

                if (bhp.getNeedsText() && outcomeText == null) {
                    OPDE.getDisplayManager().addSubMessage(
                            new DisplayMessage("nursingrecords.bhp.notext.nooutcome", DisplayMessage.WARNING));
                    return;
                }

                if (bhp.getPrescription().isWeightControlled()) {
                    new DlgYesNo(SYSConst.icon48scales, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (SYSTools.catchNull(o).isEmpty()) {
                                weight = null;
                            } else {
                                weight = (BigDecimal) o;
                            }
                        }
                    }, "nursingrecords.bhp.weight", null, new Validator<BigDecimal>() {
                        @Override
                        public boolean isValid(String value) {
                            BigDecimal bd = parse(value);
                            return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                        }

                        @Override
                        public BigDecimal parse(String text) {
                            return SYSTools.parseDecimal(text);
                        }
                    });

                }

                if (bhp.getPrescription().isWeightControlled() && weight == null) {
                    OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                            "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                    return;
                }

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();

                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    BHP myBHP = em.merge(bhp);
                    em.lock(myBHP, LockModeType.OPTIMISTIC);

                    if (myBHP.isOnDemand()) {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                    } else {
                        em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                        em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);
                    }

                    myBHP.setState(BHPTools.STATE_DONE);
                    myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                    myBHP.setIst(new Date());
                    myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                    myBHP.setMDate(new Date());
                    myBHP.setText(outcomeText);

                    Prescription involvedPresciption = null;
                    if (myBHP.shouldBeCalculated()) {
                        MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                myBHP.getTradeForm());
                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(), weight, myBHP);
                        // Was the prescription closed during this withdraw ?
                        involvedPresciption = em.find(Prescription.class, myBHP.getPrescription().getID());
                    }

                    BHP outcomeBHP = null;
                    // add outcome check BHP if necessary
                    if (!myBHP.isOutcomeText()
                            && myBHP.getPrescriptionSchedule().getCheckAfterHours() != null) {
                        outcomeBHP = em.merge(new BHP(myBHP));
                        mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND).add(outcomeBHP);
                    }

                    em.getTransaction().commit();

                    if (myBHP.shouldBeCalculated() && involvedPresciption.isClosed()) { // &&
                        reload();
                    } else if (outcomeBHP != null) {
                        reload();
                    } else {
                        mapBHP2Pane.put(myBHP, createCP4(myBHP));
                        int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                        mapShift2BHP.get(myBHP.getShift()).remove(position);
                        mapShift2BHP.get(myBHP.getShift()).add(position, myBHP);
                        if (myBHP.isOnDemand()) {
                            // This whole thing here is only to handle the BPHs on Demand
                            // Fix the other BHPs on demand. If not, you will get locking exceptions,
                            // we FORCED INCREMENTED LOCKS on the Schedule and the Prescription.
                            ArrayList<BHP> changeList = new ArrayList<BHP>();
                            for (BHP bhp : mapShift2BHP.get(BHPTools.SHIFT_ON_DEMAND)) {
                                if (bhp.getPrescription().getID() == myBHP.getPrescription().getID()
                                        && bhp.getBHPid() != myBHP.getBHPid()) {
                                    bhp.setPrescription(myBHP.getPrescription());
                                    bhp.setPrescriptionSchedule(myBHP.getPrescriptionSchedule());
                                    changeList.add(bhp);
                                }
                            }
                            for (BHP bhp : changeList) {
                                mapBHP2Pane.put(bhp, createCP4(myBHP));
                                position = mapShift2BHP.get(bhp.getShift()).indexOf(bhp);
                                mapShift2BHP.get(myBHP.getShift()).remove(position);
                                mapShift2BHP.get(myBHP.getShift()).add(position, bhp);
                            }

                            Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                    BHPTools.getOnDemandComparator());
                        } else {
                            Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                        }

                        mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                        buildPanel(false);
                    }
                } 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();
                }

            } else {
                OPDE.getDisplayManager()
                        .addSubMessage(new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
            }
        }
    };

    //        JPanel titlePanelleft = new JPanel();
    //        titlePanelleft.setLayout(new BoxLayout(titlePanelleft, BoxLayout.LINE_AXIS));

    MedStock stock = mapPrescription2Stock.get(bhp.getPrescription());
    if (bhp.hasMed() && stock == null) {
        stock = MedStockTools
                .getStockInUse(TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm()));
        mapPrescription2Stock.put(bhp.getPrescription(), stock);
    }

    String title;

    if (bhp.isOutcomeText()) {
        title = "<html><font size=+1>"
                + SYSConst.html_italic(SYSTools
                        .left("&ldquo;" + PrescriptionTools.getShortDescriptionAsCompactText(
                                bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                        + BHPTools.getScheduleText(bhp.getOutcome4(), "&rdquo;, ", ""))
                + " [" + bhp.getPrescriptionSchedule().getCheckAfterHours() + " "
                + SYSTools.xx("misc.msg.Hour(s)") + "] " + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                +

                "</font></html>";
    } else {
        title = "<html><font size=+1>"
                + SYSTools.left(PrescriptionTools.getShortDescriptionAsCompactText(
                        bhp.getPrescriptionSchedule().getPrescription()), MAX_TEXT_LENGTH)
                + (bhp.hasMed()
                        ? ", <b>" + SYSTools.getAsHTML(bhp.getDose()) + " "
                                + DosageFormTools.getUsageText(
                                        bhp.getPrescription().getTradeForm().getDosageForm())
                                + "</b>"
                        : "")
                + BHPTools.getScheduleText(bhp, ", ", "")
                + (bhp.getPrescription().isWeightControlled()
                        ? " " + SYSConst.html_16x16_scales_internal + (bhp.isOpen() ? ""
                                : (bhp.getStockTransaction().isEmpty() ? " "
                                        : NumberFormat.getNumberInstance()
                                                .format(bhp.getStockTransaction().get(0).getWeight()) + "g "))
                        : "")
                + (bhp.getUser() != null ? ", <i>" + SYSTools.anonymizeUser(bhp.getUser().getUID()) + "</i>"
                        : "")
                + "</font></html>";
    }

    DefaultCPTitle cptitle = new DefaultCPTitle(title,
            OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID) ? applyActionListener
                    : null);

    JLabel icon1 = new JLabel(BHPTools.getIcon(bhp));
    icon1.setOpaque(false);
    if (!bhp.isOpen()) {
        icon1.setToolTipText(DateFormat.getDateTimeInstance().format(bhp.getIst()));
    }

    JLabel icon2 = new JLabel(BHPTools.getWarningIcon(bhp, stock));
    icon2.setOpaque(false);

    cptitle.getAdditionalIconPanel().add(icon1);
    cptitle.getAdditionalIconPanel().add(icon2);

    if (bhp.getPrescription().isClosed()) {
        JLabel icon3 = new JLabel(SYSConst.icon22stopSign);
        icon3.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon3);
    }

    if (bhp.isOutcomeText()) {
        JLabel icon4 = new JLabel(SYSConst.icon22comment);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (!bhp.isOutcomeText() && bhp.getPrescriptionSchedule().getCheckAfterHours() != null) {
        JLabel icon4 = new JLabel(SYSConst.icon22intervalBySecond);
        icon4.setOpaque(false);
        cptitle.getAdditionalIconPanel().add(icon4);
    }

    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        if (!bhp.getPrescription().isClosed()) {

            /***
             *      _     _            _                _
             *     | |__ | |_ _ __    / \   _ __  _ __ | |_   _
             *     | '_ \| __| '_ \  / _ \ | '_ \| '_ \| | | | |
             *     | |_) | |_| | | |/ ___ \| |_) | |_) | | |_| |
             *     |_.__/ \__|_| |_/_/   \_\ .__/| .__/|_|\__, |
             *                             |_|   |_|      |___/
             */
            JButton btnApply = new JButton(SYSConst.icon22apply);
            btnApply.setPressedIcon(SYSConst.icon22applyPressed);
            btnApply.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnApply.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnApply.tooltip"));
            btnApply.addActionListener(applyActionListener);
            btnApply.setContentAreaFilled(false);
            btnApply.setBorder(null);
            btnApply.setEnabled(bhp.isOpen()
                    && (!bhp.hasMed() || mapPrescription2Stock.containsKey(bhp.getPrescription())));
            cptitle.getRight().add(btnApply);

            /***
             *                             ____  _             _
             *       ___  _ __   ___ _ __ / ___|| |_ ___   ___| | __
             *      / _ \| '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ /
             *     | (_) | |_) |  __/ | | |___) | || (_) | (__|   <
             *      \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\
             *           |_|
             */
            if (bhp.hasMed() && stock == null && MedInventoryTools.getNextToOpen(
                    TradeFormTools.getInventory4TradeForm(resident, bhp.getTradeForm())) != null) {
                final JButton btnOpenStock = new JButton(SYSConst.icon22ledGreenOn);
                btnOpenStock.setPressedIcon(SYSConst.icon22ledGreenOff);
                btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnOpenStock.setContentAreaFilled(false);
                btnOpenStock.setBorder(null);
                btnOpenStock.setToolTipText(SYSTools
                        .toHTMLForScreen(SYSTools.xx("nursingrecords.inventory.stock.btnopen.tooltip")));
                btnOpenStock.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {

                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);
                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            MedStock myStock = em.merge(MedInventoryTools.openNext(
                                    TradeFormTools.getInventory4TradeForm(resident, myBHP.getTradeForm())));
                            em.lock(myStock, LockModeType.OPTIMISTIC);
                            em.getTransaction().commit();

                            OPDE.getDisplayManager()
                                    .addSubMessage(new DisplayMessage(
                                            String.format(SYSTools.xx("newstocks.stock.has.been.opened"),
                                                    myStock.getID().toString())));
                            reload();

                        } 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(btnOpenStock);
            }

            if (!bhp.isOutcomeText()) {
                /***
                 *      _     _         ____       __
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|
                 *
                 */
                final JButton btnRefuse = new JButton(SYSConst.icon22cancel);
                btnRefuse.setPressedIcon(SYSConst.icon22cancelPressed);
                btnRefuse.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuse.setContentAreaFilled(false);
                btnRefuse.setBorder(null);
                btnRefuse.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuse.tooltip")));
                btnRefuse.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } 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();
                            }

                        } else {
                            OPDE.getDisplayManager().addSubMessage(
                                    new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                        }
                    }
                });
                btnRefuse.setEnabled(!bhp.isOnDemand() && bhp.isOpen());
                cptitle.getRight().add(btnRefuse);

                /***
                 *      _     _         ____       __                ____  _                       _
                 *     | |__ | |_ _ __ |  _ \ ___ / _|_   _ ___  ___|  _ \(_)___  ___ __ _ _ __ __| |
                 *     | '_ \| __| '_ \| |_) / _ \ |_| | | / __|/ _ \ | | | / __|/ __/ _` | '__/ _` |
                 *     | |_) | |_| | | |  _ <  __/  _| |_| \__ \  __/ |_| | \__ \ (_| (_| | | | (_| |
                 *     |_.__/ \__|_| |_|_| \_\___|_|  \__,_|___/\___|____/|_|___/\___\__,_|_|  \__,_|
                 *
                 */
                final JButton btnRefuseDiscard = new JButton(SYSConst.icon22deleteall);
                btnRefuseDiscard.setPressedIcon(SYSConst.icon22deleteallPressed);
                btnRefuseDiscard.setAlignmentX(Component.RIGHT_ALIGNMENT);
                btnRefuseDiscard.setContentAreaFilled(false);
                btnRefuseDiscard.setBorder(null);
                btnRefuseDiscard.setToolTipText(
                        SYSTools.toHTMLForScreen(SYSTools.xx("nursingrecords.bhp.btnRefuseDiscard.tooltip")));
                btnRefuseDiscard.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent actionEvent) {
                        if (bhp.getState() != BHPTools.STATE_OPEN) {
                            return;
                        }

                        if (BHPTools.isChangeable(bhp)) {

                            if (bhp.getPrescription().isWeightControlled()) {
                                new DlgYesNo(SYSConst.icon48scales, new Closure() {
                                    @Override
                                    public void execute(Object o) {
                                        if (SYSTools.catchNull(o).isEmpty()) {
                                            weight = null;
                                        } else {
                                            weight = (BigDecimal) o;
                                        }
                                    }
                                }, "nursingrecords.bhp.weight", null, new Validator<BigDecimal>() {
                                    @Override
                                    public boolean isValid(String value) {
                                        BigDecimal bd = parse(value);
                                        return bd != null && bd.compareTo(BigDecimal.ZERO) > 0;

                                    }

                                    @Override
                                    public BigDecimal parse(String text) {
                                        return SYSTools.parseDecimal(text);
                                    }
                                });

                            }

                            if (bhp.getPrescription().isWeightControlled() && weight == null) {
                                OPDE.getDisplayManager().addSubMessage(new DisplayMessage(
                                        "nursingrecords.bhp.noweight.nosuccess", DisplayMessage.WARNING));
                                return;
                            }

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                BHP myBHP = em.merge(bhp);
                                em.lock(myBHP, LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                                em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                                myBHP.setState(BHPTools.STATE_REFUSED_DISCARDED);
                                myBHP.setUser(em.merge(OPDE.getLogin().getUser()));
                                myBHP.setIst(new Date());
                                myBHP.setiZeit(SYSCalendar.whatTimeIDIs(new Date()));
                                myBHP.setMDate(new Date());

                                if (myBHP.shouldBeCalculated()) {
                                    MedInventory inventory = TradeFormTools.getInventory4TradeForm(resident,
                                            myBHP.getTradeForm());
                                    if (inventory != null) {
                                        MedInventoryTools.withdraw(em, em.merge(inventory), myBHP.getDose(),
                                                weight, myBHP);
                                    } else {
                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage("nursingrecords.bhp.NoInventory"));
                                    }
                                }

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                em.getTransaction().commit();
                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            } 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();
                            }

                        } else {
                            OPDE.getDisplayManager().addSubMessage(
                                    new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                        }
                    }
                });

                btnRefuseDiscard.setEnabled(
                        !bhp.isOnDemand() && bhp.hasMed() && bhp.shouldBeCalculated() && bhp.isOpen());
                cptitle.getRight().add(btnRefuseDiscard);
            }

            /***
             *      _     _         _____                 _
             *     | |__ | |_ _ __ | ____|_ __ ___  _ __ | |_ _   _
             *     | '_ \| __| '_ \|  _| | '_ ` _ \| '_ \| __| | | |
             *     | |_) | |_| | | | |___| | | | | | |_) | |_| |_| |
             *     |_.__/ \__|_| |_|_____|_| |_| |_| .__/ \__|\__, |
             *                                     |_|        |___/
             */
            final JButton btnEmpty = new JButton(SYSConst.icon22empty);
            btnEmpty.setPressedIcon(SYSConst.icon22emptyPressed);
            btnEmpty.setAlignmentX(Component.RIGHT_ALIGNMENT);
            btnEmpty.setContentAreaFilled(false);
            btnEmpty.setBorder(null);
            btnEmpty.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnEmpty.tooltip"));
            btnEmpty.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {
                    if (bhp.getState() == BHPTools.STATE_OPEN) {
                        return;
                    }

                    BHP outcomeBHP = BHPTools.getComment(bhp);

                    if (outcomeBHP != null && !outcomeBHP.isOpen()) {
                        // already commented
                        return;
                    }

                    if (BHPTools.isChangeable(bhp)) {
                        EntityManager em = OPDE.createEM();
                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            BHP myBHP = em.merge(bhp);

                            em.lock(myBHP, LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescriptionSchedule(), LockModeType.OPTIMISTIC);
                            em.lock(myBHP.getPrescription(), LockModeType.OPTIMISTIC);

                            // the normal BHPs (those assigned to a NursingProcess) are reset to the OPEN state.
                            // TXs are deleted
                            myBHP.setState(BHPTools.STATE_OPEN);
                            myBHP.setUser(null);
                            myBHP.setIst(null);
                            myBHP.setiZeit(null);
                            myBHP.setMDate(new Date());
                            myBHP.setText(null);

                            if (myBHP.shouldBeCalculated()) {
                                for (MedStockTransaction tx : myBHP.getStockTransaction()) {
                                    em.remove(tx);
                                }
                                myBHP.getStockTransaction().clear();
                            }

                            if (outcomeBHP != null) {
                                BHP myOutcomeBHP = em.merge(outcomeBHP);
                                em.remove(myOutcomeBHP);
                            }

                            if (myBHP.isOnDemand()) {
                                em.remove(myBHP);
                            }

                            em.getTransaction().commit();

                            if (myBHP.isOnDemand()) {
                                reload();
                            } else {

                                mapBHP2Pane.put(myBHP, createCP4(myBHP));
                                int position = mapShift2BHP.get(myBHP.getShift()).indexOf(bhp);
                                mapShift2BHP.get(bhp.getShift()).remove(position);
                                mapShift2BHP.get(bhp.getShift()).add(position, myBHP);
                                if (myBHP.isOnDemand()) {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()),
                                            BHPTools.getOnDemandComparator());
                                } else {
                                    Collections.sort(mapShift2BHP.get(myBHP.getShift()));
                                }

                                mapShift2Pane.put(myBHP.getShift(), createCP4(myBHP.getShift()));
                                buildPanel(false);
                            }
                        } 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();
                        }

                    } else {
                        OPDE.getDisplayManager().addSubMessage(
                                new DisplayMessage(SYSTools.xx("nursingrecords.bhp.notchangeable")));
                    }
                }
            });
            btnEmpty.setEnabled(!bhp.isOpen());
            cptitle.getRight().add(btnEmpty);
        }

        /***
         *      _     _         ___        __
         *     | |__ | |_ _ __ |_ _|_ __  / _| ___
         *     | '_ \| __| '_ \ | || '_ \| |_ / _ \
         *     | |_) | |_| | | || || | | |  _| (_) |
         *     |_.__/ \__|_| |_|___|_| |_|_|  \___/
         *
         */
        final JButton btnInfo = new JButton(SYSConst.icon22info);

        btnInfo.setPressedIcon(SYSConst.icon22infoPressed);
        btnInfo.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnInfo.setContentAreaFilled(false);
        btnInfo.setBorder(null);
        btnInfo.setToolTipText(SYSTools.xx("nursingrecords.bhp.btnInfo.tooltip"));
        final JTextPane txt = new JTextPane();
        txt.setContentType("text/html");
        txt.setEditable(false);
        final JidePopup popupInfo = new JidePopup();
        popupInfo.setMovable(false);
        popupInfo.setContentPane(new JScrollPane(txt));
        popupInfo.removeExcludedComponent(txt);
        popupInfo.setDefaultFocusComponent(txt);

        btnInfo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                popupInfo.setOwner(btnInfo);

                if (bhp.isOutcomeText() && !bhp.isOpen()) {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getText())));
                } else {
                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                }

                //                    txt.setText(SYSTools.toHTML(SYSConst.html_div(bhp.getPrescription().getText())));
                GUITools.showPopup(popupInfo, SwingConstants.SOUTH_WEST);
            }
        });

        if (bhp.isOutcomeText() && !bhp.isOpen()) {
            btnInfo.setEnabled(true);
        } else {
            btnInfo.setEnabled(!SYSTools.catchNull(bhp.getPrescription().getText()).isEmpty());
        }

        cptitle.getRight().add(btnInfo);

    }

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

    final JTextPane contentPane = new JTextPane();
    contentPane.setEditable(false);
    contentPane.setContentType("text/html");
    bhpPane.setContentPane(contentPane);
    bhpPane.setBackground(bhp.getBG());
    bhpPane.setForeground(bhp.getFG());

    try {
        bhpPane.setCollapsed(true);
    } catch (PropertyVetoException e) {
        OPDE.error(e);
    }

    bhpPane.addCollapsiblePaneListener(new CollapsiblePaneAdapter() {
        @Override
        public void paneExpanded(CollapsiblePaneEvent collapsiblePaneEvent) {
            contentPane.setText(SYSTools.toHTML(
                    PrescriptionTools.getPrescriptionAsHTML(bhp.getPrescription(), false, false, true, false)));
        }
    });

    bhpPane.setHorizontalAlignment(SwingConstants.LEADING);
    bhpPane.setOpaque(false);
    return bhpPane;
}

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// w  w w .j  av a2 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();
    }
}

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

/**
 * Handle SUBMIT workflow logic.// w ww  . jav  a  2  s.co m
 *
 * @param json JSON String containing the METADATA object to SUBMIT
 * @param file (optional) a FILE associated with this METADATA
 * @param fileInfo (optional) the FILE disposition information, if any
 * @param container (optional) a CONTAINER IMAGE associated with this METADATA
 * @param containerInfo (optional) the CONTAINER IMAGE disposition information, if any
 * @return an appropriate Response object to the caller
 */
private Response doSubmit(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());
        }

        // lookup Announced Snapshot status
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus", MetadataSnapshot.class)
                .setParameter("codeId", currentCodeId).setParameter("status", DOECodeMetadata.Status.Announced);

        List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
        if (results.size() > 0) {
            log.error("Cannot Submit, Previously Announced: " + currentCodeId);
            return ErrorResponse.internalServerError(
                    "This record was previously Announced to E-Link, if you need to update the metadata, please change your endpoint to \"/announce.\"")
                    .build();
        }

        em.getTransaction().begin();

        performDataNormalization(md);

        // set the ownership and workflow status
        md.setOwner(user.getEmail());
        md.setWorkflowStatus(Status.Submitted);
        md.setSiteOwnershipCode(user.getSiteId());

        // store it
        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 for Submitted workflow
        List<String> errors = validateSubmit(md);
        if (!errors.isEmpty()) {
            // generate a JSONAPI errors object
            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 to DataCite if needed (and there is a RELEASE DATE set)
        if (null != md.getDoi() && null != md.getReleaseDate()) {
            try {
                DataCite.register(md);
            } catch (IOException e) {
                // tell why the DataCite registration failed
                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
        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);

        // commit it
        em.getTransaction().commit();

        // send NOTIFICATION if configured to do so
        sendStatusNotification(md);

        // we are done here
        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: Unable to update record, invalid owner: " + user.getEmail());
        log.warn("Message: " + e.getMessage());
        return ErrorResponse.forbidden("Logged in User is not allowed to modify this 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 Submitting: " + e.getMessage());
        return ErrorResponse.internalServerError("Persistence error submitting record.").build();
    } finally {
        em.close();
    }
}