Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

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

Prototype

public <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);

Source Link

Document

Create an instance of TypedQuery for executing a Java Persistence query language named query.

Usage

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Deletes AlertCurrent records in relation with AlertHistory entries older than the given date.
 *
 * @param clusterId        the identifier of the cluster the AlertCurrents belong to
 * @param beforeDateMillis the date in milliseconds the
 * @return a long representing the number of affected (deleted) records
 *///from www  .j a  v  a  2  s  .  c o m
@Transactional
private int cleanAlertCurrentsForClusterBeforeDate(long clusterId, long beforeDateMillis) {
    LOG.info("Deleting AlertCurrent entities before date " + new Date(beforeDateMillis));
    EntityManager entityManager = m_entityManagerProvider.get();
    List<Integer> ids = findAllAlertHistoryIdsBeforeDate(clusterId, beforeDateMillis);
    int affectedRows = 0;
    TypedQuery<AlertCurrentEntity> currentQuery = entityManager
            .createNamedQuery("AlertCurrentEntity.removeByHistoryIds", AlertCurrentEntity.class);
    if (ids != null && !ids.isEmpty()) {
        for (int i = 0; i < ids.size(); i += BATCH_SIZE) {
            int endIndex = (i + BATCH_SIZE) > ids.size() ? ids.size() : (i + BATCH_SIZE);
            List<Integer> idsSubList = ids.subList(i, endIndex);
            LOG.info("Deleting AlertCurrent entity batch with history ids: " + idsSubList.get(0) + " - "
                    + idsSubList.get(idsSubList.size() - 1));
            currentQuery.setParameter("historyIds", ids.subList(i, endIndex));
            affectedRows += currentQuery.executeUpdate();
        }
    }

    return affectedRows;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Deletes AlertNotice records in relation with AlertHistory entries older than the given date.
 *
 * @param clusterId        the identifier of the cluster the AlertNotices belong to
 * @param beforeDateMillis the date in milliseconds the
 * @return a long representing the number of affected (deleted) records
 *///  www . j  a  v  a 2 s .  co m
@Transactional
private int cleanAlertNoticesForClusterBeforeDate(Long clusterId, long beforeDateMillis) {
    LOG.info("Deleting AlertNotice entities before date " + new Date(beforeDateMillis));
    EntityManager entityManager = m_entityManagerProvider.get();
    List<Integer> ids = findAllAlertHistoryIdsBeforeDate(clusterId, beforeDateMillis);
    int affectedRows = 0;
    // Batch delete
    TypedQuery<AlertNoticeEntity> noticeQuery = entityManager
            .createNamedQuery("AlertNoticeEntity.removeByHistoryIds", AlertNoticeEntity.class);
    if (ids != null && !ids.isEmpty()) {
        for (int i = 0; i < ids.size(); i += BATCH_SIZE) {
            int endIndex = (i + BATCH_SIZE) > ids.size() ? ids.size() : (i + BATCH_SIZE);
            List<Integer> idsSubList = ids.subList(i, endIndex);
            LOG.info("Deleting AlertNotice entity batch with history ids: " + idsSubList.get(0) + " - "
                    + idsSubList.get(idsSubList.size() - 1));
            noticeQuery.setParameter("historyIds", idsSubList);
            affectedRows += noticeQuery.executeUpdate();
        }
    }

    return affectedRows;
}

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

/**
 * Send an email notification on APPROVAL of DOE CODE records.
 *
 * @param md the METADATA to send notification for
 *//*from   w ww  .j a v  a  2 s  .c om*/
private static void sendApprovalNotification(DOECodeMetadata md) {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
    email.setHostName(EMAIL_HOST);

    // if HOST or record OWNER or PROJECT MANAGER NAME isn't set, cannot send
    if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(md.getOwner())
            || StringUtils.isEmpty(PM_NAME))
        return;
    // only has meaning for APPROVED records
    if (!Status.Approved.equals(md.getWorkflowStatus()))
        return;

    try {
        // get the OWNER information
        User owner = UserServices.findUserByEmail(md.getOwner());
        if (null == owner) {
            log.warn("Unable to locate USER information for Code ID: " + md.getCodeId());
            return;
        }

        Long codeId = md.getCodeId();

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

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

        String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

        email.setFrom(EMAIL_FROM);
        email.setSubject("Approved -- DOE CODE ID: " + codeId + ", " + softwareTitle);
        email.addTo(md.getOwner());

        // if email is provided, BCC the Project Manager
        if (!StringUtils.isEmpty(PM_EMAIL))
            email.addBcc(PM_EMAIL, PM_NAME);

        StringBuilder msg = new StringBuilder();

        msg.append("<html>");
        msg.append("Dear ").append(owner.getFirstName()).append(" ").append(owner.getLastName()).append(":");

        msg.append("<P>Thank you -- your ").append(lastApprovalFor).append(" project, DOE CODE ID: <a href=\"")
                .append(SITE_URL).append("/biblio/").append(codeId).append("\">").append(codeId)
                .append("</a>, has been approved.  It is now <a href=\"").append(SITE_URL)
                .append("\">searchable</a> in DOE CODE by, for example, title or CODE ID #.</P>");

        // OMIT the following for BUSINESS TYPE software, or last ANNOUNCED software
        if (!DOECodeMetadata.Type.B.equals(md.getSoftwareType())
                && !lastApprovalFor.equalsIgnoreCase("announced")) {
            msg.append(
                    "<P>You may need to continue editing your project to announce it to the Department of Energy ")
                    .append("to ensure announcement and dissemination in accordance with DOE statutory responsibilities. For more information please see ")
                    .append("<a href=\"").append(SITE_URL)
                    .append("/faq#what-does-it-mean-to-announce\">What does it mean to announce scientific code to DOE CODE?</a></P>");
        }
        msg.append(
                "<P>If you have questions such as What are the benefits of getting a DOI for code or software?, see the ")
                .append("<a href=\"").append(SITE_URL).append("/faq\">DOE CODE FAQs</a>.</P>");
        msg.append(
                "<P>If we can be of assistance, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</P>");
        msg.append("<P>Sincerely,</P>");
        msg.append("<P>").append(PM_NAME).append("<BR/>Product Manager for DOE CODE<BR/>USDOE/OSTI</P>");

        msg.append("</html>");

        email.setHtmlMsg(msg.toString());

        email.send();
    } catch (EmailException e) {
        log.error("Unable to send APPROVAL notification for #" + md.getCodeId());
        log.error("Message: " + e.getMessage());
    }
}

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

/**
 * Send a POC email notification on SUBMISSION/APPROVAL of DOE CODE records.
 *
 * @param md the METADATA to send notification for
 *//*from w w  w  . ja  v  a  2s .c  om*/
private static void sendPOCNotification(DOECodeMetadata md) {
    // if HOST or MD or PROJECT MANAGER NAME isn't set, cannot send
    if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(PM_NAME))
        return;

    Long codeId = md.getCodeId();
    String siteCode = md.getSiteOwnershipCode();
    Status workflowStatus = md.getWorkflowStatus();

    // if SITE OWNERSHIP isn't set, cannot send
    if (StringUtils.isEmpty(siteCode))
        return;

    // only applicable to APPROVED records
    if (!Status.Approved.equals(workflowStatus))
        return;

    // get the SITE information
    Site site = SiteServices.findSiteBySiteCode(siteCode);
    if (null == site) {
        log.warn("Unable to locate SITE information for SITE CODE: " + siteCode);
        return;
    }

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

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

    List<String> emails = site.getPocEmails();

    // if POC is setup
    if (emails != null && !emails.isEmpty()) {
        try {
            HtmlEmail email = new HtmlEmail();
            email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
            email.setHostName(EMAIL_HOST);

            String lab = site.getLab();
            lab = lab.isEmpty() ? siteCode : lab;

            String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

            email.setFrom(EMAIL_FROM);
            email.setSubject("POC Notification -- " + workflowStatus + " -- DOE CODE ID: " + codeId + ", "
                    + softwareTitle);

            for (String pocEmail : emails)
                email.addTo(pocEmail);

            // if email is provided, BCC the Project Manager
            if (!StringUtils.isEmpty(PM_EMAIL))
                email.addBcc(PM_EMAIL, PM_NAME);

            StringBuilder msg = new StringBuilder();

            msg.append("<html>");
            msg.append("Dear Sir or Madam:");

            String biblioLink = SITE_URL + "/biblio/" + codeId;

            msg.append("<p>As a point of contact for ").append(lab)
                    .append(", we wanted to inform you that a software project, titled ").append(softwareTitle)
                    .append(", associated with your organization was ").append(lastApprovalFor)
                    .append(" to DOE CODE and assigned DOE CODE ID: ").append(codeId)
                    .append(".  This project record is discoverable in <a href=\"").append(SITE_URL)
                    .append("\">DOE CODE</a>, e.g. searching by the project title or DOE CODE ID #, and can be found here: <a href=\"")
                    .append(biblioLink).append("\">").append(biblioLink).append("</a></p>");

            msg.append(
                    "<p>If you have any questions, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</p>");
            msg.append("<p>Sincerely,</p>");
            msg.append("<p>").append(PM_NAME).append("<br/>Product Manager for DOE CODE<br/>USDOE/OSTI</p>");

            msg.append("</html>");

            email.setHtmlMsg(msg.toString());

            email.send();
        } catch (EmailException e) {
            log.error("Unable to send POC notification to " + Arrays.toString(emails.toArray()) + " for #"
                    + md.getCodeId());
            log.error("Message: " + e.getMessage());
        }
    }
}

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

/**
 * Remove non-indexable New/Previous RI from metadata.
 *
 * @param em the EntityManager to control commits.
 * @param md the Metadata to evaluate./*from  w  w w  . j a  v a  2s. c om*/
 * @return Updated DOECodeMetadata object.
 */
private static DOECodeMetadata removeNonIndexableRi(EntityManager em, DOECodeMetadata md) throws IOException {
    // need a detached copy of the RI data
    DOECodeMetadata alteredMd = new DOECodeMetadata();
    BeanUtilsBean bean = new BeanUtilsBean();

    try {
        bean.copyProperties(alteredMd, md);
    } catch (IllegalAccessException | InvocationTargetException ex) {
        // log issue, swallow error
        String msg = "NonIndexable RI Removal Bean Error: " + ex.getMessage();
        throw new IOException(msg);
    }

    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByDoiAndStatus", MetadataSnapshot.class)
            .setParameter("status", DOECodeMetadata.Status.Approved);

    // get detached list of RI to check
    List<RelatedIdentifier> riList = new ArrayList<>();
    riList.addAll(alteredMd.getRelatedIdentifiers());

    // filter to targeted RI
    List<RelatedIdentifier> filteredRiList = riList.stream()
            .filter(p -> p.getIdentifierType() == RelatedIdentifier.Type.DOI
                    && (p.getRelationType() == RelatedIdentifier.RelationType.IsNewVersionOf
                            || p.getRelationType() == RelatedIdentifier.RelationType.IsPreviousVersionOf))
            .collect(Collectors.toList());

    // track removals
    List<RelatedIdentifier> removalList = new ArrayList<>();

    for (RelatedIdentifier ri : filteredRiList) {
        // lookup by Snapshot by current DOI
        querySnapshot.setParameter("doi", ri.getIdentifierValue());

        List<MetadataSnapshot> results = querySnapshot.getResultList();

        // if no results, keep, otherwise remove unless there is a minted version found
        boolean remove = !results.isEmpty();
        for (MetadataSnapshot ms : results) {
            if (ms.getDoiIsMinted()) {
                remove = false;
                break;
            }
        }

        if (remove)
            removalList.add(ri);
    }

    // perform removals, as needed, and update
    if (!removalList.isEmpty()) {
        riList.removeAll(removalList);
        alteredMd.setRelatedIdentifiers(riList);
    }

    return alteredMd;
}

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

@GET
@Produces(MediaType.APPLICATION_JSON)/*from  www  .j  a v  a 2  s  . com*/
@Path("/reindex")
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response reindex() throws IOException {
    EntityManager em = DoeServletContextListener.createEntityManager();

    try {
        TypedQuery<MetadataSnapshot> query = em
                .createNamedQuery("MetadataSnapshot.findAllByStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved);
        List<MetadataSnapshot> results = query.getResultList();
        int records = 0;

        for (MetadataSnapshot amd : results) {
            DOECodeMetadata md = DOECodeMetadata.parseJson(new StringReader(amd.getJson()));

            sendToIndex(em, md);
            ++records;
        }

        return Response.ok()
                .entity(mapper.createObjectNode().put("indexed", String.valueOf(records)).toString()).build();
    } finally {
        em.close();
    }
}

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

/**
 * Get previous snapshot info for use in backfill process that occurs after current snapshot is updated.
 *
 * @param em the EntityManager to control commits.
 * @param md the Metadata to evaluate for RI backfilling.
 * @return List of RelatedIdentifier objects.
 */// w w  w. jav  a2  s. c om
private List<RelatedIdentifier> getPreviousRiList(EntityManager em, DOECodeMetadata md) throws IOException {
    // if current project has no DOI, there is nothing to process later on, so do not pull previous info
    if (StringUtils.isBlank(md.getDoi()))
        return null;

    long codeId = md.getCodeId();

    // pull last know Approved info
    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus", MetadataSnapshot.class)
            .setParameter("codeId", codeId).setParameter("status", DOECodeMetadata.Status.Approved);

    List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();

    // get previous Approved RI list, if applicable
    List<RelatedIdentifier> previousList = new ArrayList<>();
    for (MetadataSnapshot ms : results) {
        try {
            DOECodeMetadata pmd = DOECodeMetadata.parseJson(new StringReader(ms.getJson()));

            previousList = pmd.getRelatedIdentifiers();

            if (previousList == null)
                previousList = new ArrayList<>();

            // filter to targeted RI
            previousList = previousList.stream().filter(p -> p.getIdentifierType() == RelatedIdentifier.Type.DOI
                    && (p.getRelationType() == RelatedIdentifier.RelationType.IsNewVersionOf
                            || p.getRelationType() == RelatedIdentifier.RelationType.IsPreviousVersionOf))
                    .collect(Collectors.toList());

        } catch (IOException ex) {
            // unable to parse JSON, but for this process
            String msg = "Unable to parse previously 'Approved' Snapshot JSON for " + codeId + ": "
                    + ex.getMessage();
            throw new IOException(msg);
        }
        break; // failsafe: there should only ever be one, at most
    }

    return previousList;
}

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

/**
 * Handle SUBMIT workflow logic.//from  w  w  w .ja  v 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();
    }
}

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

/**
 * Add/Remove backfill RI information./*from   w  w  w. j  a va 2s .c  o  m*/
 * To modify source items, you must be an OSTI admin, project owner, or site admin.
 *
 * @param em the EntityManager to control commits.
 * @param md the Metadata to evaluate for RI updating.
 * @param previousList the RelatedIdentifiers from previous Approval.
 */
private void backfillProjects(EntityManager em, DOECodeMetadata md, List<RelatedIdentifier> previousList)
        throws IllegalAccessException, IOException {
    // if current project has no DOI, there is nothing to process
    if (StringUtils.isBlank(md.getDoi()))
        return;

    // get current list of RI info, for backfill additions
    List<RelatedIdentifier> additionList = md.getRelatedIdentifiers();

    if (additionList == null)
        additionList = new ArrayList<>();

    // filter additions to targeted RI
    additionList = additionList.stream()
            .filter(p -> p.getIdentifierType() == RelatedIdentifier.Type.DOI
                    && (p.getRelationType() == RelatedIdentifier.RelationType.IsNewVersionOf
                            || p.getRelationType() == RelatedIdentifier.RelationType.IsPreviousVersionOf))
            .collect(Collectors.toList());

    if (previousList == null)
        previousList = new ArrayList<>();

    // previous relations no longer defined must be removed
    previousList.removeAll(additionList);

    // store details about what will need sent to OSTI and re-indexed
    Map<Long, DOECodeMetadata> backfillSendToIndex = new HashMap<>();
    Map<Long, DOECodeMetadata> backfillSendToOsti = new HashMap<>();

    // define needed queries
    TypedQuery<DOECodeMetadata> deleteQuery = em.createNamedQuery("DOECodeMetadata.findByDoiAndRi",
            DOECodeMetadata.class);
    TypedQuery<DOECodeMetadata> addQuery = em.createNamedQuery("DOECodeMetadata.findByDoi",
            DOECodeMetadata.class);
    TypedQuery<MetadataSnapshot> snapshotQuery = em.createNamedQuery("MetadataSnapshot.findByCodeIdAndStatus",
            MetadataSnapshot.class);
    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
            .setParameter("status", DOECodeMetadata.Status.Approved);

    List<RelatedIdentifier> backfillSourceList;

    // for each BackfillType, perform actions:  delete obsolete previous info / add new info
    for (RelatedIdentifier.BackfillType backfillType : RelatedIdentifier.BackfillType.values()) {
        // previous relations no longer defined must be removed, current relations need to be added
        backfillSourceList = backfillType == RelatedIdentifier.BackfillType.Deletion ? previousList
                : additionList;

        // if there is no list to process, skip
        if (backfillSourceList == null || backfillSourceList.isEmpty())
            continue;

        for (RelatedIdentifier ri : backfillSourceList) {
            // get inverse relation
            RelatedIdentifier inverseRelation = new RelatedIdentifier(ri);
            inverseRelation.setRelationType(ri.getRelationType().inverse());
            inverseRelation.setIdentifierValue(md.getDoi());
            inverseRelation.setSource(RelatedIdentifier.Source.AutoBackfill);

            List<RelatedIdentifier> targetedList = Arrays.asList(inverseRelation);

            List<DOECodeMetadata> results = new ArrayList<>();
            List<MetadataSnapshot> snapshotResults;

            if (backfillType == RelatedIdentifier.BackfillType.Deletion) {
                // check for the existance of the inverse relation
                deleteQuery.setParameter("doi", ri.getIdentifierValue())
                        .setParameter("type", inverseRelation.getIdentifierType())
                        .setParameter("value", inverseRelation.getIdentifierValue())
                        .setParameter("relType", inverseRelation.getRelationType());

                results = deleteQuery.getResultList();
            } else if (backfillType == RelatedIdentifier.BackfillType.Addition) {
                // lookup target DOI
                addQuery.setParameter("doi", ri.getIdentifierValue());

                results = addQuery.getResultList();
            }

            // update RI where needed
            for (DOECodeMetadata bmd : results) {
                // target CODE ID and Workflow Status
                Long codeId = bmd.getCodeId();
                DOECodeMetadata.Status status = bmd.getWorkflowStatus();

                List<RelatedIdentifier> updateList = bmd.getRelatedIdentifiers();

                if (updateList == null)
                    updateList = new ArrayList<>();

                // get User data
                List<RelatedIdentifier> userRIList = getSourceRi(updateList, RelatedIdentifier.Source.User);

                // update metadata RI info
                updateList.removeAll(targetedList); // always remove match
                if (backfillType == RelatedIdentifier.BackfillType.Addition)
                    updateList.addAll(targetedList); // add back, if needed

                // restore any modified User data
                updateList.removeAll(userRIList); // always remove match
                updateList.addAll(userRIList); // add back, if needed

                // save changes
                bmd.setRelatedIdentifiers(updateList);

                // update snapshot metadata
                snapshotQuery.setParameter("codeId", codeId).setParameter("status", status);

                snapshotResults = snapshotQuery.getResultList();

                // update snapshot RI, for same status, where needed
                for (MetadataSnapshot ms : snapshotResults) {
                    try {
                        DOECodeMetadata smd = DOECodeMetadata.parseJson(new StringReader(ms.getJson()));

                        List<RelatedIdentifier> snapshotList = smd.getRelatedIdentifiers();

                        if (snapshotList == null)
                            snapshotList = new ArrayList<>();

                        // get User data
                        userRIList = getSourceRi(snapshotList, RelatedIdentifier.Source.User);

                        // update snapshot RI info, if needed
                        snapshotList.removeAll(targetedList); // always remove match
                        if (backfillType == RelatedIdentifier.BackfillType.Addition)
                            snapshotList.addAll(targetedList); // add back, if needed

                        // restore any modified User data
                        snapshotList.removeAll(userRIList); // always remove match
                        snapshotList.addAll(userRIList); // add back, if needed

                        // save changes to Snapshot
                        smd.setRelatedIdentifiers(snapshotList);
                        ms.setJson(smd.toJson().toString());

                        // log updated, Approved snapshot info for post-backfill actions
                        if (status == DOECodeMetadata.Status.Approved) {
                            // log for re-indexing
                            backfillSendToIndex.put(codeId, smd);

                            // lookup snapshot status info, prior to Approval
                            querySnapshot.setParameter("codeId", codeId);

                            List<MetadataSnapshot> previousResults = querySnapshot.setMaxResults(1)
                                    .getResultList();
                            for (MetadataSnapshot pms : previousResults) {
                                DOECodeMetadata.Status lastApprovalFor = pms.getSnapshotKey()
                                        .getSnapshotStatus();

                                // if Approved for Announcement, log for OSTI
                                if (lastApprovalFor == DOECodeMetadata.Status.Announced)
                                    backfillSendToOsti.put(codeId, smd);

                                break; // failsafe, but should only be at most one item returned
                            }
                        }
                    } catch (IOException ex) {
                        // unable to parse JSON, but for this process
                        String msg = "Unable to parse '" + ms.getSnapshotKey().getSnapshotStatus()
                                + "' Snapshot JSON for " + ms.getSnapshotKey().getCodeId() + ": "
                                + ex.getMessage();
                        throw new IOException(msg);
                    }
                }
            }
        }
    }

    // update OSTI, as needed
    for (Map.Entry<Long, DOECodeMetadata> entry : backfillSendToOsti.entrySet()) {
        sendToOsti(em, entry.getValue());
    }

    // update Index, as needed
    for (Map.Entry<Long, DOECodeMetadata> entry : backfillSendToIndex.entrySet()) {
        sendToIndex(em, entry.getValue());
    }
}

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//w  ww.  j  a v  a  2 s  .  com
 */
@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();
    }
}