List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:com.enioka.jqm.tools.Loader.java
/** * Part of the endOfRun process that needs the database. May be deferred if the database is not available. */// w w w.ja v a2 s . c om void endOfRunDb() { EntityManager em = Helpers.getNewEm(); try { // Retrieve the object to update job = em.find(JobInstance.class, this.job.getId()); // Which end time should we use? Default is always use DB time to avoid time lips between servers. Date dbTimeTmp = em.createQuery("SELECT current_timestamp() AS A from GlobalParameter", Date.class) .getSingleResult(); Calendar dbTime = Calendar.getInstance(); dbTime.setTime(dbTimeTmp); if (!this.isDelayed) { // In case of delayed finalization, use the stored time instead of db time. this.endDate = dbTime; } // Done: put inside history & remove instance from queue. em.getTransaction().begin(); History h = Helpers.createHistory(job, em, this.resultStatus, endDate); jqmlogger.trace("An History was just created for job instance " + h.getId()); em.createQuery("DELETE FROM JobInstance WHERE id = :i").setParameter("i", job.getId()).executeUpdate(); em.getTransaction().commit(); } catch (RuntimeException e) { endBlockDbFailureAnalysis(e); } finally { Helpers.closeQuietly(em); } }
From source file:nl.b3p.kaartenbalie.core.server.accounting.AccountManager.java
/** * /*www . j ava 2 s . c o m*/ * @param accountTransaction * @param user * @throws java.lang.Exception */ public synchronized void commitTransaction(Transaction accountTransaction, User user) throws Exception { if (!enableAccounting) { return; } if (accountTransaction != null) { //Create an EntityManager log.debug("Getting entity manager ......"); EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM); //Get the account and set the current balance. Update the class variable at the same time. Account account = (Account) em.find(Account.class, organizationId); balance = account.getCreditBalance(); //Set the account & user for the accountTransaction. accountTransaction.setAccount(account); accountTransaction.setUser(user); try { //Run validation (checks what type of transaction is allowed..) accountTransaction.validate(); //Now check if the transaction either has to deposit or withdraw... BigDecimal newBalance = null; if (accountTransaction.getType() == Transaction.DEPOSIT) { newBalance = balance.add(accountTransaction.getCreditAlteration()); } else if (accountTransaction.getType() == Transaction.WITHDRAW) { newBalance = balance.subtract(accountTransaction.getCreditAlteration()); if (newBalance.doubleValue() < 0) { throw new TransactionDeniedException("Insufficient credits for transaction. " + "Required credits: " + accountTransaction.getCreditAlteration().setScale(2, BigDecimal.ROUND_HALF_UP) .toString() + ", " + "Current balance: " + balance.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); } } else { log.error("Unsupported transaction type"); throw new Exception("Unsupported transaction type"); } account.setCreditBalance(newBalance); accountTransaction.setMutationDate(new Date()); accountTransaction.setStatus(Transaction.ACCEPTED); Iterator iterPriceComp = accountTransaction.getLayerPriceCompositions().iterator(); while (iterPriceComp.hasNext()) { LayerPriceComposition lpc = (LayerPriceComposition) iterPriceComp.next(); em.persist(lpc); } em.merge(accountTransaction); em.flush(); balance = newBalance; } catch (TransactionDeniedException tde) { accountTransaction.setErrorMessage(tde.getMessage()); accountTransaction.setStatus(Transaction.REFUSED); em.merge(accountTransaction); em.flush(); throw tde; } } }
From source file:org.apache.juddi.api.impl.AuthenticatedService.java
public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage { if (authInfo == null || authInfo.length() == 0) throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired")); org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo); if (modelAuthToken == null) throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); int allowedMinutesOfInactivity = 0; try {//from w w w . j av a2 s. c o m allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0); } catch (ConfigurationException ce) { logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + "the application's configuration. No automatic timeout token invalidation will occur. " + ce.getMessage(), ce); } int maxMinutesOfAge = 0; try { maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0); } catch (ConfigurationException ce) { logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from " + "the application's configuration. No automatic timeout token invalidation will occur. " + ce.getMessage(), ce); } Date now = new Date(); // 0 or negative means token does not expire if (allowedMinutesOfInactivity > 0) { // expire tokens after # minutes of inactivity // compare the time in milli-seconds if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) { logger.info("AUDIT: FAILTURE Token " + modelAuthToken.getAuthToken() + " expired due to inactivity " + getRequestorsIPAddress()); modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); } } if (maxMinutesOfAge > 0) { // expire tokens when max age is reached // compare the time in milli-seconds if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) { logger.info("AUDIT: FAILURE - Token " + modelAuthToken.getAuthorizedName() + " expired due to old age " + getRequestorsIPAddress()); modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); } } if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED) { throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthTokenExpired")); } if (ctx != null) { try { boolean check = true; try { check = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP, true); } catch (ConfigurationException ex) { logger.warn("Error loading config property " + Property.JUDDI_AUTH_TOKEN_ENFORCE_SAME_IP + " Enforcing Same IP for Auth Tokens will be enabled by default", ex); } if (check) { MessageContext mc = ctx.getMessageContext(); HttpServletRequest req = null; if (mc != null) { req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST); } if (req != null && modelAuthToken.getIPAddress() != null && modelAuthToken.getIPAddress() != null && !modelAuthToken.getIPAddress().equalsIgnoreCase(req.getRemoteAddr())) { modelAuthToken.setTokenState(AUTHTOKEN_RETIRED); logger.error( "AUDIT FAILURE - Security Alert - Attempt to use issued auth token from a different IP address, user " + modelAuthToken.getAuthorizedName() + ", issued IP " + modelAuthToken.getIPAddress() + ", attempted use from " + req.getRemoteAddr() + ", forcing reauthentication."); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); //invalidate the token, someone's intercepted it or it was reused on another ip } } } catch (Exception ex) { if (ex instanceof AuthTokenRequiredException) throw (AuthTokenRequiredException) ex; logger.error("unexpected error caught looking up requestor's ip address", ex); } } Authenticator authenticator = AuthenticatorFactory.getAuthenticator(); UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName()); // Must make sure the returned publisher has all the necessary fields filled if (entityPublisher == null) { logger.warn( "AUDIT FAILURE - Auth token invalided, publisher does not exist " + getRequestorsIPAddress()); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); } if (entityPublisher.getAuthorizedName() == null) { logger.warn("AUDIT FAILURE - Auth token invalided, username does exist" + getRequestorsIPAddress()); throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid")); } // Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset. modelAuthToken.setLastUsed(new Date()); modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1); return entityPublisher; }
From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java
public void testSetFlushAndReset() throws IOException { EntityManager em = emf.createEntityManager(); em.getTransaction().begin();//from w ww . j a v a2s. co m LobEntity le = newLobEntity(createLobData(), 1); em.persist(le); em.flush(); String string = createLobData2(); changeStream(le, string); LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1); assertEquals(string, getStreamContentAsString(entity.getStream())); em.getTransaction().commit(); em.close(); }
From source file:fr.amapj.service.services.saisiepermanence.PermanenceService.java
@DbWrite public void updateorCreateDistribution(PermanenceDTO dto, boolean create) { EntityManager em = TransactionHelper.getEm(); DatePermanence d = null;/* w ww . j av a 2 s . co m*/ if (create) { d = new DatePermanence(); d.setDatePermanence(dto.datePermanence); em.persist(d); } else { d = em.find(DatePermanence.class, dto.id); List<DatePermanenceUtilisateur> dus = getAllDateDistriUtilisateur(em, d); for (DatePermanenceUtilisateur du : dus) { em.remove(du); } } for (PermanenceUtilisateurDTO distriUtilisateur : dto.permanenceUtilisateurs) { DatePermanenceUtilisateur du = new DatePermanenceUtilisateur(); du.setDatePermanence(d); du.setUtilisateur(em.find(Utilisateur.class, distriUtilisateur.idUtilisateur)); du.setNumSession(distriUtilisateur.numSession); em.persist(du); } }
From source file:org.sigmah.server.servlet.exporter.models.OrgUnitModelHandler.java
@Override public String exportModel(OutputStream outputStream, String identifier, EntityManager em) throws Exception { String name = ""; if (identifier != null) { final Integer orgUnitModelId = Integer.parseInt(identifier); final OrgUnitModel hibernateModel = em.find(OrgUnitModel.class, orgUnitModelId); if (hibernateModel == null) throw new Exception("No orgUnit model is associated with the identifier '" + identifier + "'."); name = hibernateModel.getName(); // Stripping hibernate proxies from the model. final OrgUnitModel realModel = Realizer.realize(hibernateModel); // Serialization try {//from w ww . jav a 2s.co m final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(realModel); } catch (Exception ex) { throw new Exception("An error occured while serializing the orgUnit model " + orgUnitModelId, ex); } } else { throw new Exception("The identifier is missing."); } return name; }
From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java
@Override public String exportModel(OutputStream outputStream, String identifier, EntityManager em) throws ExportException { String name = ""; if (identifier != null) { final Integer orgUnitModelId = Integer.parseInt(identifier); final OrgUnitModel hibernateModel = em.find(OrgUnitModel.class, orgUnitModelId); if (hibernateModel == null) throw new ExportException( "No orgUnit model is associated with the identifier '" + identifier + "'."); name = hibernateModel.getName(); // Stripping hibernate proxies from the model. final OrgUnitModel realModel = Realizer.realize(hibernateModel); // Serialization try {/*w w w .j a v a 2 s . c o m*/ final ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(realModel); } catch (IOException ex) { throw new ExportException("An error occured while serializing the orgUnit model " + orgUnitModelId, ex); } } else { throw new ExportException("The identifier is missing."); } return name; }
From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java
public Resolution removeFromIndex() { EntityManager em = Stripersist.getEntityManager(); SolrServer server = SolrInitializer.getServerInstance(); solrConfiguration = em.find(SolrConf.class, solrConfiguration.getId()); SolrUpdateJob.removeSolrConfigurationFromIndex(solrConfiguration, em, server); em.getTransaction().commit();/*www. j a va 2 s .c om*/ return new ForwardResolution(EDIT_JSP); }
From source file:nl.b3p.viewer.admin.stripes.ConfigureSolrActionBean.java
@WaitPage(path = "/WEB-INF/jsp/waitpage.jsp", delay = 2000, refresh = 1000, ajax = "/WEB-INF/jsp/waitpageajax.jsp") public Resolution addToIndex() throws InterruptedException { removeFromIndex();// w w w.j a va2s.c o m status = new WaitPageStatus(); EntityManager em = Stripersist.getEntityManager(); SolrServer server = SolrInitializer.getServerInstance(); solrConfiguration = em.find(SolrConf.class, solrConfiguration.getId()); SolrUpdateJob.insertSolrConfigurationIntoIndex(solrConfiguration, em, status, server); em.getTransaction().commit(); return new ForwardResolution(EDIT_JSP); }
From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.SessionDaoImpl.java
@Override public SessionImpl getSession(long sessionId) { final EntityManager entityManager = this.getEntityManager(); return entityManager.find(SessionImpl.class, sessionId); }