List of usage examples for javax.persistence EntityManager find
public <T> T find(Class<T> entityClass, Object primaryKey);
From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationCollectionService.java
/** * Register a new application./*from w w w .j a va 2 s . co m*/ * * @param application The application to register * @return The registered application */ @POST @Status(Response.Status.CREATED) @Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE }) @Produces(Constants.INDIGOMIMETYPE) public final Application createApplication(final Application application) { if (application.getInfrastructureIds() == null || application.getInfrastructureIds().isEmpty()) { throw new BadRequestException(); } Date now = new Date(); application.setDateCreated(now); EntityManager em = getEntityManager(); EntityTransaction et = null; try { et = em.getTransaction(); et.begin(); List<Infrastructure> lstInfra = new LinkedList<>(); for (String infraId : application.getInfrastructureIds()) { Infrastructure infra = em.find(Infrastructure.class, infraId); if (infra == null) { throw new BadRequestException(); } lstInfra.add(infra); } application.setInfrastructures(lstInfra); em.persist(application); et.commit(); log.debug("New application registered: " + application.getId()); } catch (BadRequestException re) { throw re; } catch (RuntimeException re) { log.error("Impossible to create the application"); log.error(re); throw re; } finally { if (et != null && et.isActive()) { et.rollback(); } em.close(); } return application; }
From source file:nl.b3p.kaartenbalie.struts.WMSUrlCreatorAction.java
public void createLists(DynaValidatorForm form, HttpServletRequest request) throws JSONException, Exception { super.createLists(form, request); log.debug("Getting entity manager ......"); EntityManager em = getEntityManager(); User sesuser = (User) request.getUserPrincipal(); if (sesuser == null) { return;//from w ww . ja va 2 s . c o m } User user = (User) em.find(User.class, sesuser.getId()); if (user == null) { return; } form.set("personalUrl", user.getPersonalURL(request)); String bbox = (String) form.get("bbox"); if (bbox == null || bbox.length() == 0) { form.set("bbox", "12000,304000,280000,620000"); // heel nederland } String[] formats = new String[5]; formats[0] = "image/gif"; formats[1] = "image/png"; formats[2] = "image/jpeg"; formats[3] = "image/bmp"; formats[4] = "image/tiff"; request.setAttribute("formatList", formats); Set userLayers = user.getLayers(); JSONObject root = createTree("Kaartlagen", userLayers); request.setAttribute("layerList", root); LayerValidator lv = new LayerValidator(userLayers); String[] alSrsen = lv.validateSRS(); request.setAttribute("projectieList", alSrsen); }
From source file:org.noorganization.instalist.server.api.UnitResource.java
/** * Returns the unit.//from w w w . j a v a2 s . c o m * @param _groupId The croup containing the requested unit. * @param _unitUUID The uuid of the requested unit. */ @GET @TokenSecured @Path("{unituuid}") @Produces({ "application/json" }) public Response getUnit(@PathParam("groupid") int _groupId, @PathParam("unituuid") String _unitUUID) throws Exception { try { UUID toFind; try { toFind = UUID.fromString(_unitUUID); } catch (IllegalArgumentException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID); } EntityManager manager = DatabaseHelper.getInstance().getManager(); IUnitController unitController = ControllerFactory.getUnitController(manager); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); Unit resultUnit = unitController.findByGroupAndUUID(group, toFind); if (resultUnit == null) { if (unitController.findDeletedByGroupAndUUID(group, toFind) == null) { manager.close(); return ResponseFactory .generateNotFound(new Error().withMessage("The requested " + "unit was not found.")); } manager.close(); return ResponseFactory .generateGone(new Error().withMessage("The requested unit has " + "been deleted.")); } manager.close(); UnitInfo rtn = new UnitInfo().withDeleted(false); rtn.setName(resultUnit.getName()); rtn.setUUID(resultUnit.getUUID()); rtn.setLastChanged(Date.from(resultUnit.getUpdated())); return ResponseFactory.generateOK(rtn); } catch (Exception _e) { _e.printStackTrace(); throw _e; } }
From source file:org.apache.juddi.validation.ValidateSubscription.java
private void validateSubscriptionBindingkeyExists(EntityManager em, String bindingKey) throws ValueNotAllowedException { if (bindingKey == null || bindingKey.length() == 0) { return;//w w w.j a va 2 s .co m } Object obj = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey); if (obj == null) { throw new ValueNotAllowedException( new ErrorMessage("errors.subscription.BindingDoesntExist", bindingKey)); } }
From source file:com.gigglinggnus.controllers.ManageExamsController.java
/** * * @param request servlet request/*from w w w . j a va2s .co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = (EntityManager) request.getSession().getAttribute("em"); String examId = request.getParameter("examid"); String status = request.getParameter("status"); Clock clk = (Clock) (request.getSession().getAttribute("clock")); User user = (User) (request.getSession().getAttribute("user")); Exam exam = em.find(Exam.class, examId); try { em.getTransaction().begin(); } catch (Exception e) { } try { if (status.equals("approved")) { user.changeExamStatus(exam, ExamStatus.APPROVED); em.persist(exam); em.getTransaction().commit(); request.setAttribute("msg", "Exam APPROVED"); } else if (status.equals("denied")) { user.changeExamStatus(exam, ExamStatus.DENIED); em.persist(exam); em.getTransaction().commit(); request.setAttribute("msg", "Exam Denied"); } else { request.setAttribute("msg", "Invalid status"); } } catch (Exception e) { em.getTransaction().rollback(); request.setAttribute("msg", e.toString()); throw e; } RequestDispatcher rd = request.getRequestDispatcher("/home.jsp"); rd.forward(request, response); }
From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java
@Override public Properties getEventMetadata(long eventId) throws NotFoundException, SchedulerServiceDatabaseException { EntityManager em = null; try {//from w ww .j ava2s . c om em = emf.createEntityManager(); EventEntity entity = em.find(EventEntity.class, eventId); if (entity == null) { throw new NotFoundException("Could not found series with ID " + eventId); } Properties caProperties = null; if (entity.getCaptureAgentMetadata() != null) { caProperties = parseProperties(entity.getCaptureAgentMetadata()); } return caProperties; } catch (NotFoundException e) { throw e; } catch (Exception e) { logger.error("Could not retrieve CA properties for event '{}': {}", eventId, e.getMessage()); throw new SchedulerServiceDatabaseException(e); } finally { if (em != null) em.close(); } }
From source file:org.rhq.enterprise.server.content.test.ContentUIManagerBeanEligiblePackagesTest.java
private void setupTestEnvironment() throws Exception { getTransactionManager().begin();//ww w .java 2 s .c om EntityManager em = getEntityManager(); try { try { architecture = em.find(Architecture.class, 1); resourceType = new ResourceType("resourcetype-" + System.currentTimeMillis(), "TestPlugin", ResourceCategory.PLATFORM, null); em.persist(resourceType); // Create resource against which we'll be retrieving packages resource = new Resource("parent" + System.currentTimeMillis(), "name", resourceType); resource.setUuid("" + new Random().nextInt()); resource.setVersion("1.0"); em.persist(resource); // Product versions productVersion1 = new ProductVersion(); productVersion1.setVersion("1.0"); productVersion1.setResourceType(resourceType); em.persist(productVersion1); resource.setProductVersion(productVersion1); productVersion2 = new ProductVersion(); productVersion2.setVersion("2.0"); productVersion2.setResourceType(resourceType); em.persist(productVersion2); // Add package types to resource type packageType1 = new PackageType(); packageType1.setName("package1-" + System.currentTimeMillis()); packageType1.setDescription(""); packageType1.setCategory(PackageCategory.DEPLOYABLE); packageType1.setDisplayName("TestResourcePackage"); packageType1.setCreationData(true); packageType1.setResourceType(resourceType); em.persist(packageType1); resourceType.addPackageType(packageType1); // Package 1 - No product versions specified package1 = new Package("Package1", packageType1); PackageVersion packageVersion1 = new PackageVersion(package1, "1.0.0", architecture); package1.addVersion(packageVersion1); em.persist(package1); // Package 2 - Has list of product versions that contains the resource's version package2 = new Package("Package2", packageType1); PackageVersion packageVersion2 = new PackageVersion(package2, "1.0.0", architecture); ProductVersionPackageVersion pvpv1 = packageVersion2.addProductVersion(productVersion1); ProductVersionPackageVersion pvpv2 = packageVersion2.addProductVersion(productVersion2); package2.addVersion(packageVersion2); em.persist(package2); em.persist(pvpv1); em.persist(pvpv2); // Package 3 - Has list of product versions where the resource version is not included package3 = new Package("Package3", packageType1); PackageVersion packageVersion3 = new PackageVersion(package3, "1.0.0", architecture); ProductVersionPackageVersion pvpv3 = packageVersion3.addProductVersion(productVersion2); package3.addVersion(packageVersion3); em.persist(package3); em.persist(pvpv3); // Package 4 - No product version restriction, but already installed on the resource package4 = new Package("Package4", packageType1); PackageVersion packageVersion4 = new PackageVersion(package4, "1.0.0", architecture); package4.addVersion(packageVersion4); em.persist(package4); // Wire up the repo to the resource and add all of these packages to it repo1 = new Repo("repo-" + RandomStringUtils.randomNumeric(6)); em.persist(repo1); repoPackageVersion1 = repo1.addPackageVersion(packageVersion1); repoPackageVersion2 = repo1.addPackageVersion(packageVersion2); repoPackageVersion3 = repo1.addPackageVersion(packageVersion3); repoPackageVersion4 = repo1.addPackageVersion(packageVersion4); em.persist(repoPackageVersion1); em.persist(repoPackageVersion2); em.persist(repoPackageVersion3); em.persist(repoPackageVersion4); resourceRepo1 = repo1.addResource(resource); em.persist(resourceRepo1); // Subscribe the resource to a second repo to make sure the joins won't duplicate stuff repo2 = new Repo("test-" + RandomStringUtils.randomNumeric(6)); em.persist(repo2); resourceRepo2 = repo2.addResource(resource); em.persist(resourceRepo2); installedPackage1 = new InstalledPackage(); installedPackage1.setResource(resource); installedPackage1.setPackageVersion(packageVersion4); resource.addInstalledPackage(installedPackage1); getTransactionManager().commit(); } catch (Exception e) { e.printStackTrace(); getTransactionManager().rollback(); throw e; } } finally { em.close(); } }
From source file:org.opencastproject.adminui.usersettings.UserSettingsService.java
/** * Delete a user setting by using a unique id to find it. * * @param id/*from w w w. j av a 2 s .com*/ * The unique id for the user setting. * @throws UserSettingsServiceException */ public void deleteUserSetting(long id) throws UserSettingsServiceException { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); UserSettingDto userSettingsDto = em.find(UserSettingDto.class, id); tx = em.getTransaction(); tx.begin(); em.remove(userSettingsDto); tx.commit(); } catch (Exception e) { logger.error("Could not delete user setting '%d': %s", id, ExceptionUtils.getStackTrace(e)); if (tx.isActive()) tx.rollback(); throw new UserSettingsServiceException(e); } finally { if (em != null) em.close(); } }
From source file:com.olp.jpa.domain.docu.ut.repo.EmployeeRepositoryImpl.java
@Override @Transactional//from w w w .j a v a 2s . c om public EmployeeBean createEmployee(EmployeeBean employee, DepartmentBean dept, EmployeeBean manager) { save(employee); EntityManager em = getEntityManager(); if (dept != null) { /* if (em.contains(dept)) { employee.setCurrentDept(dept); dept.getEmployees().add(employee); } else { DepartmentBean dept2 = em.merge(dept); employee.setCurrentDept(dept2); dept2.getEmployees().add(employee); } */ dept = em.find(DepartmentBean.class, dept.getId()); employee.setDepartmentRef(dept); dept.getEmployees().add(employee); } return (employee); }