Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

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

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:org.apache.juddi.validation.ValidatePublish.java

/**
 * Publishing API functions are specific to jUDDI. Requires administrative privilege
 * @param em/*from  w w  w .  j  a  v  a 2 s.  c o m*/
 * @param body
 * @throws DispositionReportFaultMessage 
 */
public void validateDeletePublisher(EntityManager em, DeletePublisher body)
        throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }

    // No null or empty list
    List<String> entityKeyList = body.getPublisherId();
    if (entityKeyList == null || entityKeyList.size() == 0) {
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys"));
    }

    if (!((Publisher) publisher).isAdmin()) {
        throw new UserMismatchException(new ErrorMessage("errors.deletepublisher.AdminReqd"));
    }

    HashSet<String> dupCheck = new HashSet<String>();
    for (String entityKey : entityKeyList) {
        validateKeyLength(entityKey);
        boolean inserted = dupCheck.add(entityKey);
        if (!inserted) {
            throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey));
        }

        Object obj = em.find(org.apache.juddi.model.Publisher.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.PublisherNotFound", entityKey));
        }

    }
}

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  .  ja v a 2 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.//from  w  w w  .ja v  a  2 s  . c  om
 *
 * @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:org.apache.juddi.validation.ValidatePublish.java

public void validateDeleteBinding(EntityManager em, DeleteBinding body) throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }//  w w  w .ja  va2 s . c  om

    // No null or empty list
    List<String> entityKeyList = body.getBindingKey();
    if (entityKeyList == null || entityKeyList.size() == 0) {
        throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.NoKeys"));
    }

    // Checking for duplicates and existence
    HashSet<String> dupCheck = new HashSet<String>();
    int i = 0;
    for (String entityKey : entityKeyList) {
        validateKeyLength(entityKey);
        // Per section 4.4: keys must be case-folded
        entityKey = entityKey.toLowerCase();
        entityKeyList.set(i, entityKey);

        boolean inserted = dupCheck.add(entityKey);
        if (!inserted) {
            throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.DuplicateKey", entityKey));
        }

        Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", entityKey));
        }

        AccessCheck(obj, entityKey);

        i++;
    }
}

From source file:org.sigmah.server.dao.impl.FileHibernateDAO.java

/**
 * Saves a new file./*from  w ww .  j a  va  2  s.  com*/
 * 
 * @param properties
 *          The properties map of the uploaded file (see {@link FileUploadUtils}).
 * @param physicalName
 *          The uploaded file content.
 * @param size
 *          Size of the uploaded file.
 * @param authorId
 *          The author id.
 * @return The id of the just saved file.
 * @throws IOException
 */
@Transactional
protected Integer saveNewFile(Map<String, String> properties, String physicalName, int size, int authorId)
        throws IOException {

    final EntityManager em = em();

    LOGGER.debug("[saveNewFile] New file.");

    // --------------------------------------------------------------------
    // STEP 1 : saves the file.
    // --------------------------------------------------------------------
    LOGGER.debug("[saveNewFile] Saves the new file.");
    final File file = new File();

    // Gets the details of the name of the file.
    final String fullName = ValueResultUtils.normalizeFileName(properties.get(FileUploadUtils.DOCUMENT_NAME));
    final int index = fullName.indexOf('.');

    final String name = index > 0 ? fullName.substring(0, index) : fullName;
    final String extension = index > 0 && index < fullName.length() ? fullName.substring(index + 1) : null;

    file.setName(name);

    // Creates and adds the new version.
    file.addVersion(createVersion(1, name, extension, authorId, physicalName, size));

    em.persist(file);

    // --------------------------------------------------------------------
    // STEP 2 : gets the current value for this list of files.
    // --------------------------------------------------------------------

    // Element id.
    final int elementId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_FLEXIBLE_ELEMENT), 0);

    // Project id.
    final int projectId = ClientUtils.asInt(properties.get(FileUploadUtils.DOCUMENT_PROJECT), 0);

    // Retrieving the current value
    final TypedQuery<Value> query = em.createQuery(
            "SELECT v FROM Value v WHERE v.containerId = :projectId and v.element.id = :elementId",
            Value.class);
    query.setParameter("projectId", projectId);
    query.setParameter("elementId", elementId);

    Value currentValue = null;

    try {
        currentValue = query.getSingleResult();
    } catch (NoResultException nre) {
        // No current value
    }

    // --------------------------------------------------------------------
    // STEP 3 : creates or updates the value with the new file id.
    // --------------------------------------------------------------------

    // The value already exists, must update it.
    if (currentValue != null) {
        currentValue.setLastModificationAction('U');

        // Sets the value (adds a new file id).
        currentValue.setValue(currentValue.getValue() + ValueResultUtils.DEFAULT_VALUE_SEPARATOR
                + String.valueOf(file.getId()));
    }
    // The value for this list of files doesn't exist already, must
    // create it.
    else {
        currentValue = new Value();

        // Creation of the value
        currentValue.setLastModificationAction('C');

        // Parent element
        final FlexibleElement element = em.find(FlexibleElement.class, elementId);
        currentValue.setElement(element);

        // Container
        currentValue.setContainerId(projectId);

        // Sets the value (one file id).
        currentValue.setValue(String.valueOf(file.getId()));
    }

    // Modifier
    final User user = em.find(User.class, authorId);
    currentValue.setLastModificationUser(user);

    // Last update date
    currentValue.setLastModificationDate(new Date());

    // Saves or updates the new value.
    em.merge(currentValue);

    return file.getId();
}

From source file:io.apiman.manager.api.jpa.JpaStorage.java

/**
 * Returns a list of all contracts for the given client.
 * @param organizationId/*  w  w w . j  a v  a 2 s .c om*/
 * @param clientId
 * @param version
 * @throws StorageException
 */
protected List<ContractSummaryBean> getClientContractsInternal(String organizationId, String clientId,
        String version) throws StorageException {
    List<ContractSummaryBean> rval = new ArrayList<>();
    EntityManager entityManager = getActiveEntityManager();
    String jpql = "SELECT c from ContractBean c " + "  JOIN c.client clientv " + "  JOIN clientv.client client "
            + "  JOIN client.organization aorg" + " WHERE client.id = :clientId " + "   AND aorg.id = :orgId "
            + "   AND clientv.version = :version " + " ORDER BY aorg.id, client.id ASC";
    Query query = entityManager.createQuery(jpql);
    query.setParameter("orgId", organizationId); //$NON-NLS-1$
    query.setParameter("clientId", clientId); //$NON-NLS-1$
    query.setParameter("version", version); //$NON-NLS-1$
    List<ContractBean> contracts = query.getResultList();
    for (ContractBean contractBean : contracts) {
        ClientBean client = contractBean.getClient().getClient();
        ApiBean api = contractBean.getApi().getApi();
        PlanBean plan = contractBean.getPlan().getPlan();

        OrganizationBean clientOrg = entityManager.find(OrganizationBean.class,
                client.getOrganization().getId());
        OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());

        ContractSummaryBean csb = new ContractSummaryBean();
        csb.setClientId(client.getId());
        csb.setClientOrganizationId(client.getOrganization().getId());
        csb.setClientOrganizationName(clientOrg.getName());
        csb.setClientName(client.getName());
        csb.setClientVersion(contractBean.getClient().getVersion());
        csb.setContractId(contractBean.getId());
        csb.setCreatedOn(contractBean.getCreatedOn());
        csb.setPlanId(plan.getId());
        csb.setPlanName(plan.getName());
        csb.setPlanVersion(contractBean.getPlan().getVersion());
        csb.setApiDescription(api.getDescription());
        csb.setApiId(api.getId());
        csb.setApiName(api.getName());
        csb.setApiOrganizationId(apiOrg.getId());
        csb.setApiOrganizationName(apiOrg.getName());
        csb.setApiVersion(contractBean.getApi().getVersion());

        rval.add(csb);
    }
    return rval;
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected void initSiteProfiles(AdminMaintActionForm form, Site site) throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();

    Vector<LabelValueBean> vector = new Vector<LabelValueBean>();
    Long siteProfileClassDefaultId = null;
    SiteProfileClass siteProfileClassDefault = site.getSiteProfileClassDefault();
    if (siteProfileClassDefault != null) {
        siteProfileClassDefaultId = siteProfileClassDefault.getSiteProfileClassId();
        form.setSiteProfileClassDefaultId(siteProfileClassDefaultId);
        vector.add(new LabelValueBean(siteProfileClassDefault.getSiteProfileClassName(),
                siteProfileClassDefault.getSiteProfileClassId().toString()));
    }//from www  .  j  a va2s  .  c  o  m

    String sql = "from   SiteProfileClass siteProfileClass " + "where  siteProfileClass.site.siteId = :siteId "
            + "order  by siteProfileClassName ";
    Query query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    Iterator<?> iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfileClass siteProfileClass = (SiteProfileClass) iterator.next();
        if (siteProfileClassDefault != null) {
            if (siteProfileClass.getSiteProfileClassId().equals(siteProfileClassDefaultId)) {
                continue;
            }
        }
        vector.add(new LabelValueBean(siteProfileClass.getSiteProfileClassName(),
                siteProfileClass.getSiteProfileClassId().toString()));
    }
    LabelValueBean siteProfileClassBeans[] = new LabelValueBean[vector.size()];
    vector.copyInto(siteProfileClassBeans);
    form.setSiteProfileClassBeans(siteProfileClassBeans);

    if (form.getSiteProfileClassId() != null) {
        boolean found = false;
        for (LabelValueBean bean : siteProfileClassBeans) {
            if (bean.getValue().equals(form.getSiteProfileClassId().toString())) {
                found = true;
                break;
            }
        }
        if (!found) {
            form.setSiteProfileClassId(null);
        }
    }

    if (form.getSiteProfileClassId() == null) {
        if (siteProfileClassDefault != null) {
            form.setSiteProfileClassId(siteProfileClassDefaultId);
        }
        form.setSiteProfileClassDefault(true);
    } else {
        if (siteProfileClassDefault == null || form.getSiteProfileClassId().equals(siteProfileClassDefaultId)) {
            form.setSiteProfileClassDefault(true);
        } else {
            form.setSiteProfileClassDefault(false);
        }
        form.setTranslationEnable(false);
        String fromLocale = "";
        String toLocale = "";
        fromLocale = siteProfileClassDefault.getLanguage().getGoogleTranslateLocale();
        SiteProfileClass siteProfileClass = (SiteProfileClass) em.find(SiteProfileClass.class,
                form.getSiteProfileClassId());
        toLocale = siteProfileClass.getLanguage().getGoogleTranslateLocale();
        if (!Format.isNullOrEmpty(fromLocale) && !Format.isNullOrEmpty(toLocale)
                && !fromLocale.equals(toLocale)) {
            form.setTranslationEnable(true);
            form.setFromLocale(fromLocale);
            form.setToLocale(toLocale);
        }
    }

    vector = new Vector<LabelValueBean>();
    Long siteCurrencyClassDefaultId = null;
    SiteCurrencyClass siteCurrencyClassDefault = site.getSiteCurrencyClassDefault();
    if (siteCurrencyClassDefault != null) {
        siteCurrencyClassDefaultId = siteCurrencyClassDefault.getSiteCurrencyClassId();
        form.setSiteCurrencyClassDefaultId(siteCurrencyClassDefaultId);
        vector.add(new LabelValueBean(siteCurrencyClassDefault.getSiteCurrencyClassName(),
                siteCurrencyClassDefault.getSiteCurrencyClassId().toString()));
    }

    sql = "from   SiteCurrencyClass siteCurrencyClass " + "where  siteCurrencyClass.site.siteId = :siteId "
            + "order  by siteCurrencyClassName ";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrencyClass siteCurrencyClass = (SiteCurrencyClass) iterator.next();
        if (siteProfileClassDefault != null) {
            if (siteCurrencyClass.getSiteCurrencyClassId().equals(siteCurrencyClassDefaultId)) {
                continue;
            }
        }
        vector.add(new LabelValueBean(siteCurrencyClass.getSiteCurrencyClassName(),
                siteCurrencyClass.getSiteCurrencyClassId().toString()));
    }
    LabelValueBean siteCurrencyClassBeans[] = new LabelValueBean[vector.size()];
    vector.copyInto(siteCurrencyClassBeans);
    form.setSiteCurrencyClassBeans(siteCurrencyClassBeans);

    if (form.getSiteCurrencyClassId() == null) {
        if (siteCurrencyClassDefault != null) {
            form.setSiteCurrencyClassId(siteCurrencyClassDefaultId);
        }
        form.setSiteCurrencyClassDefault(true);
    } else {
        if (siteCurrencyClassDefault == null
                || form.getSiteCurrencyClassId().equals(siteCurrencyClassDefaultId)) {
            form.setSiteCurrencyClassDefault(true);
        } else {
            form.setSiteCurrencyClassDefault(false);
        }
    }
}

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

@Override
public Filter getFilter(Long id) throws PersistenceException {
    Filter f = null;/*from w w w  . java 2 s .co m*/
    EntityManager em = null;
    try {
        em = getEntityManager();
        f = em.find(Filter.class, id);
        if (f != null && f.getValues() != null && !f.getValues().isEmpty()) {
            List<FilterValue> l = new ArrayList<FilterValue>(f.getValues().size());
            for (FilterValue fv : f.getValues())
                l.add(fv);
            f.setValues(l);
        }
        return f;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in getFilter " + e.getMessage(), e);
        throw new PersistenceException("Exception in getFilter " + e.getMessage(), e);
    } finally {
        closeEntityManager(em);
    }
}

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

public void removeFilter(Long id) throws PersistenceException {
    TransactionContext tc = null;/*from  w  w  w .ja v a  2s  .  c  o  m*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        Filter f = em.find(Filter.class, id);
        List<FilterValue> values = f.getValues();
        if (values != null && !values.isEmpty()) {
            for (FilterValue fv : values) {
                em.remove(fv);
            }
        }
        values.clear();
        em.remove(f);
        tx.begin();
        tx.commit();
    } catch (Exception e) {
        catchPersistException(tc, e);
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }
}

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

/**
 * Perform SAVE workflow on indicated METADATA.
 *
 * @param json the JSON String containing the metadata to SAVE
 * @param file a FILE associated with this record if any
 * @param fileInfo the FILE disposition information if any
 * @param container a CONTAINER IMAGE associated with this record if any
 * @param containerInfo the CONTAINER IMAGE disposition of information if any
 * @return a Response containing the JSON of the saved record if successful,
 * or error information if not//  w ww  . j  a v  a2  s  .c om
 */
private Response doSave(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));

        em.getTransaction().begin();

        performDataNormalization(md);

        md.setWorkflowStatus(Status.Saved); // default to this
        md.setOwner(user.getEmail()); // this User should OWN it
        md.setSiteOwnershipCode(user.getSiteId());

        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
        if (null != file && null != fileInfo) {
            try {
                String fileName = writeFile(file, md.getCodeId(), fileInfo.getFileName(), FILE_UPLOADS);
                md.setFileName(fileName);
            } 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
        if (null != container && null != containerInfo) {
            try {
                String containerName = writeFile(container, md.getCodeId(), containerInfo.getFileName(),
                        CONTAINER_UPLOADS);
                md.setContainerName(containerName);
            } catch (IOException e) {
                log.error("Container Image Upload Failed: " + e.getMessage());
                return ErrorResponse.internalServerError("Container Image upload failed.").build();
            }
        }

        // we're done here
        em.getTransaction().commit();

        return Response.status(200)
                .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 update attempt from " + user.getEmail());
        log.warn("Message: " + e.getMessage());
        return ErrorResponse.forbidden("Unable to persist update for 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("Save IO Error: " + e.getMessage()).build();
    } finally {
        em.close();
    }
}