List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:cz.fi.muni.pa165.daoImpl.TroopDAOImpl.java
@Override public void removeTroop(Troop troop) throws IllegalArgumentException { if (troop == null) { throw new IllegalArgumentException("Troop can't be null."); }//from w ww.j a v a 2 s. c o m if (troop.getId() == null) { throw new IllegalArgumentException("Troop is not present in DB."); } EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Troop present = em.find(Troop.class, troop.getId()); em.getTransaction().commit(); if (present == null) { throw new IllegalArgumentException("Troop is not present in DB."); } else { em.getTransaction().begin(); em.remove(em.contains(troop) ? troop : em.merge(troop)); em.getTransaction().commit(); } em.close(); }
From source file:org.apache.falcon.service.FalconJPAService.java
@Override public void init() throws FalconException { Properties props = getPropsforStore(); entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit, props); EntityManager entityManager = getEntityManager(); entityManager.find(EntityBean.class, 1); entityManager.find(InstanceBean.class, 1); LOG.info("All entities initialized"); // need to use a pseudo no-op transaction so all entities, datasource // and connection pool are initialized one time only entityManager.getTransaction().begin(); OpenJPAEntityManagerFactorySPI spi = (OpenJPAEntityManagerFactorySPI) entityManagerFactory; // Mask the password with '***' String logMsg = spi.getConfiguration().getConnectionProperties().replaceAll("Password=.*?,", "Password=***,"); LOG.info("JPA configuration: {0}", logMsg); entityManager.getTransaction().commit(); entityManager.close();/*from w w w. j ava2s. co m*/ }
From source file:org.viafirma.persistencia.dao.GenericEjb3Dao.java
/** * Recupera el objeto con el identificador indicado * @throws ExcepcionNoEncontrado Cuando no se puede recuperar la indentidad con el identificador indicado *//* w w w. j av a 2 s . c om*/ public T findById(ID id) throws ExcepcionNoEncontrado { EntityManager manager = getEntityManager(); try { T entidad = manager.find(persistentClass, id); if (entidad == null) { throw new ExcepcionNoEncontrado(CodigoError.ERROR_IDENTIFICADOR_NO_ENCONTRADO); } return entidad; } finally { manager.close(); } }
From source file:com.romb.hashfon.helper.Helper.java
public boolean isStudentLogged(String[] token) { try {/*w w w. ja va2s. com*/ EntityManager em = getEntityManager(); if (token[1].equals("STUDENT")) { Student s = em.find(Student.class, Long.parseLong(token[2])); return s != null; } else { return false; } } catch (Exception e) { return false; } }
From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureService.java
/** * Removes the infrastructure. Delete the infrastructure only if there are * not applications associated with it to avoid inconsistency in the DB. * <p>/*from ww w. j a va 2s . c o m*/ * Infrastructures with associated applications can only be disabled to * avoid future execution of applications. * * @param id Id of the infrastructure to remove */ @DELETE public final void deleteInfra(@PathParam("id") final String id) { Infrastructure infra; EntityManager em = getEntityManager(); try { infra = em.find(Infrastructure.class, id); if (infra == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure") .setParameter("infraId", id).setMaxResults(1).getResultList(); if (appsForInfra == null || appsForInfra.isEmpty()) { em.remove(infra); } else { throw new WebApplicationException("The infrastructure " + "cannot be removed because there are associated " + "applications", Response.Status.CONFLICT); } et.commit(); } catch (WebApplicationException wex) { throw wex; } catch (RuntimeException re) { log.error(re); log.error("Impossible to remove the infrastructure"); throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id); } finally { if (et != null && et.isActive()) { et.rollback(); } } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the infrastructure list"); log.error(re); throw new BadRequestException("Task '" + id + "' does not exist!"); } finally { em.close(); } }
From source file:com.romb.hashfon.helper.Helper.java
public boolean isLogged(String[] token) { try {//from w w w . j a v a 2 s . co m EntityManager em = getEntityManager(); if (token[1].equals("STUDENT")) { Student s = em.find(Student.class, Long.parseLong(token[2])); return s != null; } else { Hr hr = (Hr) em.createNamedQuery("Hr.findById").setParameter("id", Long.parseLong(token[2])) .getSingleResult(); return hr != null; } } catch (Exception e) { return false; } }
From source file:it.drwolf.ridire.cleaners.ReadabilityCleaner.java
public String getCleanedTextFromString(CrawledResource crawledResource, StringWithEncoding rawContentAndEncoding, EntityManager entityManager) { String bookmarkJS = entityManager.find(Parameter.class, Parameter.READABILITY_SOURCE.getKey()).getValue(); String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue(); bookmarkJS = bookmarkJS.replaceAll("@@@HOST@@@", host.trim()); WebClient webClient = new WebClient(); webClient = new WebClient(BrowserVersion.FIREFOX_3); webClient.setCssEnabled(true);/*from w ww.j ava 2 s . c o m*/ webClient.setJavaScriptEnabled(true); // vedi FAQ: http://htmlunit.sourceforge.net/faq.html#AJAXDoesNotWork webClient.setAjaxController(new NicelyResynchronizingAjaxController()); webClient.waitForBackgroundJavaScript(5000); webClient.waitForBackgroundJavaScriptStartingBefore(5000); // i seguenti 4 set servono per limitare i log webClient.setHTMLParserListener(null); webClient.setIncorrectnessListener(new NoOpIncorrectnessListener()); webClient.setCssErrorHandler(new NoOpErrorHandler()); webClient.setPrintContentOnFailingStatusCode(false); // questo serve per avere il tipo di errore HTTP webClient.setThrowExceptionOnFailingStatusCode(true); webClient.setThrowExceptionOnScriptError(false); webClient.setRefreshHandler(new ThreadedRefreshHandler()); // webClient.setJavaScriptTimeout(4000); webClient.setTimeout(4000); File tmpFile = null; HtmlPage htmlPage = null; String ret = new String(); try { tmpFile = File.createTempFile("readability", null); FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString()); htmlPage = webClient.getPage(host.trim() + "/tmp/resource.seam?filename=" + tmpFile.getName()); FileUtils.deleteQuietly(tmpFile); if (htmlPage != null) { // webClient.setJavaScriptEnabled(false); ScriptResult scriptResult = htmlPage.executeJavaScript(bookmarkJS); // System.out.println(htmlPage.asXml()); for (HtmlElement he : htmlPage.getElementsByName("div")) { // System.out.println("-->" + he.getAttribute("id") + // "<--"); // System.out.println(he.asText()); } HtmlElement element = htmlPage.getElementById("readability-content"); if (element != null) { ret = element.asText(); } } if (tmpFile != null) { FileUtils.deleteQuietly(tmpFile); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RuntimeException re) { // TODO: handle exception re.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } finally { webClient.closeAllWindows(); } return ret.trim(); }
From source file:com.epam.training.taranovski.web.project.repository.implementation.AdminRepositoryImplementation.java
@Override public Admin getById(int id) { EntityManager em = entityManagerFactory.createEntityManager(); Admin admin;/*from w w w . ja va 2 s .c o m*/ try { em.getTransaction().begin(); admin = em.find(Admin.class, id); em.getTransaction().commit(); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return admin; }
From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java
/** * Removes the application. Delete the application only if there are not * tasks associated with it because tasks must be associated with an * application.//from w w w . ja v a 2 s.co m * <p> * Applications with associated tasks can only be disabled to avoid future * execution of new tasks. Nevertheless, a task can be associated with a * disabled application and in this case will stay waiting until the * application is enabled. * * @param id Id of the application to remove */ @DELETE public final void deleteApp(@PathParam("id") final String id) { Application app; EntityManager em = getEntityManager(); try { app = em.find(Application.class, id); if (app == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id) .setMaxResults(1).getResultList(); if (taskForApp == null || taskForApp.isEmpty()) { em.remove(app); } else { log.info("Application " + id + " has tasks and cannot be" + " deleted"); throw new WebApplicationException( "The application cannot " + "be removed because there are associated tasks", Response.Status.CONFLICT); } et.commit(); } catch (WebApplicationException wex) { throw wex; } catch (RuntimeException re) { log.error(re); log.error("Impossible to remove the application"); throw new InternalServerErrorException("Error to remove " + "the application " + id); } finally { if (et != null && et.isActive()) { et.rollback(); } } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the application list"); log.error(re); throw new BadRequestException("Application '" + id + "' " + "does not exist!"); } finally { em.close(); } }
From source file:net.anthonychaves.bookmarks.service.UserService.java
public User deleteBookmark(User user, String bookmarkId) { EntityManager em = emf.createEntityManager(); em.getTransaction().begin();//ww w . j a v a 2 s . c o m Bookmark bookmark = (Bookmark) em.find(Bookmark.class, bookmarkId); if (user.getId() != bookmark.getUser().getId()) { throw new RuntimeException("user ids don't match when deleting a bookmark"); } user = (User) em.find(User.class, user.getId()); user.getBookmarks().remove(bookmark); em.remove(bookmark); em.getTransaction().commit(); return user; }