List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:com.chiralbehaviors.CoRE.kernel.Bootstrap.java
public static void main(String[] argv) throws Exception { if (argv.length != 2) { System.err.println("Usage: Bootstrap <jpa.properties> <output file>"); System.exit(1);//from w w w. j a v a2 s . c om } Properties properties = new Properties(); try (InputStream is = new FileInputStream(new File(argv[0]))) { properties.load(is); } EntityManagerFactory emf = Persistence.createEntityManagerFactory(WellKnownObject.CORE, properties); EntityManager em = emf.createEntityManager(); Bootstrap bootstrap = new Bootstrap(em); bootstrap.clear(); em.getTransaction().begin(); bootstrap.bootstrap(); em.getTransaction().commit(); em.clear(); bootstrap.serialize(argv[1]); }
From source file:pt.souplesse.spark.Server.java
public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("guestbook"); EntityManager manager = factory.createEntityManager(); JinqJPAStreamProvider streams = new JinqJPAStreamProvider(factory); get("/messages", (req, rsp) -> { rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); });//from ww w. j a v a2s . co m post("/messages", (req, rsp) -> { try { Message msg = gson.fromJson(req.body(), Message.class); if (StringUtils.isBlank(msg.getMessage()) || StringUtils.isBlank(msg.getName())) { halt(400); } manager.getTransaction().begin(); manager.persist(msg); manager.getTransaction().commit(); } catch (JsonSyntaxException e) { halt(400); } rsp.type("application/json"); return gson.toJson(streams.streamAll(manager, Message.class).collect(Collectors.toList())); }); get("/comments", (req, rsp) -> { rsp.type("application/json"); Map<String, List<Body>> body = new HashMap<>(); try (CloseableHttpClient client = create().build()) { String url = String.format("https://api.github.com/repos/%s/events", req.queryMap("repo").value()); log.info(url); body = client.execute(new HttpGet(url), r -> { List<Map<String, Object>> list = gson.fromJson(EntityUtils.toString(r.getEntity()), List.class); Map<String, List<Body>> result = new HashMap<>(); list.stream().filter(m -> m.getOrDefault("type", "").equals("IssueCommentEvent")) .map(m -> new Body(((Map<String, String>) m.get("actor")).get("login"), ((Map<String, Map<String, String>>) m.get("payload")).get("comment") .get("body"))) .forEach(b -> result.compute(b.getLogin(), (k, v) -> v == null ? new ArrayList<>() : Lists.asList(b, v.toArray(new Body[v.size()])))); return result; }); } catch (IOException e) { log.error(null, e); halt(400, e.getMessage()); } return gson.toJson(body); }); }
From source file:com.doculibre.constellio.services.SkosServicesImpl.java
public static void main(String[] args) throws Exception { SkosServices skosServices = ConstellioSpringUtils.getSkosServices(); File webinfDir = ClasspathUtils.getWebinfDir(); File skosDir = new File(webinfDir, "skos"); File tagSkosFile = new File(skosDir, "tagskos.rdf"); ProgressInfo progressInfo = new ProgressInfo(); Thesaurus thesaurus = skosServices.importThesaurus(new FileInputStream(tagSkosFile), progressInfo, new ArrayList<String>()); System.out.println(thesaurus.getDcTitle()); System.out.println(thesaurus.getDcDescription()); System.out.println(thesaurus.getDcCreator()); System.out.println(thesaurus.getDcDate()); System.out.println(thesaurus.getDcLanguage()); for (SkosConcept skosConcept : thesaurus.getTopConcepts()) { printNice(skosConcept);//from w ww. jav a 2 s.co m } EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager(); if (!entityManager.getTransaction().isActive()) { entityManager.getTransaction().begin(); } skosServices.makePersistent(thesaurus); entityManager.getTransaction().commit(); // // if (!entityManager.getTransaction().isActive()) { // entityManager.getTransaction().begin(); // } // skosServices.makeTransient(thesaurus); // entityManager.getTransaction().commit(); }
From source file:com.medicaid.mmis.util.DataLoader.java
/** * The main function, imports the files given as arguments. * /*from w ww . j ava 2 s. c o m*/ * @param args the file names * @throws IOException for read/write errors * @throws PortalServiceException for any other errors */ public static void main(String[] args) throws IOException, PortalServiceException { if (args.length != 2) { System.out.println("2 file path arguments are required."); return; } PropertyConfigurator.configure("log4j.properties"); logger = Logger.getLogger(DataLoader.class); LookupServiceBean lookupBean = new LookupServiceBean(); EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load"); EntityManager em = emf.createEntityManager(); lookupBean.setEm(em); DataLoader loader = new DataLoader(); loader.setLookup(lookupBean); SequenceGeneratorBean sequence = new SequenceGeneratorBean(); sequence.setEm(em); ProviderEnrollmentServiceBean enrollmentBean = new ProviderEnrollmentServiceBean(); enrollmentBean.setEm(em); enrollmentBean.setSequence(sequence); enrollmentBean.setLookupService(lookupBean); loader.setEnrollmentService(enrollmentBean); long processId = sequence.getNextValue("PROCESS_ID"); System.out.println("Started process id " + processId); BufferedReader br = null; PrintWriter accepted = null; PrintWriter rejected = null; try { System.out.println("Processing file 1..."); File success = new File("accepted_1_" + processId + ".txt"); File failure = new File("rejected_1_" + processId + ".txt"); success.createNewFile(); failure.createNewFile(); accepted = new PrintWriter(success); rejected = new PrintWriter(failure); br = new BufferedReader(new FileReader(args[0])); String line = null; int total = 0; int errors = 0; while ((line = br.readLine()) != null) { total++; try { em.getTransaction().begin(); loader.readProviderFile(new ByteArrayInputStream(line.getBytes())); em.getTransaction().commit(); accepted.println(line); logger.info("Commit row " + total); } catch (PortalServiceException e) { rejected.println(line); em.getTransaction().rollback(); errors++; logger.error("Rollback row " + total + " :" + e.getMessage()); } } accepted.flush(); accepted.close(); rejected.flush(); rejected.close(); br.close(); System.out.println("Total records read: " + total); System.out.println("Total rejected: " + errors); System.out.println("Processing file 2..."); success = new File("accepted_2_" + processId + ".txt"); failure = new File("rejected_2_" + processId + ".txt"); success.createNewFile(); failure.createNewFile(); accepted = new PrintWriter(success); rejected = new PrintWriter(failure); br = new BufferedReader(new FileReader(args[1])); line = null; total = 0; errors = 0; while ((line = br.readLine()) != null) { total++; try { em.getTransaction().begin(); Map<String, OwnershipInformation> owners = loader .readWS000EXT2OWNBEN(new ByteArrayInputStream(line.getBytes())); for (Map.Entry<String, OwnershipInformation> entry : owners.entrySet()) { enrollmentBean.addBeneficialOwners(entry.getKey(), entry.getValue()); } em.getTransaction().commit(); accepted.println(line); logger.info("Commit row " + total); } catch (PortalServiceException e) { rejected.println(line); em.getTransaction().rollback(); errors++; logger.error("Rollback row " + total + " :" + e.getMessage()); } } accepted.flush(); rejected.flush(); System.out.println("Total records read: " + total); System.out.println("Total rejected: " + errors); } finally { if (br != null) { br.close(); } if (accepted != null) { accepted.close(); } if (rejected != null) { rejected.close(); } } }
From source file:GestoreAccountLocale.GestoreAccountLocale.java
private static void memorizzaAccount(Account account) { EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("ClientMDBPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); try {//ww w . ja v a 2 s.c om em.persist(account); em.getTransaction().commit(); } catch (Exception e) { em.getTransaction().rollback(); } finally { em.close(); } }
From source file:com.chiralbehaviors.CoRE.kernel.KernelUtil.java
public static Kernel loadKernel(EntityManager em, InputStream is) throws IOException { em.getTransaction().begin(); RehydratedWorkspace workspace = rehydrateKernel(is); workspace.retarget(em);//w ww. j a va 2 s. c om Kernel kernel = workspace.getAccesor(Kernel.class); CACHED_KERNEL.set(kernel); em.getTransaction().commit(); workspace.detach(em); return kernel; }
From source file:au.org.ands.vocabs.toolkit.db.TaskUtils.java
/** Set the status and data fields for a task. * @param task The task being updated/* www . j av a 2 s . co m*/ * @param status The updated status information * @param response The updated response */ public static void setTaskStatusAndData(final Task task, final String status, final String response) { EntityManager em = DBContext.getEntityManager(); em.getTransaction().begin(); task.setStatus(status); task.setResponse(response); em.merge(task); em.getTransaction().commit(); em.close(); }
From source file:actors.SessionCleaner.java
public static boolean clean(WebSession session, boolean timedout, boolean forceCleanup) { if (session == null) { return false; }/*from w w w .j a v a2s . co m*/ Logger.info("deleting session " + UuidUtils.normalize(session.getId())); List<ProgressObserverToken> poTokens = ProgressObserverToken.find.where().eq("session", session).findList(); for (ProgressObserverToken poToken : poTokens) { poToken.delete(); } if (session.getStatus() == SessionStatus.ALIVE || forceCleanup) { session.setStatus(timedout ? SessionStatus.TIMEDOUT : SessionStatus.KILLED); session.update(); // if the session is not authenticated, delete all stores owned. if (!SessionedAction.isAuthenticated(session)) { EntityManager em = SareTransactionalAction.createEntityManager(); em.getTransaction().begin(); // delete all owned stores. for (String uuid : new PersistentDocumentStoreController().getAllUuids(em, UuidUtils.normalize(session.getId()))) { Logger.info("deleting store " + uuid + " owned by " + UuidUtils.normalize(session.getId())); PersistentDocumentStore store = em.find(PersistentDocumentStore.class, UuidUtils.toBytes(uuid)); if (store != null) { em.remove(store); } } em.getTransaction().commit(); em.close(); } } return true; }
From source file:org.opentides.dao.impl.AuditLogDaoImpl.java
/** * Saves the log event into the database. * @param shortMessage/* ww w .j av a 2s . c om*/ * @param message * @param entity */ public static void logEvent(String message, BaseEntity entity) { Long userId = entity.getAuditUserId(); String username = entity.getAuditUsername(); if (ApplicationStartupListener.isApplicationStarted()) { if (userId == null) { _log.error("No userId specified for audit logging on object [" + entity.getClass().getName() + "] for message [" + message + "]. Retrieving user from interceptor."); SessionUser user = SecurityUtil.getSessionUser(); userId = user.getId(); username = user.getUsername(); } } else { userId = new Long(0); username = "System Evolve"; } EntityManager em = DatabaseUtil.getEntityManager(); try { em.getTransaction().begin(); AuditLog record = new AuditLog(message, entity.getId(), entity.getClass(), entity.getReference(), userId, username); em.persist(record); em.flush(); em.getTransaction().commit(); } finally { if (em != null && em.isOpen()) { em.close(); } } }
From source file:com.enioka.jqm.test.helpers.TestHelpers.java
public static void setNodesLogLevel(String level, EntityManager em) { em.getTransaction().begin(); em.createQuery("UPDATE Node n set n.rootLogLevel = :l").setParameter("l", level).executeUpdate(); em.getTransaction().commit();// www . j ava 2s. co m }