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: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./*w ww . j a  va2s.  co  m*/
 *
 * @param codeId the CODE ID of the record to APPROVE.
 * @return a Response containing the JSON of the approved record if successful, or
 * error information if not
 * @throws InternalServerErrorException on JSON parsing or other IO errors
 */
@GET
@Path("/approve/{codeId}")
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
@RequiresRoles("OSTI")
public Response approve(@PathParam("codeId") Long codeId) {
    EntityManager em = DoeServletContextListener.createEntityManager();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

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

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

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

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

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

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

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

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

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

        em.merge(snapshot);

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

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

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

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

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

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

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

private void validateAccessPoint(EntityManager em, AccessPoint value, Configuration config)
        throws ValueNotAllowedException {
    if (log.isDebugEnabled()) {
        log.debug("validateAccessPoint");
    }/*w ww. j  a va  2s.  c  o  m*/

    if (value != null) {
        if (value.getValue().length() > ValidationConstants.MAX_accessPoint) {
            throw new ValueNotAllowedException(new ErrorMessage("errors.accessPoint.TooLong"));
        }

        validateUseType(value.getUseType());
        if (value.getUseType() != null) {
            if (value.getUseType().equalsIgnoreCase(AccessPointType.BINDING_TEMPLATE.toString())) {
                //validate that the referenced binding key exists already
                Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, value.getValue());
                if (obj == null) {
                    throw new ValueNotAllowedException(
                            new ErrorMessage("errors.accessPoint.bindingtemplateRedirect.keynotexist"));
                }

            } else if (value.getUseType().equalsIgnoreCase(AccessPointType.HOSTING_REDIRECTOR.toString())) {
                try {
                    //no validation necessary other than confirm that it's a URL
                    new URL(value.getValue());
                } catch (MalformedURLException ex) {
                    throw new ValueNotAllowedException(
                            new ErrorMessage("errors.accessPoint.hostingRedirector.notaurl"));
                }
            }
            //TODO determine if additional validation is required.
            //potentials, if its a wsdl deployment, is the Value a valid URI
            //if endpoint, is it a valid URI?
        }
    }
}

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

/**
 * Look up a record for EDITING, checks authentication and ownership prior
 * to succeeding./*from  w ww  .  ja v a2s  .com*/
 *
 * Ownership is defined as:  owner and user email match, OR user's roles
 * include the SITE OWNERSHIP CODE of the record, OR user has the "OSTI"
 * special administrative role.
 * Result Codes:
 * 200 - OK, with JSON containing the metadata information
 * 400 - you didn't specify a CODE ID
 * 401 - authentication required
 * 403 - forbidden, logged in user does not have permission to this metadata
 * 404 - requested metadata is not on file
 *
 * @param codeId the CODE ID to look up
 * @param format optional; "yaml" or "xml", default is JSON unless specified
 * @return a Response containing JSON if successful
 */
@GET
@Path("{codeId}")
@Produces({ MediaType.APPLICATION_JSON, "text/yaml", MediaType.APPLICATION_XML })
@RequiresAuthentication
@SuppressWarnings("ConvertToStringSwitch")
public Response getSingleRecord(@PathParam("codeId") Long codeId, @QueryParam("format") String format) {
    EntityManager em = DoeServletContextListener.createEntityManager();
    Subject subject = SecurityUtils.getSubject();
    User user = (User) subject.getPrincipal();

    // no CODE ID?  Bad request.
    if (null == codeId)
        return ErrorResponse.badRequest("Missing code ID.").build();

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

    // no metadata?  404
    if (null == md)
        return ErrorResponse.notFound("Code ID not on file.").build();

    // do you have permissions to get this?
    if (!user.getEmail().equals(md.getOwner()) && !user.hasRole("OSTI")
            && !user.hasRole(md.getSiteOwnershipCode()))
        return ErrorResponse.forbidden("Permission denied.").build();

    // if YAML is requested, return that; otherwise, default to JSON
    try {
        if ("yaml".equals(format)) {
            // return the YAML (excluding filtered data)
            return Response.ok().header("Content-Type", "text/yaml")
                    .header("Content-Disposition", "attachment; filename = \"metadata.yml\"")
                    .entity(YAML_MAPPER.writer(filter).writeValueAsString(md)).build();
        } else if ("xml".equals(format)) {
            return Response.ok().header("Content-Type", MediaType.APPLICATION_XML).entity(HttpUtil.writeXml(md))
                    .build();
        } else {
            // send back the JSON
            return Response.ok().header("Content-Type", MediaType.APPLICATION_JSON)
                    .entity(mapper.createObjectNode().putPOJO("metadata", md.toJson()).toString()).build();
        }
    } catch (IOException e) {
        log.warn("JSON Output Error", e);
        return ErrorResponse.internalServerError("Unable to process request.").build();
    }
}

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

public void validateTModel(EntityManager em, org.uddi.api_v3.TModel tModel, Configuration config)
        throws DispositionReportFaultMessage {
    // A supplied tModel can't be null
    if (tModel == null) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NullInput"));
    }//w  w  w .  j  a va2s  . c  om

    boolean entityExists = false;
    String entityKey = tModel.getTModelKey();
    if (entityKey == null || entityKey.length() == 0) {
        KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator();
        entityKey = keyGen.generate();
        validateNotSigned(tModel);
        tModel.setTModelKey(entityKey);
    } else {
        // Per section 4.4: keys must be case-folded
        entityKey = entityKey.toLowerCase();
        tModel.setTModelKey(entityKey);

        Object obj = em.find(org.apache.juddi.model.Tmodel.class, entityKey);
        if (obj != null) {
            entityExists = true;

            // Make sure publisher owns this entity.
            AccessCheck(obj, entityKey);
            //if (!publisher.isOwner((UddiEntity) obj)&& !((Publisher) publisher).isAdmin()) {
            //        throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey));
            // }
        } else {
            // Inside this block, we have a key proposed by the publisher on a new entity

            // First test to see if this is a Key Generator tModel. The keyGenerator suffix appearing in the key is the indicator, since this is not
            // allowed *unless* it's a key generator.
            if (entityKey.toUpperCase().contains(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) {
                ValidateUDDIKey.validateUDDIv3KeyGeneratorTModel(tModel);

                // The root publisher is only allowed one key generator.  This is published in the installation.
                String rootPublisherStr = "root";
                try {
                    rootPublisherStr = AppConfig.getConfiguration().getString(Property.JUDDI_ROOT_PUBLISHER);
                } catch (ConfigurationException ce) {
                    log.error("Could not read the root publisher setting in the configuration.");
                }
                if (publisher.getAuthorizedName().equals(rootPublisherStr)) {
                    throw new FatalErrorException(new ErrorMessage("errors.tmodel.keygenerator.RootKeyGen"));
                }

                // It's a valid Key Generator, but is it available for this publisher?
                if (!publisher.isKeyGeneratorAvailable(em, entityKey)) {
                    throw new KeyUnavailableException(
                            new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
                }

            } else {
                // If not a key generator, then simply validate key and then check to see that the proposed key is valid for this publisher
                ValidateUDDIKey.validateUDDIv3Key(entityKey);
                //fix for JUDDI-851
                if (!entityKey.toUpperCase().startsWith("UUID:")) {
                    if (!publisher.isValidPublisherKey(em, entityKey)) {
                        throw new KeyUnavailableException(
                                new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
                    }
                }
            }
        }
    }

    if (!entityExists) {
        // Check to make sure key isn't used by another entity.
        if (!isUniqueKey(em, entityKey)) {
            throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey));
        }
    }
    validateKeyLength(entityKey);

    // TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support

    if (tModel.getName() == null || tModel.getName().getValue() == null
            || tModel.getName().getValue().equals("")) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.NoName"));
    }

    validateCategoryBag(tModel.getCategoryBag(), config, false);
    validateIdentifierBag(tModel.getIdentifierBag(), config, false);
    validateDescriptions(tModel.getDescription());
    validateNameLength(tModel.getName().getValue());
    validateLang(tModel.getName().getLang());
    List<org.uddi.api_v3.OverviewDoc> overviewDocList = tModel.getOverviewDoc();
    if (overviewDocList != null) {
        for (org.uddi.api_v3.OverviewDoc overviewDoc : overviewDocList) {
            validateOverviewDoc(overviewDoc);
        }
    }

}

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

public void validateBusinessEntity(EntityManager em, org.uddi.api_v3.BusinessEntity businessEntity,
        Configuration config) throws DispositionReportFaultMessage {

    // A supplied businessEntity can't be null
    if (businessEntity == null) {
        throw new ValueNotAllowedException(new ErrorMessage("errors.businessentity.NullInput"));
    }/*from  w  w w.  j  a  va  2s .c om*/

    boolean entityExists = false;
    validateNotSigned(businessEntity);
    String entityKey = businessEntity.getBusinessKey();
    if (entityKey == null || entityKey.length() == 0) {
        KeyGenerator keyGen = KeyGeneratorFactory.getKeyGenerator();
        entityKey = keyGen.generate();
        businessEntity.setBusinessKey(entityKey);
    } else {
        // Per section 4.4: keys must be case-folded
        entityKey = entityKey.toLowerCase();
        businessEntity.setBusinessKey(entityKey);
        validateKeyLength(entityKey);
        Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey);
        if (obj != null) {
            entityExists = true;

            // Make sure publisher owns this entity.
            AccessCheck(obj, entityKey);

        } else {
            // Inside this block, we have a key proposed by the publisher on a new entity

            // Validate key and then check to see that the proposed key is valid for this publisher
            ValidateUDDIKey.validateUDDIv3Key(entityKey);
            if (!publisher.isValidPublisherKey(em, entityKey)) {
                throw new KeyUnavailableException(
                        new ErrorMessage("errors.keyunavailable.BadPartition", entityKey));
            }

        }
    }

    if (!entityExists) {
        // Check to make sure key isn't used by another entity.
        if (!isUniqueKey(em, entityKey)) {
            throw new KeyUnavailableException(new ErrorMessage("errors.keyunavailable.KeyExists", entityKey));
        }
    }

    // was TODO: validate "checked" categories or category groups (see section 5.2.3 of spec)? optional to support
    //covered by ref integrity checks

    validateNames(businessEntity.getName());
    validateDiscoveryUrls(businessEntity.getDiscoveryURLs());
    validateContacts(businessEntity.getContacts(), config);
    validateCategoryBag(businessEntity.getCategoryBag(), config, false);
    validateIdentifierBag(businessEntity.getIdentifierBag(), config, false);
    validateDescriptions(businessEntity.getDescription());
    validateBusinessServices(em, businessEntity.getBusinessServices(), businessEntity, config);

}

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

public void validateDeletePublisherAssertions(EntityManager em, DeletePublisherAssertions body)
        throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }/*from  ww  w .  j a v a  2  s  .co m*/

    // No null or empty list
    List<org.uddi.api_v3.PublisherAssertion> entityList = body.getPublisherAssertion();
    if (entityList == null || entityList.size() == 0) {
        throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.NoPubAssertions"));
    }

    for (org.uddi.api_v3.PublisherAssertion entity : entityList) {
        validateKeyLength(entity.getFromKey());
        validateKeyLength(entity.getToKey());
        validatePublisherAssertion(em, entity);

        org.apache.juddi.model.PublisherAssertionId pubAssertionId = new org.apache.juddi.model.PublisherAssertionId(
                entity.getFromKey(), entity.getToKey());
        Object obj = em.find(org.apache.juddi.model.PublisherAssertion.class, pubAssertionId);
        if (obj == null) {
            throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound",
                    entity.getFromKey() + ", " + entity.getToKey()));
        } else {
            org.apache.juddi.model.PublisherAssertion pubAssertion = (org.apache.juddi.model.PublisherAssertion) obj;
            org.uddi.api_v3.KeyedReference keyedRef = entity.getKeyedReference();
            if (keyedRef == null) {
                throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound",
                        entity.getFromKey() + ", " + entity.getToKey()));
            }

            if (!pubAssertion.getTmodelKey().equalsIgnoreCase(keyedRef.getTModelKey())
                    || !pubAssertion.getKeyName().equalsIgnoreCase(keyedRef.getKeyName())
                    || !pubAssertion.getKeyValue().equalsIgnoreCase(keyedRef.getKeyValue())) {
                throw new AssertionNotFoundException(new ErrorMessage("errors.pubassertion.AssertionNotFound",
                        entity.getFromKey() + ", " + entity.getToKey()));
            }

        }

    }
}

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

public void validateDeleteService(EntityManager em, DeleteService body) throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }/*from  w  w  w .  j a  v  a2s.c om*/

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

    HashSet<String> dupCheck = new HashSet<String>();
    int i = 0;
    for (String entityKey : entityKeyList) {

        // 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.BusinessService.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.ServiceNotFound", entityKey));
        }

        //if you're are the owner, access granted
        //if you are an admin && this item belongs to this node, access granted
        //else denied

        AccessCheck(obj, entityKey);
        i++;
    }
}

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

public void validateDeleteBusiness(EntityManager em, DeleteBusiness body) throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }/*from w w w  .j  a va  2s . c  o m*/

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

    HashSet<String> dupCheck = new HashSet<String>();
    int i = 0;
    for (String entityKey : entityKeyList) {

        // 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.BusinessEntity.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.BusinessNotFound", entityKey));
        }

        if (!publisher.isOwner((UddiEntity) obj) && !((Publisher) publisher).isAdmin()) {
            throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey));
        }

        i++;
    }
}

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

public void validateAdminDeleteTModel(EntityManager em, DeleteTModel body)
        throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }//from  www .  ja va  2 s.c  o m

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

    if (!((Publisher) publisher).isAdmin()) {
        throw new UserMismatchException(new ErrorMessage("errors.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.Tmodel.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey));
        }

        //if (!publisher.isOwner((UddiEntity) obj)) {
        //        throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey));
        //}

    }
}

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

public void validateDeleteTModel(EntityManager em, DeleteTModel body) throws DispositionReportFaultMessage {

    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }//from w ww.j  a  v a2  s.  co  m

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

    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.Tmodel.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.TModelNotFound", entityKey));
        }

        AccessCheck(obj, entityKey);

        i++;
    }
}