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.api.impl.JUDDIApiImpl.java

/**
 * Retrieves clientSubscriptionKey(s) from the persistence layer. This
 * method is specific to jUDDI. Used for server to server subscriptions
 * Administrative privilege required./*from   w  w  w  .  j  a v a  2s  .co  m*/
 * @param body
 * @return ClientSubscriptionInfoDetail
 * @throws DispositionReportFaultMessage 
 */
public ClientSubscriptionInfoDetail getClientSubscriptionInfoDetail(GetClientSubscriptionInfoDetail body)
        throws DispositionReportFaultMessage {

    new ValidateClientSubscriptionInfo(null).validateGetClientSubscriptionInfoDetail(body);

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        this.getEntityPublisher(em, body.getAuthInfo());

        ClientSubscriptionInfoDetail result = new ClientSubscriptionInfoDetail();

        List<String> subscriptionKeyList = body.getClientSubscriptionKey();
        for (String subscriptionKey : subscriptionKeyList) {

            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);

            result.getClientSubscriptionInfo().add(apiClientSubscriptionInfo);
        }

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

}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BusinessService uddiEntity,
        UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);// ww  w .ja  v a 2  s. c  om
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class,
                uddiEntity.getBusinessEntity().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);
    }

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BusinessService existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null) {
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    } else
        uddiEntity.setCreated(now);

    List<org.apache.juddi.model.BindingTemplate> bindingList = uddiEntity.getBindingTemplates();
    for (org.apache.juddi.model.BindingTemplate binding : bindingList)
        setOperationalInfo(em, binding, publisher, true);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.BindingTemplate uddiEntity,
        UddiEntityPublisher publisher, boolean isChild) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*from w ww. ja  v a2s.  co  m*/
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessService parent = em.find(org.apache.juddi.model.BusinessService.class,
                uddiEntity.getBusinessService().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);

        // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
        org.apache.juddi.model.BusinessEntity businessParent = em
                .find(org.apache.juddi.model.BusinessEntity.class, parent.getBusinessEntity().getEntityKey());
        businessParent.setModifiedIncludingChildren(now);
        em.persist(businessParent);
    }

    String nodeId = "";
    try {
        nodeId = AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID);
    } catch (ConfigurationException ce) {
        throw new FatalErrorException(
                new ErrorMessage("errors.configuration.Retrieval", Property.JUDDI_NODE_ID));
    }
    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.BindingTemplate existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> void delete(Class<T> clazz, T o, Object id) throws Exception {

    testClazz(clazz);/*from   ww  w  . ja  v a2s.  c  o m*/

    EntityManager em = getEntityManager();

    try {
        if (!globalTransactionOpen)
            em.getTransaction().begin();

        T attached = em.find(clazz, id);
        if (attached != null) {
            em.remove(attached);
            // em.remove(o);
        }
        if (!globalTransactionOpen)
            em.getTransaction().commit();

    } catch (Exception e) {
        throw e;
    } finally {

        // Close the database connection:
        if (!globalTransactionOpen) {
            if (em.getTransaction().isActive())
                em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

}

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

private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager)
        throws SAXException, TikaException, IOException, TransformerConfigurationException,
        InterruptedException {/*from   www  .jav  a  2  s  .  c  o  m*/
    File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", ""))
            + JobMapperMonitor.RESOURCESDIR);
    String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue();
    String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue();
    String resourceFileName = cr.getDigest() + ".gz";
    File resourceFile = new File(resourceDir, resourceFileName);
    StringWithEncoding rawContentAndEncoding = null;
    String contentType = cr.getContentType();
    // long t1 = System.currentTimeMillis();
    if (contentType != null && contentType.contains("application/msword")) {
        rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("application/rtf")) {
        rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("text/plain")) {
        // txt -> html -> txt is for txt cleaning
        rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("pdf")) {
        rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("html")) {
        rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile);
    }
    // long t2 = System.currentTimeMillis();
    // System.out.println("Transformation: " + (t2 - t1));
    if (rawContentAndEncoding != null) {
        if (rawContentAndEncoding.getEncoding() == null) {
            rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8");
        }
        // t1 = System.currentTimeMillis();
        String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString());
        rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding());
        File tmpFile = File.createTempFile("ridire", null);
        FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8");
        String ridireCleanerJar = entityManager
                .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue();
        String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue();
        CommandLine commandLine = CommandLine
                .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar);
        commandLine.addArgument("-f");
        commandLine.addArgument(tmpFile.getPath());
        commandLine.addArgument("-e");
        commandLine.addArgument("UTF-8");
        commandLine.addArgument("-h");
        commandLine.addArgument(host);
        commandLine.addArgument("-k");
        commandLine.addArgument(alchemyKey);
        commandLine.addArgument("-r");
        commandLine.addArgument(readabilityKey);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = executor.execute(commandLine);
        if (exitValue == 0) {
            rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8");
            // TODO filter real errors
            rawContentAndEncoding.setCleaner(baosStdErr.toString().trim());
        }
        FileUtils.deleteQuietly(tmpFile);
    }
    return rawContentAndEncoding;
}

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

public void deleteBusiness(DeleteBusiness body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*  w  ww.jav a 2  s. co  m*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateDeleteBusiness(em, body);

        List<String> entityKeyList = body.getBusinessKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BusinessEntity.class, entityKey);
            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BUSINESS, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

public void validateDeleteSubscription(EntityManager em, DeleteSubscription body)
        throws DispositionReportFaultMessage {
    // No null input
    if (body == null) {
        throw new FatalErrorException(new ErrorMessage("errors.NullInput"));
    }//from   w  ww  . j  a va  2  s .  c  o  m

    // No null or empty list
    List<String> entityKeyList = body.getSubscriptionKey();
    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.Subscription.class, entityKey);
        if (obj == null) {
            throw new InvalidKeyPassedException(
                    new ErrorMessage("errors.invalidkey.SubscriptionNotFound", entityKey));
        }

        // Make sure publisher owns this entity.
        if (!publisher.getAuthorizedName()
                .equals(((org.apache.juddi.model.Subscription) obj).getAuthorizedName())) {
            throw new UserMismatchException(new ErrorMessage("errors.usermismatch.InvalidOwner", entityKey));
        }

        i++;
    }
}

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

public void deleteService(DeleteService body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//from  w ww  .j  a  va 2s .c  om
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateDeleteService(em, body);

        List<String> entityKeyList = body.getServiceKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey);

            ((org.apache.juddi.model.BusinessService) obj).getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

public void deleteBinding(DeleteBinding body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from w  ww  .j  a va  2s.  com*/
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidatePublish(publisher).validateDeleteBinding(em, body);

        List<String> entityKeyList = body.getBindingKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, entityKey);

            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService()
                    .setModifiedIncludingChildren(new Date());
            // JUDDI-421:  now the businessEntity parent will have it's modifiedIncludingChildren set
            ((org.apache.juddi.model.BindingTemplate) obj).getBusinessService().getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_BINDING, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}