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.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public Collection<PropValue> getPropValues(Object propFieldId) {
    EntityManager em = this.emf.createEntityManager();
    try {/*from  w  ww .  java  2 s  .c  o m*/
        PropField pf = em.find(PropField.class, LongUserType.massageToLong(propFieldId));
        logger.debug("PropField is " + pf.toString());
        Query query = em.createQuery("FROM PropValue propValue WHERE propField IN (:pf)");
        query.setParameter("pf", pf);
        List<PropValue> values = query.getResultList();
        logger.debug("PropValues are " + values.toString());
        return values;
    } finally {
        cleanup(em);
    }
}

From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java

public ActionForward removeCustomAttributeDetails(ActionMapping mapping, ActionForm actionForm,
        HttpServletRequest request, HttpServletResponse response) throws Throwable {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm;
    AdminBean adminBean = getAdminBean(request);
    Site site = adminBean.getSite();//  ww w .j av  a  2 s. c  o m

    JSONEscapeObject jsonResult = new JSONEscapeObject();
    jsonResult.put("status", Constants.WEBSERVICE_STATUS_SUCCESS);

    Long customAttribGroupId = Format.getLong(form.getCustomAttribGroupId());
    CustomAttributeGroup customAttributeGroup = CustomAttributeGroupDAO.load(site.getSiteId(),
            customAttribGroupId);
    String customAttribDetailIds[] = form.getCustomAttribDetailIds();
    if (customAttribDetailIds != null) {
        for (int i = 0; i < customAttribDetailIds.length; i++) {
            CustomAttributeDetail customAttributeDetail = (CustomAttributeDetail) em
                    .find(CustomAttributeDetail.class, Format.getLong(customAttribDetailIds[i]));
            if (customAttributeDetail.getCustomAttribute()
                    .getCustomAttribTypeCode() == Constants.CUSTOM_ATTRIBUTE_TYPE_SKU_MAKEUP) {
                String sql = "select  count(*) " + "from     ItemAttributeDetail itemAttributeDetail "
                        + "where     itemAttributeDetail.customAttributeDetail = :customAttributeDetail "
                        + "and     itemAttributeDetail.item.itemTypeCd = :itemTypeCd";
                Query query = em.createQuery(sql);
                query.setParameter("customAttributeDetail", customAttributeDetail);
                query.setParameter("itemTypeCd", Constants.ITEM_TYPE_SKU);
                Long count = (Long) query.getSingleResult();
                if (count.intValue() > 0) {
                    jsonResult.put("status", Constants.WEBSERVICE_STATUS_FAILED);
                    jsonResult.put("reason", Constants.WEBSERVICE_REASON_INUSE);
                    streamWebService(response, jsonResult.toHtmlString());
                    return null;
                }
            }

            String sql = "delete " + "from   ItemAttributeDetail itemAttributeDetail "
                    + "where  itemAttributeDetail.customAttributeDetail = :customAttributeDetail ";
            Query query = em.createQuery(sql);
            query.setParameter("customAttributeDetail", customAttributeDetail);
            query.executeUpdate();

            customAttributeGroup.getCustomAttributeDetails().remove(customAttributeDetail);
            em.remove(customAttributeDetail);
        }
    }
    streamWebService(response, jsonResult.toHtmlString());
    return null;
}

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

private void saveLanguage(ContactUs contactUs, ContactUsMaintActionForm form, AdminBean adminBean)
        throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    ContactUsLanguage contactUsLanguage = null;
    User user = adminBean.getUser();//  w w w. ja v a  2  s  .co  m
    Long siteProfileClassId = form.getSiteProfileClassId();
    boolean found = false;
    Iterator<?> iterator = contactUs.getContactUsLanguages().iterator();
    while (iterator.hasNext()) {
        contactUsLanguage = (ContactUsLanguage) iterator.next();
        if (contactUsLanguage.getSiteProfileClass().getSiteProfileClassId().equals(siteProfileClassId)) {
            found = true;
            break;
        }
    }
    if (!found) {
        contactUsLanguage = new ContactUsLanguage();
        contactUsLanguage.setRecCreateBy(user.getUserId());
        contactUsLanguage.setRecCreateDatetime(new Date(System.currentTimeMillis()));
        SiteProfileClass siteProfileClass = em.find(SiteProfileClass.class, siteProfileClassId);
        contactUsLanguage.setSiteProfileClass(siteProfileClass);
        contactUs.getContactUsLanguages().add(contactUsLanguage);
    }
    if (form.isContactUsNameLangFlag()) {
        contactUsLanguage.setContactUsName(form.getContactUsNameLang());
    } else {
        contactUsLanguage.setContactUsName(null);
    }
    if (form.isContactUsDescLangFlag()) {
        contactUsLanguage.setContactUsDesc(form.getContactUsDescLang());
    } else {
        contactUsLanguage.setContactUsDesc(null);
    }
    contactUsLanguage.setRecUpdateBy(user.getUserId());
    contactUsLanguage.setRecUpdateDatetime(new Date(System.currentTimeMillis()));
    em.persist(contactUsLanguage);
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public PropField getPropField(Object id) {
    EntityManager em = this.emf.createEntityManager();
    try {//from ww  w  .j a  v  a  2  s.  co m
        Long longId = LongUserType.massageToLong(id);
        PropField pf = em.find(PropField.class, longId);
        return pf;
    } finally {
        cleanup(em);
    }
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

private void enforceCorrectValueType(PropField propField, TicketProp prop, EntityManager em)
        throws InvalidValueException {
    Long longId = LongUserType.massageToLong(propField.getId());
    propField = em.find(PropField.class, longId);
    if (!propField.getValueType().newTicketProp().getClass().getName().equals(prop.getClass().getName())) {
        String err = "Value [" + prop.getValueAsString() + "] is not a valid value for the field ["
                + propField.getName() + "].  ";
        err += "Field is of type [" + propField.getValueType().name() + "].";
        throw new InvalidValueException(err);
    }/*from   w w w. j  a va 2 s  . c  om*/
}

From source file:org.rhq.enterprise.server.content.test.ContentSourceManagerBeanTest.java

private void tearDownTestEnvironment() throws Exception {
    getTransactionManager().begin();//from w  ww .  ja va 2s.c om
    EntityManager em = getEntityManager();

    try {
        try {
            resource1 = em.find(Resource.class, resource1.getId());
            for (InstalledPackage ip : resource1.getInstalledPackages()) {
                em.remove(ip);
            }

            package1 = em.find(Package.class, package1.getId());
            em.remove(package1);

            package2 = em.find(Package.class, package2.getId());
            em.remove(package2);

            package3 = em.find(Package.class, package3.getId());
            em.remove(package3);

            package4 = em.find(Package.class, package4.getId());
            em.remove(package4);

            package5 = em.find(Package.class, package5.getId());
            em.remove(package5);

            packageType1 = em.find(PackageType.class, packageType1.getId());
            em.remove(packageType1);

            packageType2 = em.find(PackageType.class, packageType2.getId());
            em.remove(packageType2);

            packageType3 = em.find(PackageType.class, packageType3.getId());
            em.remove(packageType3);

            packageType4 = em.find(PackageType.class, packageType4.getId());
            em.remove(packageType4);

            ResourceTreeHelper.deleteResource(em, resource1);

            resourceType1 = em.find(ResourceType.class, resourceType1.getId());
            em.remove(resourceType1);

            getTransactionManager().commit();
        } catch (Exception e) {
            e.printStackTrace();
            getTransactionManager().rollback();
            throw e;
        }
    } finally {
        em.close();
    }
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public Boolean deletePropField(Object id) {
    EntityManager em = this.emf.createEntityManager();
    try {//ww  w  .j a v  a 2 s .  c o  m
        Long longId = LongUserType.massageToLong(id);
        PropField pf = em.find(PropField.class, longId);
        if (pf != null) {
            em.getTransaction().begin();
            em.remove(pf);
            em.getTransaction().commit();
            return true;
        } else {
            return false;
        }
    } finally {
        cleanup(em);
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Instructs the registry to perform a synchronous subscription
 * response./*from  w  w  w  .j  a v  a 2 s  . co  m*/
 * @param body
 * @return SyncSubscriptionDetail
 * @throws DispositionReportFaultMessage
 * @throws RemoteException 
 */
@SuppressWarnings("unchecked")
public SyncSubscriptionDetail invokeSyncSubscription(SyncSubscription body)
        throws DispositionReportFaultMessage, RemoteException {

    //validate
    SyncSubscriptionDetail syncSubscriptionDetail = new SyncSubscriptionDetail();

    Map<String, org.apache.juddi.api_v3.ClientSubscriptionInfo> clientSubscriptionInfoMap = new HashMap<String, org.apache.juddi.api_v3.ClientSubscriptionInfo>();
    //find the clerks to go with these subscriptions
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());
        for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) {
            String subscriptionKey = getSubscriptionResult.getSubscriptionKey();
            org.apache.juddi.model.ClientSubscriptionInfo modelClientSubscriptionInfo = null;
            try {
                modelClientSubscriptionInfo = em.find(org.apache.juddi.model.ClientSubscriptionInfo.class,
                        subscriptionKey);
            } catch (ClassCastException e) {
            }
            if (modelClientSubscriptionInfo == null) {
                throw new InvalidKeyPassedException(
                        new ErrorMessage("errors.invalidkey.SubscripKeyNotFound", subscriptionKey));
            }
            org.apache.juddi.api_v3.ClientSubscriptionInfo apiClientSubscriptionInfo = new org.apache.juddi.api_v3.ClientSubscriptionInfo();
            MappingModelToApi.mapClientSubscriptionInfo(modelClientSubscriptionInfo, apiClientSubscriptionInfo);
            clientSubscriptionInfoMap.put(apiClientSubscriptionInfo.getSubscriptionKey(),
                    apiClientSubscriptionInfo);
        }

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

    for (GetSubscriptionResults getSubscriptionResult : body.getGetSubscriptionResultsList()) {
        try {
            String subscriptionKey = getSubscriptionResult.getSubscriptionKey();
            Clerk fromClerk = clientSubscriptionInfoMap.get(subscriptionKey).getFromClerk();
            Clerk toClerk = clientSubscriptionInfoMap.get(subscriptionKey).getToClerk();
            String clazz = fromClerk.getNode().getProxyTransport();
            Class<?> transportClass = ClassUtil.forName(clazz, this.getClass());
            Transport transport = (Transport) transportClass.getConstructor(String.class)
                    .newInstance(fromClerk.getNode().getName());
            UDDISubscriptionPortType subscriptionService = transport
                    .getUDDISubscriptionService(fromClerk.getNode().getSubscriptionUrl());
            SubscriptionResultsList list = subscriptionService.getSubscriptionResults(getSubscriptionResult);

            JAXBContext context = JAXBContext.newInstance(list.getClass());
            Marshaller marshaller = context.createMarshaller();
            StringWriter sw = new StringWriter();
            marshaller.marshal(list, sw);

            log.info("Notification received by UDDISubscriptionListenerService : " + sw.toString());

            NotificationList<String> nl = NotificationList.getInstance();
            nl.getNotifications().add(sw.toString());

            //update the registry with the notification list.
            XRegisterHelper.handle(fromClerk, toClerk, list);

            syncSubscriptionDetail.getSubscriptionResultsList().add(list);
        } catch (Exception ce) {
            log.error(ce.getMessage(), ce);
            if (ce instanceof DispositionReportFaultMessage) {
                throw (DispositionReportFaultMessage) ce;
            }
            if (ce instanceof RemoteException) {
                throw (RemoteException) ce;
            }
        }
    }
    //for now sending a clean object back

    return syncSubscriptionDetail;
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public void deletePropValue(Object propFieldId, Object propValueId) {
    EntityManager em = this.emf.createEntityManager();
    try {/*  ww  w .java  2  s .  c o  m*/
        Long longId = LongUserType.massageToLong(propValueId);
        PropValue pv = em.find(PropValue.class, longId);
        if (pv != null) {
            PropField propField = getPropField(pv.getPropField().getId());
            propField.getPropValues().remove(pv);
            em.getTransaction().begin();
            em.remove(pv);
            propField = em.merge(propField);
            em.getTransaction().commit();
        }
    } finally {
        cleanup(em);
    }
}

From source file:it.drwolf.ridire.session.async.Mapper.java

private String createPoSTagResource(File plainTextFile, EntityManager entityManager, String encoding)
        throws InterruptedException, IOException {
    // this is needed because TreeTagger doesn't handle spaces inside
    // filenames correctly
    File tmpFile = File.createTempFile("treetagger", null);
    FileUtils.copyFile(plainTextFile, tmpFile);
    String treeTaggerBin = entityManager
            .find(CommandParameter.class, CommandParameter.TREETAGGER_EXECUTABLE_KEY).getCommandValue();
    // if (encoding.equalsIgnoreCase("UTF-8")
    // || encoding.equalsIgnoreCase("UTF8")) {
    // treeTaggerBin = entityManager.find(CommandParameter.class,
    // CommandParameter.TREETAGGER_EXECUTABLE_UTF8_KEY)
    // .getCommandValue();
    // }/* w w w  .j  ava  2s .  c  o m*/
    this.ridireReTagger.setTreetaggerBin(treeTaggerBin);
    String tmpPoSFile = this.ridireReTagger.retagFile(tmpFile);
    File newPosFile = new File(plainTextFile.getAbsolutePath() + ".pos");
    if (tmpPoSFile != null) {
        if (newPosFile.exists()) {
            FileUtils.deleteQuietly(newPosFile);
        }
        FileUtils.moveFile(new File(tmpPoSFile), newPosFile);
        return newPosFile.getAbsolutePath();
    }
    return null;

    // CommandLine commandLine = CommandLine.parse(treeTaggerBin);
    // commandLine.addArgument(tmpFile.getPath());
    // DefaultExecutor executor = new DefaultExecutor();
    // executor.setExitValue(0);
    // ExecuteWatchdog watchdog = new ExecuteWatchdog(
    // Mapper.TREETAGGER_TIMEOUT);
    // executor.setWatchdog(watchdog);
    // ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    // ExecuteStreamHandler executeStreamHandler = new
    // PumpStreamHandler(baos,
    // null, null);
    // executor.setStreamHandler(executeStreamHandler);
    // int exitValue = executor.execute(commandLine);
    // FileUtils.deleteQuietly(tmpFile);
    // if (exitValue == 0) {
    // File posTagFile = new File(plainTextFile.getPath() + ".pos");
    // FileUtils.writeByteArrayToFile(posTagFile, baos.toByteArray());
    // return posTagFile.getCanonicalPath();
    // }
    // return null;
}