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.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

@Test
public void deleteResource() throws Exception {
    // Setup//from  w ww. ja  v  a2  s. com
    mockAgentService.setDeleteReturnStatus(DeleteResourceStatus.SUCCESS);
    Resource deleteMe = addResourceToParent();

    assert deleteMe != null : "Child resource to be deleted was not correctly added in the first place";

    // Assemble call parameters
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();

    // Test
    resourceFactoryManager.deleteResource(overlord, deleteMe.getId());

    // Verify
    EntityManager entityManager = null;

    try {
        getTransactionManager().begin();
        entityManager = getEntityManager();

        Resource parent = entityManager.find(Resource.class, parentResource.getId());
        Set<Resource> childResources = parent.getChildResources();

        assert childResources.size() == 1 : "Child resource not found on the parent";

        Resource deletedResource = childResources.iterator().next();

        assert deletedResource
                .getInventoryStatus() == InventoryStatus.DELETED : "Inventory status for deleted resource was incorrect. Expected: Deleted, Found: "
                        + deletedResource.getInventoryStatus();
    } finally {
        getTransactionManager().rollback();
        entityManager.close();
    }
}

From source file:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

@Test
public void deleteResourceFailure() throws Exception {
    // Setup/*w ww.  ja  v a 2 s  .  co  m*/
    mockAgentService.setDeleteReturnStatus(DeleteResourceStatus.FAILURE);
    Resource deleteMe = addResourceToParent();

    assert deleteMe != null : "Child resource to be deleted was not correctly added in the first place";

    // Assemble call parameters
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();

    // Test
    resourceFactoryManager.deleteResource(overlord, deleteMe.getId());

    // Verify
    EntityManager entityManager = null;

    try {
        getTransactionManager().begin();
        entityManager = getEntityManager();

        Resource parent = entityManager.find(Resource.class, parentResource.getId());
        Set<Resource> childResources = parent.getChildResources();

        assert childResources.size() == 1 : "Child resource not found on the parent";

        Resource deletedResource = childResources.iterator().next();

        assert deletedResource
                .getInventoryStatus() == InventoryStatus.COMMITTED : "Inventory status for deleted resource was incorrect. Expected: Committed, Found: "
                        + deletedResource.getInventoryStatus();
    } finally {
        getTransactionManager().rollback();
        entityManager.close();
    }
}

From source file:nl.b3p.kaartenbalie.struts.WmsServerAction.java

protected ServiceProvider getServiceProvider(DynaValidatorForm dynaForm, HttpServletRequest request,
        boolean createNew) throws Exception {
    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    ServiceProvider serviceProvider = null;
    Integer id = getID(dynaForm);
    if (null == id && createNew) {
        serviceProvider = new ServiceProvider();
    } else if (null != id) {
        serviceProvider = (ServiceProvider) em.find(ServiceProvider.class, new Integer(id.intValue()));
    }//www . ja v a2s. c om
    return serviceProvider;
}

From source file:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

@Test
public void createResourceViaConfigurationFailure() throws Exception {
    // Setup//from w  w  w .j a  v a2  s  . co  m
    mockAgentService.setCreateReturnStatus(CreateResourceStatus.FAILURE);

    // Assemble call parameters
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();

    Configuration resourceConfiguration = new Configuration();
    resourceConfiguration.put(new PropertySimple("property1", "value1"));

    // Test
    resourceFactoryManager.createResource(overlord, parentResource.getId(), childResourceType.getId(),
            "newResource", null, resourceConfiguration);

    // Verify
    EntityManager entityManager = null;
    try {
        getTransactionManager().begin();
        entityManager = getEntityManager();

        Resource parent = entityManager.find(Resource.class, parentResource.getId());
        List<CreateResourceHistory> historyList = parent.getCreateChildResourceRequests();

        assert historyList.size() == 1 : "Incorrect number of children found. Expected: 1, Found: "
                + historyList.size();

        CreateResourceHistory historyItem = historyList.get(0);

        assert historyItem
                .getStatus() == CreateResourceStatus.FAILURE : "Incorrect status for history item. Expected: Failure, Found: "
                        + historyItem.getStatus();
        assert historyItem.getErrorMessage().equals(
                "errorMessage") : "Incorrect error message for history item. Expected: errorMessage, Found: "
                        + historyItem.getErrorMessage();
    } finally {
        getTransactionManager().rollback();
        entityManager.close();
    }
}

From source file:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

@Test
public void createResourceViaConfiguration() throws Exception {
    // Setup/*  w  w  w .  jav a  2 s.c om*/
    mockAgentService.setCreateReturnStatus(CreateResourceStatus.SUCCESS);

    // Assemble call parameters
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();

    Configuration resourceConfiguration = new Configuration();
    resourceConfiguration.put(new PropertySimple("property1", "value1"));

    // Test
    resourceFactoryManager.createResource(overlord, parentResource.getId(), childResourceType.getId(),
            "newResource", null, resourceConfiguration);

    // Verify
    EntityManager entityManager = null;
    try {
        getTransactionManager().begin();
        entityManager = getEntityManager();

        Resource parent = entityManager.find(Resource.class, parentResource.getId());
        List<CreateResourceHistory> historyList = parent.getCreateChildResourceRequests();

        assert historyList.size() == 1 : "Incorrect number of children found. Expected: 1, Found: "
                + historyList.size();

        CreateResourceHistory historyItem = historyList.get(0);

        assert historyItem
                .getStatus() == CreateResourceStatus.SUCCESS : "Incorrect status for history item. Expected: Success, Found: "
                        + historyItem.getStatus();
        assert historyItem.getNewResourceKey().equals(
                "mockResourceKey") : "Incorrect resource key for history item. Expected: mockResourceKey, Found: "
                        + historyItem.getNewResourceKey();
        assert historyItem.getErrorMessage() == null : "Error message found for successful call";
        assert historyItem.getConfiguration() != null : "Null configuration found for history item";
    } finally {
        getTransactionManager().rollback();
        entityManager.close();
    }
}

From source file:org.apache.juddi.v3.auth.HTTPHeaderAuthenticator.java

@Override
public UddiEntityPublisher identify(String notusedauthtoken, String notusedusername, WebServiceContext ctx)
        throws AuthenticationException, FatalErrorException {
    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    String http_header_name = null;
    try {/*w  w  w . j av  a  2  s  .  c o  m*/
        http_header_name = AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_HTTP_HEADER_NAME);
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        log.error("config exception! ", ex);
    }
    if (http_header_name == null) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", "misconfiguration!"));
    }
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String user = null;

        MessageContext mc = ctx.getMessageContext();
        HttpServletRequest req = null;
        if (mc != null) {
            req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
            user = req.getHeader(http_header_name);
        }

        if (user == null || user.length() == 0) {
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher"));
        }
        tx.begin();
        Publisher publisher = em.find(Publisher.class, user);
        if (publisher == null) {
            log.warn("Publisher \"" + user
                    + "\" was not found in the database, adding the publisher in on the fly.");
            publisher = new Publisher();
            publisher.setAuthorizedName(user);
            publisher.setIsAdmin("false");
            publisher.setIsEnabled("true");
            publisher.setMaxBindingsPerService(MaxBindingsPerService);
            publisher.setMaxBusinesses(MaxBusinesses);
            publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
            publisher.setMaxTmodels(MaxTmodels);
            publisher.setPublisherName("Unknown");
            em.persist(publisher);
            tx.commit();
        }

        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

/**
 * {@inheritDoc}/* ww  w . j a  va2 s.  c om*/
 * 
 * @see org.opencastproject.usertracking.api.UserTrackingService#getUserAction(java.lang.Long)
 */
@Override
public UserAction getUserAction(Long id) throws UserTrackingException, NotFoundException {
    EntityManager em = null;
    UserActionImpl result = null;
    try {
        em = emf.createEntityManager();
        result = em.find(UserActionImpl.class, id);
    } catch (Exception e) {
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
    if (result == null) {
        throw new NotFoundException("No UserAction found with id='" + id + "'");
    } else {
        return result;
    }
}

From source file:com.jada.admin.contactus.ContactUsMaintAction.java

private void saveDefault(ContactUs contactUs, ContactUsMaintActionForm form, AdminBean adminBean)
        throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    ContactUsLanguage contactUsLanguage = contactUs.getContactUsLanguage();
    if (contactUsLanguage == null) {
        contactUsLanguage = new ContactUsLanguage();
        contactUsLanguage.setContactUs(contactUs);
        contactUs.getContactUsLanguages().add(contactUsLanguage);
        SiteProfileClass siteProfileClass = em.find(SiteProfileClass.class,
                form.getSiteProfileClassDefaultId());
        contactUsLanguage.setSiteProfileClass(siteProfileClass);
        contactUsLanguage.setRecCreateBy(adminBean.getUser().getUserId());
        contactUsLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        contactUs.setContactUsLanguage(contactUsLanguage);
    }/* www  .ja v a2  s . c  o m*/
    contactUsLanguage.setContactUsName(form.getContactUsName());
    contactUsLanguage.setContactUsDesc(form.getContactUsDesc());
    contactUsLanguage.setRecUpdateBy(adminBean.getUser().getUserId());
    contactUsLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
    em.persist(contactUsLanguage);
}

From source file:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

@Test
public void createResourceViaPackage() throws Exception {
    // Setup/*  w  ww.  ja v a 2s  .co m*/
    mockAgentService.setCreateReturnStatus(CreateResourceStatus.SUCCESS);

    // Assemble call parameters
    Subject overlord = LookupUtil.getSubjectManager().getOverlord();
    String packageName = "testDataResourcePackage";
    String packageVersion = "1.0.0";
    int architectureId = 1; // easier than loading a specific architecture from the DB, just use the first one

    Configuration deploymentTimeConfiguration = new Configuration();
    deploymentTimeConfiguration.put(new PropertySimple("testProperty", "testValue"));

    // This file should be in the classpath, so use it for the artifact content
    URL contentResource = this.getClass().getClassLoader().getResource("jndi.properties");
    assert contentResource != null : "Could not load jndi.properties as package content";

    InputStream packageInputStream = contentResource.openStream();

    // Test
    resourceFactoryManager.createResource(overlord, parentResource.getId(), childResourceType.getId(),
            "newResource", null, packageName, packageVersion, architectureId, deploymentTimeConfiguration,
            packageInputStream);

    // Verify
    EntityManager entityManager = null;
    try {
        getTransactionManager().begin();
        entityManager = getEntityManager();

        Resource parent = entityManager.find(Resource.class, parentResource.getId());
        List<CreateResourceHistory> historyList = parent.getCreateChildResourceRequests();

        assert historyList.size() == 1 : "Incorrect number of children found. Expected: 1, Found: "
                + historyList.size();

        CreateResourceHistory historyItem = historyList.get(0);

        assert historyItem
                .getStatus() == CreateResourceStatus.SUCCESS : "Incorrect status for history item. Expected: Success, Found: "
                        + historyItem.getStatus();
        assert historyItem.getNewResourceKey().equals(
                "mockResourceKey") : "Incorrect resource key for history item. Expected: mockResourceKey, Found: "
                        + historyItem.getNewResourceKey();
        assert historyItem.getErrorMessage() == null : "Error message found for successful call";
    } finally {
        getTransactionManager().rollback();
        entityManager.close();
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Sends out the notifications.//from w w w .ja va2s .  c o  m
 * @param getSubscriptionResults
 * @param resultList 
 * @param notificationDate 
 */
protected void notify(GetSubscriptionResults getSubscriptionResults, SubscriptionResultsList resultList,
        Date notificationDate) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        String subscriptionKey = resultList.getSubscription().getSubscriptionKey();
        org.apache.juddi.model.Subscription modelSubscription = em
                .find(org.apache.juddi.model.Subscription.class, subscriptionKey);
        Date lastNotifiedDate = modelSubscription.getLastNotified();
        //now log to the db that we are sending the notification.
        tx.begin();
        modelSubscription.setLastNotified(notificationDate);
        em.persist(modelSubscription);
        tx.commit();

        org.apache.juddi.model.BindingTemplate bindingTemplate = em
                .find(org.apache.juddi.model.BindingTemplate.class, modelSubscription.getBindingKey());
        NotifySubscriptionListener body = new NotifySubscriptionListener();
        //         if (resultList.getServiceList()!=null && resultList.getServiceList().getServiceInfos()!=null &&
        //               resultList.getServiceList().getServiceInfos().getServiceInfo().size() == 0) {
        //            resultList.getServiceList().setServiceInfos(null);
        //         }
        body.setSubscriptionResultsList(resultList);

        //TODO if the endpoint requires an auth token, look up the security endpoint of the remote registry
        //via ClientSubscriptionInfo

        if (sendToken) {
            String authorizedName = modelSubscription.getAuthorizedName();
            UDDISecurityImpl security = new UDDISecurityImpl();

            if (authorizedName != null) { // add a security token if needed
                try {
                    //obtain a token for this publisher
                    org.uddi.api_v3.AuthToken token = security.getAuthToken(authorizedName);
                    body.setAuthInfo(token.getAuthInfo());
                } catch (DispositionReportFaultMessage e) {
                    body.setAuthInfo("Failed to generate token, please contact UDDI admin");
                    log.error(e.getMessage(), e);
                }
            }
        }

        if (bindingTemplate != null) {
            if (AccessPointType.END_POINT.toString().equalsIgnoreCase(bindingTemplate.getAccessPointType())
                    || AccessPointType.WSDL_DEPLOYMENT.toString()
                            .equalsIgnoreCase(bindingTemplate.getAccessPointType())) {
                try {
                    Notifier notifier = new NotifierFactory().getNotifier(bindingTemplate);
                    if (notifier != null) {
                        log.info("Sending out notification to " + bindingTemplate.getAccessPointUrl());
                        notifier.notifySubscriptionListener(body);
                        //there maybe more chunks we have to send
                        String chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        while (chunkToken != null) {
                            UddiEntityPublisher publisher = new UddiEntityPublisher();
                            publisher.setAuthorizedName(modelSubscription.getAuthorizedName());
                            log.debug("Sending out next chunk: " + chunkToken + " to "
                                    + bindingTemplate.getAccessPointUrl());
                            getSubscriptionResults.setChunkToken(chunkToken);
                            resultList = subscriptionImpl.getSubscriptionResults(getSubscriptionResults,
                                    publisher);
                            body.setSubscriptionResultsList(resultList);
                            notifier.notifySubscriptionListener(body);
                            chunkToken = body.getSubscriptionResultsList().getChunkToken();
                        }
                        //successful notification so remove from the badNotificationList
                        if (badNotifications.containsKey(resultList.getSubscription().getSubscriptionKey()))
                            badNotifications.remove(resultList.getSubscription().getSubscriptionKey());
                    }
                } catch (Exception e) {
                    if (e.getCause() instanceof IOException) {
                        addBadNotificationToList(subscriptionKey, bindingTemplate.getAccessPointUrl());
                        //we could not notify so compensate the transaction above
                        modelSubscription.setLastNotified(lastNotifiedDate);
                        tx.begin();
                        em.persist(modelSubscription);
                        tx.commit();
                        //} else {
                        //log.warn("Unexpected WebServiceException " + e.getMessage() + e.getCause());
                    }
                    log.error("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause());
                    log.debug("Unexpected notification exception:" + e.getClass().getCanonicalName() + " "
                            + e.getMessage() + " " + e.getCause(), e);
                }
            } else {
                log.info("Binding " + bindingTemplate.getEntityKey() + " has an unsupported binding type of "
                        + bindingTemplate.getAccessPointType() + ". Only "
                        + AccessPointType.END_POINT.toString() + " and "
                        + AccessPointType.WSDL_DEPLOYMENT.toString() + " are supported.");
                addBadNotificationToList(subscriptionKey,
                        bindingTemplate.getAccessPointType() + " not supported");
            }
        } else {
            log.info("There is no valid binding template defined for this subscription: "
                    + modelSubscription.getBindingKey());
            addBadNotificationToList(subscriptionKey, modelSubscription.getBindingKey() + " not found");
        }

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}