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:com.enioka.jqm.tools.JqmEngine.java

void startDbRestarter() {
    // On first alert, start the thread which will check connection restoration and relaunch the pollers.
    synchronized (this) {
        if (qpRestarter != null) {
            return;
        }//from ww  w . j a va2  s  .co m
    }

    final JqmEngine ee = this;
    qpRestarter = new Thread() {
        @Override
        public void run() {
            // Test if the DB is back and wait for it if not
            jqmlogger.warn("The engine will now indefinitely try to restore connection to the database");
            EntityManager em = null;
            boolean back = false;
            long timeToWait = 1;
            while (!back) {
                try {
                    synchronized (ee) {
                        em = Helpers.getNewEm();
                        em.find(Node.class, 1);
                        back = true;
                        ee.qpRestarter = null;
                        jqmlogger.warn("connection to database was restored");
                    }
                } catch (Exception e) {
                    // The db is not back yet
                    try {
                        jqmlogger.debug("waiting for db...");
                        Thread.sleep(1000 * timeToWait);
                        timeToWait = Math.min(timeToWait + 1, 120);
                    } catch (InterruptedException e1) {
                        // Not an issue here.
                        jqmlogger.debug("interrupted wait in db restarter");
                    }
                } finally {
                    Helpers.closeQuietly(em);
                }
            }

            // Restart pollers
            QueuePoller qp = qpToRestart.poll();
            while (qp != null) {
                jqmlogger.warn("resetting poller on queue " + qp.getQueue().getName());
                qp.reset();
                Thread t = new Thread(qp);
                t.start();
                qp = qpToRestart.poll();
            }

            // Always restart internal poller
            intPoller.stop();
            ee.intPoller = new InternalPoller(ee);
            Thread t = new Thread(ee.intPoller);
            t.start();

            // Finalize loaders that could not store their result inside the database
            Loader l = loaderToFinalize.poll();
            while (l != null) {
                jqmlogger.warn("storing delayed results for loader " + l.getId());
                l.endOfRunDb();
                l = loaderToFinalize.poll();
            }

            // Restart loaders that have failed during initialization
            l = loaderToRestart.poll();
            while (l != null) {
                jqmlogger.warn("restarting (after db failure during initialization) loader " + l.getId());
                (new Thread(l)).start();
                l = loaderToRestart.poll();
            }

            // Done - let the thread end.
        }
    };
    qpRestarter.start();
}

From source file:org.eclipse.jubula.client.core.persistence.ProjectPM.java

/**
 * Load an instance of ProjectPO into the readonly session. The read
 * instance is db identical to the key supplied.
 * used for open project//from  w  w  w. j  a v a2  s.com
 * 
 * @param project
 *            Look for this instance in the db.
 * @throws PMReadException
 *             if loading from db failed
 * 
 */
public static void loadProjectInROSession(IProjectPO project) throws PMReadException {

    GeneralStorage.getInstance().reset();
    EntityManager s = GeneralStorage.getInstance().getMasterSession();
    s.clear(); // get rid of all session (cached) data
    try {
        preloadData(s, project);

        IProjectPO p = s.find(NodeMaker.getProjectPOClass(), project.getId());
        GeneralStorage.getInstance().setProject(p);
        ParamNameBP.getInstance().initMap();
        ComponentNamesBP.getInstance().init();
    } catch (PersistenceException e) {
        GeneralStorage.getInstance().setProject(null);
        OperationCanceledException cancel = checkForCancel(e);
        if (cancel != null) {
            throw cancel;
        }
        String msg = Messages.CantReadProjectFromDatabase + StringConstants.DOT;
        log.error(Messages.UnexpectedPersistenceErrorIgnored + StringConstants.DOT, e);
        throw new PMReadException(msg + e.getMessage(), MessageIDs.E_CANT_READ_PROJECT);
    } catch (PMException e) {
        String msg = Messages.CouldNotReadParamNamesFromDB + StringConstants.DOT;
        log.error(msg, e);
        throw new PMReadException(msg + e.getMessage(), MessageIDs.E_CANT_READ_PROJECT);
    } catch (JBException e) {
        GeneralStorage.getInstance().setProject(null);
        String msg = Messages.CantReadProjectFromDatabase + StringConstants.DOT;
        log.error(Messages.UnexpectedPersistenceErrorIgnored, e);
        throw new PMReadException(msg + e.getMessage(), MessageIDs.E_CANT_READ_PROJECT);
    }
}

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

@SuppressWarnings("unchecked")
public void discardTransferToken(DiscardTransferToken body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

        new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body);

        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        if (apiTransferToken != null) {
            String transferTokenId = new String(apiTransferToken.getOpaqueToken());
            org.apache.juddi.model.TransferToken modelTransferToken = em
                    .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
            if (modelTransferToken != null)
                em.remove(modelTransferToken);
        }

        KeyBag keyBag = body.getKeyBag();
        if (keyBag != null) {
            List<String> keyList = keyBag.getKey();
            Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0);
            for (String key : keyList) {
                // Creating parameters for key-checking query
                DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)",
                        key.toUpperCase(), DynamicQuery.PREDICATE_EQUALS);

                params.add(param);
            }

            // Find the associated transfer tokens and remove them.
            DynamicQuery getTokensQry = new DynamicQuery();
            getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad();
            getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0]));

            Query qry = getTokensQry.buildJPAQuery(em);
            List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList();
            if (tokensToDelete != null && tokensToDelete.size() > 0) {
                for (org.apache.juddi.model.TransferToken tt : tokensToDelete)
                    em.remove(tt);
            }
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

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

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

@Test(enabled = ENABLED)
public void getRepoGroupTypeByName() throws Exception {
    // Setup//  w ww.j  a  v  a 2  s  .c o m
    EntityManager entityManager = getEntityManager();
    String name = "test-repo-type";

    RepoGroupType groupType = new RepoGroupType(name);
    entityManager.persist(groupType);
    entityManager.flush();

    // Test
    RepoGroupType type = repoManager.getRepoGroupTypeByName(overlord, name);
    assert type != null;
    assert type.getName().equals(name);

    // Cleanup
    type = entityManager.find(RepoGroupType.class, type.getId());
    entityManager.remove(type);
    entityManager.flush();
}

From source file:nl.b3p.viewer.stripes.ApplicationActionBean.java

private void getDefaultViewer() {
    EntityManager em = Stripersist.getEntityManager();
    try {// ww w  . j a  v  a2 s.c om
        Metadata md = em.createQuery("from Metadata where configKey = :key", Metadata.class)
                .setParameter("key", Metadata.DEFAULT_APPLICATION).getSingleResult();
        String appId = md.getConfigValue();
        Long id = Long.parseLong(appId);
        Application app = em.find(Application.class, id);
        name = app.getName();
        version = app.getVersion();
    } catch (NoResultException | NullPointerException e) {
        name = "default";
        version = null;
    }
}

From source file:com.tasktop.c2c.server.internal.tasks.domain.conversion.TaskDomain.java

public void fillManaged(Component managedComponent,
        com.tasktop.c2c.server.tasks.domain.Component domainComponent, EntityManager entityManager) {
    // Fill in the modifiable fields from this domain object.
    managedComponent.setName(domainComponent.getName());
    managedComponent.setDescription(domainComponent.getDescription());

    Profile initialOwner = null;//w  w  w.ja  va 2  s .  c o m
    if (domainComponent.getInitialOwner() != null) {
        initialOwner = entityManager.find(Profile.class, domainComponent.getInitialOwner().getId());
    }
    managedComponent.setInitialOwner(initialOwner);
}

From source file:com.webbfontaine.valuewebb.action.fcvr.FCVRSendScheduler.java

@Asynchronous
public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.info("Started");

    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSentTTIdsCI)).getResultList();

        LOGGER.debug("Found Sent TTs: {0}}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }// ww w .  ja va  2  s  .  c o  m

        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
            LOGGER.error("Can not login with 'daemon' identity to update TTs");
            return null;
        }
        try {

            for (Long ttId : ttIDs) {
                try {
                    TtGen ttGen = entityManager.find(TtGen.class, ttId);

                    LOGGER.debug("TT to sent to FCVR: {0}, status {1}", ttId, ttGen.getStatus());

                    if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                        continue;
                    }

                    new TTDataLoader(ttGen).processAll();

                    Message message = FCVRSender.getInstance().sendFCVR(ttGen);

                    if (FCVRHelper.transactionError(message)) {
                        LOGGER.error("SOGate respond with error for TT {0} with FCVR Number {1}. Error: {2}",
                                ttId, ttGen.getFcvrNum(), message.getProperties());
                        FCVRHelper.logExceptions(ttId, message);
                    } else {
                        if (FCVRHelper.transactionFailed(message)) {
                            FCVRHelper.logExceptions(ttId, message);

                            String remoteExceptionMessage = FCVRHelper.extractErrors(message);
                            FCVRHelper.appendErrorsToTT(ttGen, remoteExceptionMessage);

                            if (isFCVRAlreadyExists(remoteExceptionMessage)) {
                                LOGGER.warn(
                                        "FCVR already exists for TT with ID {0}, check logs for previous unexpected errors. TT status will be changed to Sent Ok.",
                                        ttId);
                                updateTT(ttGen, RESPONSE_OK); // ignore existance and change the status.
                            } else {
                                if (isAccessProblem(remoteExceptionMessage)) {
                                    LOGGER.warn(
                                            "Cannot complete transaction for FCVR document, got {0} for TT ID: {1}, document processing skipped.",
                                            remoteExceptionMessage, ttId);
                                } else {
                                    LOGGER.info(
                                            "Cannot complete transaction for FCVR document, TT ID: {0}, document status will be changed accordingly.",
                                            ttId);
                                    updateTT(ttGen, ERROR_RESPONSE);
                                }
                            }

                        } else {
                            if (FCVRHelper.transactionSucceeded(message)) {
                                LOGGER.info("FCVR transaction on TT {0} completed successfully", ttId);
                                updateTT(ttGen, RESPONSE_OK);
                            } else {
                                LOGGER.error("Unknown FCVR response for TT: {0}, message: {1}", ttId,
                                        message.getProperties());
                                throw new FCVRProcessingException(
                                        "Unknown FCVR reponse, remote document change is ");
                            }
                        }
                    }
                } catch (FCVRProcessingException e) {
                    Throwable cause = e.getCause();
                    if (isConnectionProblem(cause) || isLoginProblem(cause)) {
                        LOGGER.warn("{0}: Can not connect to TWM-FCVR. {1}", cause.getClass().getName(),
                                cause.getMessage());
                        break; // do not continue with next TT if connection problem
                    } else {
                        LOGGER.error("", e);
                    }
                }
            }
        } finally {
            AuthenticatorBean.getDaemonIdentity().logout();
        }
        LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);
        return null;
    }
}

From source file:commonSession.PersistAttivitaFacadeBean.java

public void delete(Object id, Class clazz, String unit) throws Exception {

    //    EntityManager em;
    EntityManager em = GestionaleEm;
    if (unit.equals("GestionaleEm"))
        em = GestionaleEm;/*from   w  w  w  . jav  a 2  s .com*/
    else
        em = TerritorioEm;

    Object obj = em.find(clazz, id);
    em.remove(obj);
    em.flush();

}

From source file:com.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

@Asynchronous
public QuartzTriggerHandle getFCVRStatusScheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.debug("Scheduler to get FCVR status started");
    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSubmittedSentTTIds))
                .getResultList();//from  w w  w.ja  v a2 s . c om

        LOGGER.debug("Found Sent and Uploaded TTs: {0}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }

        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
            LOGGER.error("Can not login with 'daemon' identity to get TTs status and update TTs");
            return null;
        }

        for (Long ttId : ttIDs) {
            TtGen ttGen = entityManager.find(TtGen.class, ttId);

            if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                continue;
            }

            FisInterface fisInterface = new FisInterface();
            LOGGER.debug("Sending request to get FCVR status for TT # {0}, FCVR Number = {1}", ttGen.getId(),
                    ttGen.getFcvrNum());

            Map<String, List<String>> remSt = fisInterface.retrieveFCVRValidationStatus(ttGen.getFcvrNum(),
                    new Date());
            if (remSt != null) {
                String key = (String) remSt.keySet().toArray()[0];
                if (GCNetUtils.isRejected(key)) {
                    LOGGER.debug(
                            "Got successfully FCVR 'Rejected' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'. Error message is: {2}",
                            ttGen.getId(), ttGen.getFcvrNum(), remSt.get(key));
                    ttGen.setSubmittedToGCNet(false);
                    updateTTForSentError(ttGen, remSt.get(key));
                } else {
                    if (GCNetUtils.isAccepted(key)) {
                        LOGGER.debug(
                                "Got successfully FCVR 'Accepted' status for TT # {0}, FCVR Number = {1}, setting GCNet Submission Flag 'false'",
                                ttGen.getId(), ttGen.getFcvrNum());
                        ttGen.setSubmittedToGCNet(false);
                        updateTT(ttGen, RESPONSE_OK);
                    } else {
                        if (GCNetUtils.isSubmitted(key)) {
                            LOGGER.debug(
                                    "TT # {0}, FCVR Number = {1} is still in Submitted status on GCNet side",
                                    ttGen.getId(), ttGen.getFcvrNum());
                        }
                    }
                }
            }
        }
        AuthenticatorBean.getDaemonIdentity().logout();
    }

    LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);

    return null;
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Internal method to find a DeltaIndexingDao object by id.
 * /*www. j  a  v a2s . c  o m*/
 * @param em
 *          the EntityManager to use
 * @param id
 *          the id
 * @return the RecordDao object or null
 */
private DeltaIndexingDao findDeltaIndexingDao(final EntityManager em, final ConnectivityId id) {
    return em.find(DeltaIndexingDao.class, id.getIdHash());
}