Java Code Examples for javax.persistence.EntityManager

The following are top voted examples for showing how to use javax.persistence.EntityManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Pet-Supply-Store   File: OrderRepository.java   View source code 7 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean updateEntity(long id, Order entity) {
	boolean found = false;
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceOrder order = em.find(getEntityClass(), id);
        if (order != null) {
        	order.setTime(entity.getTime());
    		order.setTotalPriceInCents(entity.getTotalPriceInCents());
    		order.setAddressName(entity.getAddressName());
    		order.setAddress1(entity.getAddress1());
    		order.setAddress2(entity.getAddress2());
    		order.setCreditCardCompany(entity.getCreditCardCompany());
    		order.setCreditCardNumber(entity.getCreditCardNumber());
    		order.setCreditCardExpiryDate(entity.getCreditCardExpiryDate());
        	found = true;
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return found;
}
 
Example 2
Project: OperatieBRP   File: CustomJpaRepositoryFactory.java   View source code 7 votes vote down vote up
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
protected SimpleJpaRepository<?, ?> getTargetRepository(
        final RepositoryMetadata metadata,
        final EntityManager entityManager) {
    final Class<?> repositoryInterface = metadata.getRepositoryInterface();
    final JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());

    if (isQueryDslSpecificExecutor(repositoryInterface)) {
        throw new IllegalArgumentException("QueryDSL interface niet toegestaan");
    }

    return isMaxedRepository(repositoryInterface)
            ? new CustomSimpleMaxedJpaRepository(entityInformation, entityManager)
            : isQuerycostRepository(repositoryInterface)
                    ? new CustomSimpleQuerycostJpaRepository(entityInformation, entityManager, maxCostsQueryPlan)
                    : new CustomSimpleJpaRepository(entityInformation, entityManager);
}
 
Example 3
Project: Mod-Tools   File: ZipContentParserTest.java   View source code 6 votes vote down vote up
/**
 * Test of handle method, of class ZipContentParser.
 */
@Test
public void testHandle() {
    System.out.println("handle");
    try {
        EntityManager manager = new PersistenceProvider().get();
        if(!manager.getTransaction().isActive()) {
            manager.getTransaction().begin();
        }
        manager.persist(new Modification("ZipContentParserTest.mod",31));
        manager.getTransaction().commit();
        IOUtils.copy(getClass().getResourceAsStream("/test.zip"), FileUtils.openOutputStream(new File(getAllowedFolder()+"/a.zip")));
        List <ProcessTask> result = get().handle(manager);
        Assert.assertTrue(
            "result is not of correct type",
            result instanceof List<?>
        );
        Assert.assertEquals(
            "Unexpected follow-ups",
            0,
            result.size()
        );
    } catch(Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
 
Example 4
Project: osc-core   File: ForceDeleteDSTask.java   View source code 6 votes vote down vote up
@Override
public void executeTransaction(EntityManager em) {
    log.info("Force Deleting Deployment Specification: " + this.ds.getName());
    // load deployment spec from database to avoid lazy loading issues
    this.ds = DeploymentSpecEntityMgr.findById(em, this.ds.getId());

    // remove DAI(s) for this ds
    for (DistributedApplianceInstance dai : this.ds.getDistributedApplianceInstances()) {
        dai.getProtectedPorts().clear();
        OSCEntityManager.delete(em, dai, this.txBroadcastUtil);
    }

    // remove the sg reference from database
    if (this.ds.getVirtualSystem().getVirtualizationConnector().getVirtualizationType().isOpenstack()) {
        boolean osSgCanBeDeleted = DeploymentSpecEntityMgr.findDeploymentSpecsByVirtualSystemProjectAndRegion(em,
                this.ds.getVirtualSystem(), this.ds.getProjectId(), this.ds.getRegion()).size() <= 1;

        if (osSgCanBeDeleted && this.ds.getOsSecurityGroupReference() != null) {
            OSCEntityManager.delete(em, this.ds.getOsSecurityGroupReference(), this.txBroadcastUtil);
        }
    }

    // delete DS from the database
    OSCEntityManager.delete(em, this.ds, this.txBroadcastUtil);
}
 
Example 5
Project: bibliometrics   File: UserDAO.java   View source code 6 votes vote down vote up
public static User getUser(String username) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
    EntityManager em = emf.createEntityManager();
	EntityTransaction tx = em.getTransaction();
	tx.begin();
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<User> q = cb.createQuery(User.class);
	Root<User> c = q.from(User.class);
	q.select(c).where(cb.equal(c.get("username"), username));
	TypedQuery<User> query = em.createQuery(q);
	List<User> users = query.getResultList();
	em.close();
	LOGGER.info("found " + users.size() + " users with username " + username);
	if (users.size() == 1)
		return users.get(0);
	else
		return null;
}
 
Example 6
Project: osc-core   File: ListJobService.java   View source code 6 votes vote down vote up
@Override
public ListResponse<JobRecordDto> exec(ListJobRequest request, EntityManager em) throws Exception {
    ListResponse<JobRecordDto> response = new ListResponse<JobRecordDto>();

    // Initializing Entity Manager
    OSCEntityManager<JobRecord> emgr = new OSCEntityManager<JobRecord>(JobRecord.class, em, this.txBroadcastUtil);
    // to do mapping

    List<JobRecordDto> dtoList = new ArrayList<JobRecordDto>();

    // mapping all the job objects to job dto objects
    for (JobRecord j : emgr.listAll(false, "id")) {
        JobRecordDto dto = new JobRecordDto();
        JobEntityManager.fromEntity(j, dto);
        dtoList.add(dto);
    }

    response.setList(dtoList);
    return response;
}
 
Example 7
Project: comms-router   File: CoreTaskService.java   View source code 6 votes vote down vote up
private void cancelTask(EntityManager em, RouterObjectRef taskRef)
    throws NotFoundException, InvalidStateException {

  Task task = app.db.task.get(em, taskRef);

  switch (task.getState()) {
    case waiting:
      assert task.getAgent() == null : "Waiting task " + task.getRef() + " has assigned agent: "
          + task.getAgent().getRef();
      task.makeCanceled();
      return;
    case canceled:
      throw new InvalidStateException("Task already canceled");
    case assigned:
    case completed:
    default:
      throw new InvalidStateException(
          "Current state cannot be switched to canceled: " + task.getState());
  }
}
 
Example 8
Project: full-javaee-app   File: ClientPipelineDataAccessObject.java   View source code 6 votes vote down vote up
public static ClientPipelines persist (ClientPipelines elt) {
    if (elt != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(elt);
            trans.commit();
            return elt;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        }
    }
    return null;
}
 
Example 9
Project: aries-jpa   File: TaskServiceImplTest.java   View source code 6 votes vote down vote up
@Test
public void testPersistence() {
    // Make sure derby.log is in target
    System.setProperty("derby.stream.error.file", "target/derby.log");
    TaskServiceImpl taskServiceImpl = new TaskServiceImpl();
    EntityManagerFactory emf = createTestEMF();
    final EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    taskServiceImpl.em = em;

    TaskService taskService = taskServiceImpl;

    Task task = new Task();
    task.setId(1);
    task.setTitle("test");
    taskService.addTask(task);

    Task task2 = taskService.getTask(1);
    Assert.assertEquals(task.getTitle(), task2.getTitle());
    em.getTransaction().commit();
    em.close();
}
 
Example 10
Project: full-javaee-app   File: CompanyDataAccessObject.java   View source code 6 votes vote down vote up
public static Companies persist(Companies company) {
    if (company != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(company);
            trans.commit();
            return company;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
            return null;
        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 11
Project: osc-core   File: SecurityGroupEntityMgr.java   View source code 6 votes vote down vote up
public static SecurityGroup listSecurityGroupsByVcIdAndMgrId(EntityManager em, Long vcId, String mgrId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    query = query.select(root)
            .where(cb.equal(root.join("virtualizationConnector").get("id"), vcId),
                    cb.equal(root.join("securityGroupInterfaces").get("mgrSecurityGroupId"), mgrId))
            .orderBy(cb.asc(root.get("name")));

    try {
        return em.createQuery(query).getSingleResult();
    } catch (NoResultException nre) {
        return null;
    }
}
 
Example 12
Project: SqlSauce   File: DatabaseWrapper.java   View source code 6 votes vote down vote up
/**
 * Use this for COUNT() and similar sql queries which are guaranteed to return a result
 */
@Nonnull
@CheckReturnValue
public <T> T selectSqlQuerySingleResult(@Nonnull final String queryString,
                                        @Nullable final Map<String, Object> parameters,
                                        @Nonnull final Class<T> resultClass) throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        final Query q = em.createNativeQuery(queryString);
        if (parameters != null) {
            parameters.forEach(q::setParameter);
        }
        em.getTransaction().begin();
        final T result = resultClass.cast(q.getSingleResult());
        em.getTransaction().commit();
        return setSauce(result);
    } catch (final PersistenceException | ClassCastException e) {
        final String message = String.format("Failed to select single result plain SQL query %s with %s parameters for class %s on DB %s",
                queryString, parameters != null ? parameters.size() : "null", resultClass.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 13
Project: osc-core   File: VmPortHookFailurePolicyUpdateTask.java   View source code 6 votes vote down vote up
@Override
public void executeTransaction(EntityManager em) throws Exception {

    this.vmPort = em.find(VMPort.class, this.vmPort.getId());
    this.dai = em.find(DistributedApplianceInstance.class, this.dai.getId());
    this.securityGroupInterface = em.find(SecurityGroupInterface.class,
            this.securityGroupInterface.getId());

    SdnRedirectionApi controller = this.apiFactoryService.createNetworkRedirectionApi(this.dai);
    try {
        DefaultNetworkPort ingressPort = new DefaultNetworkPort(this.dai.getInspectionOsIngressPortId(),
                this.dai.getInspectionIngressMacAddress());
        DefaultNetworkPort egressPort = new DefaultNetworkPort(this.dai.getInspectionOsEgressPortId(),
                this.dai.getInspectionEgressMacAddress());
        //Element object in DefaultInspectionPort is not used, hence null
        controller.setInspectionHookFailurePolicy(new NetworkElementImpl(this.vmPort), new DefaultInspectionPort(ingressPort, egressPort, null),
                FailurePolicyType.valueOf(this.securityGroupInterface.getFailurePolicyType().name()));
    } finally {
        controller.close();
    }
}
 
Example 14
Project: SqlSauce   File: DatabaseWrapper.java   View source code 6 votes vote down vote up
/**
 * @return The managed version of the provided entity (with set autogenerated values for example).
 */
@Nonnull
@CheckReturnValue
//returns a sauced entity
public <E extends SaucedEntity<I, E>, I extends Serializable> E merge(@Nonnull final E entity)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        em.getTransaction().begin();
        final E managedEntity = em.merge(entity);
        em.getTransaction().commit();
        return managedEntity
                .setSauce(this);
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to merge entity %s on DB %s",
                entity.toString(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 15
Project: holon-datastore-jpa   File: DefaultJpaDatastore.java   View source code 6 votes vote down vote up
/**
 * Set the entity id values of given <code>entity</code> instance to be returned as an {@link OperationResult}.
 * @param result OperationResult in which to set the ids
 * @param entityManager EntityManager
 * @param set Entity bean property set
 * @param entity Entity class
 * @param instance Entity instance
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void setInsertedIds(OperationResult.Builder result, EntityManager entityManager,
		BeanPropertySet<Object> set, Class<?> entity, Object instance, boolean bringBackGeneratedIds,
		PropertyBox propertyBox) {
	try {
		getIds(entityManager, set, entity).forEach(p -> {
			Object keyValue = set.read(p, instance);
			result.withInsertedKey(p, keyValue);
			if (bringBackGeneratedIds && keyValue != null) {
				// set in propertybox
				Property property = getPropertyForPath(p, propertyBox);
				if (property != null) {
					propertyBox.setValue(property, keyValue);
				}
			}
		});
	} catch (Exception e) {
		LOGGER.warn("Failed to obtain entity id(s) value", e);
	}
}
 
Example 16
Project: SqlSauce   File: DatabaseWrapper.java   View source code 6 votes vote down vote up
public <E extends IEntity<I, E>, I extends Serializable> void deleteEntity(@Nonnull final EntityKey<I, E> entityKey)
        throws DatabaseException {
    final EntityManager em = this.databaseConnection.getEntityManager();
    try {
        em.getTransaction().begin();
        final IEntity<I, E> entity = em.find(entityKey.clazz, entityKey.id);
        if (entity != null) {
            em.remove(entity);
        }
        em.getTransaction().commit();
    } catch (final PersistenceException e) {
        final String message = String.format("Failed to delete entity id %s of class %s on DB %s",
                entityKey.id.toString(), entityKey.clazz.getName(), this.databaseConnection.getName());
        throw new DatabaseException(message, e);
    } finally {
        em.close();
    }
}
 
Example 17
Project: osc-core   File: ListAlertService.java   View source code 6 votes vote down vote up
@Override
public ListResponse<AlertDto> exec(BaseRequest<BaseDto> request, EntityManager em) throws Exception {

    // Initializing Entity Manager
    OSCEntityManager<Alert> emgr = new OSCEntityManager<Alert>(Alert.class, em, this.txBroadcastUtil);

    List<AlertDto> alertList = new ArrayList<AlertDto>();

    for (Alert alert : emgr.listAll(false, "createdTimestamp")) {
        AlertDto dto = new AlertDto();
        AlertEntityMgr.fromEntity(alert, dto);
        alertList.add(dto);
    }
    ListResponse<AlertDto> response = new ListResponse<AlertDto>();
    response.setList(alertList);
    return response;
}
 
Example 18
Project: full-javaee-app   File: ConversationDataAccessObject.java   View source code 6 votes vote down vote up
public static boolean delete(int conversationID) {
    if (conversationID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        Conversations conversation = em.find(Conversations.class, conversationID);
        if (conversation != null) {
            EntityTransaction trans = em.getTransaction();
            try {
                trans.begin();
                em.remove(conversation);
                trans.commit();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                trans.rollback();
            } finally {
                em.close();
            }
        }
    }
    return false;
}
 
Example 19
Project: osc-core   File: CheckK8sSecurityGroupLabelMetaTaskTestData.java   View source code 6 votes vote down vote up
public static void persist(SecurityGroupMember sgm, EntityManager em) {
    SecurityGroup sg = sgm.getSecurityGroup();
    em.getTransaction().begin();

    Set<VirtualSystem> virtualSystems = sg.getVirtualizationConnector().getVirtualSystems();
    em.persist(sg.getVirtualizationConnector());

    for (VirtualSystem vs : virtualSystems) {
        em.persist(vs.getDomain().getApplianceManagerConnector());
        em.persist(vs.getApplianceSoftwareVersion().getAppliance());
        em.persist(vs.getApplianceSoftwareVersion());
        em.persist(vs.getDistributedAppliance());
        em.persist(vs.getDomain());
        em.persist(vs);
    }

    em.persist(sgm.getLabel());
    em.persist(sg);
    em.persist(sgm);

    em.getTransaction().commit();
}
 
Example 20
Project: Pet-Supply-Store   File: OrderItemRepository.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public long createEntity(OrderItem entity) {
	PersistenceOrderItem item = new PersistenceOrderItem();
	item.setQuantity(entity.getQuantity());
	item.setUnitPriceInCents(entity.getUnitPriceInCents());
	EntityManager em = getEM();
    try {
        em.getTransaction().begin();
        PersistenceProduct prod = em.find(PersistenceProduct.class, entity.getProductId());
        PersistenceOrder order = em.find(PersistenceOrder.class, entity.getOrderId());
        if (prod != null && order != null) {
        	item.setProduct(prod);
        	item.setOrder(order);
        	em.persist(item);
        } else {
        	item.setId(-1L);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
    return item.getId();
}
 
Example 21
Project: osc-core   File: ValidateSecurityGroupProjectTask.java   View source code 6 votes vote down vote up
@Override
public void executeTransaction(EntityManager em) throws Exception {
    OSCEntityManager<SecurityGroup> sgEmgr = new OSCEntityManager<SecurityGroup>(SecurityGroup.class, em, this.txBroadcastUtil);
    this.securityGroup = sgEmgr.findByPrimaryKey(this.securityGroup.getId());

    this.log.info("Validating the Security Group project " + this.securityGroup.getProjectName() + " exists.");
    try (Openstack4jKeystone keystone = new Openstack4jKeystone(new Endpoint(this.securityGroup.getVirtualizationConnector()))) {
        Project project = keystone.getProjectById(this.securityGroup.getProjectId());
        if (project == null) {
            this.log.info("Security Group project " + this.securityGroup.getProjectName() + " Deleted from openstack. Marking Security Group for deletion.");
            // project was deleted, mark Security Group for deleting as well
            OSCEntityManager.markDeleted(em, this.securityGroup, this.txBroadcastUtil);
        } else {
            // Sync the project name if needed
            if (!project.getName().equals(this.securityGroup.getProjectName())) {
                this.log.info("Security Group project name updated from " + this.securityGroup.getProjectName() + " to " + project.getName());
                this.securityGroup.setProjectName(project.getName());
                OSCEntityManager.update(em, this.securityGroup, this.txBroadcastUtil);
            }
        }
    }
}
 
Example 22
Project: osc-core   File: OsProjectNotificationListener.java   View source code 5 votes vote down vote up
private void handleSGMessages(EntityManager em, String keyValue) throws Exception {
    // if Project deleted belongs to a security group
    for (SecurityGroup securityGroup : SecurityGroupEntityMgr.listByProjectId(em, keyValue)) {
        // trigger sync job for that SG
        if (securityGroup.getId().equals(((SecurityGroup) this.entity).getId())) {
            this.sgConformJobFactory.startSecurityGroupConformanceJob(securityGroup);
        }
    }
}
 
Example 23
Project: osc-core   File: ListSslCertificatesService.java   View source code 5 votes vote down vote up
@Override
protected ListResponse<CertificateBasicInfoModel> exec(BaseRequest<BaseDto> request, EntityManager em) throws Exception {
    List<CertificateBasicInfoModel> certificateInfoList = X509TrustManagerFactory.getInstance().getCertificateInfoList();

    SslCertificateAttrEntityMgr sslCertificateAttrEntityMgr = new SslCertificateAttrEntityMgr(em, this.txBroadcastUtil);
    List<SslCertificateAttrDto> sslEntriesList = sslCertificateAttrEntityMgr.getSslEntriesList();

    for (CertificateBasicInfoModel cim : certificateInfoList) {
        cim.setConnected(isConnected(sslEntriesList, cim.getAlias()));
    }

    return new ListResponse<>(certificateInfoList);
}
 
Example 24
Project: bdf2   File: JpaEntityManagerRepository.java   View source code 5 votes vote down vote up
public EntityManager getEntityManager(String dataSourceName){
	if(dataSourceName==null){
		return getEntityManager();
	}else{
		if(entityManagerMap.containsKey(dataSourceName)){
			return entityManagerMap.get(dataSourceName);
		}else{
			return getEntityManager();
		}
	}
}
 
Example 25
Project: Mod-Tools   File: OriginalFileFillerTest.java   View source code 5 votes vote down vote up
/**
 * Test of handle method, of class Task.
 * @throws java.lang.Exception
 * @deprecated has to be implemented on a case by case basis
 */
@Test
public void testHandle() throws Exception {
    System.out.println("handle");
    EntityManager manager = new PersistenceProvider().get();
    manager.getTransaction().begin();
    IOUtils.copyAndClose(
        getClass().getResourceAsStream("/test.txt"),
        FileUtils.openOutputStream(new File(getAllowedFolder()+"/steamapps/common/Stellaris/test.txt"))
    );
    Original original = new Original("test.txt");
    manager.persist(original);
    manager.getTransaction().commit();
    List<ProcessTask> result = get(original.getAid()).handle(manager);
    Assert.assertEquals(
        "Follow-up number is wrong",
        1,
        result.size()
    );
    manager.getTransaction().begin();
    manager.refresh(original);
    Assert.assertTrue(
        "Content was not written",
        original.getContent().length() > 0
    );
    manager.getTransaction().commit();
}
 
Example 26
Project: BecomeJavaHero   File: JPACategoryService.java   View source code 5 votes vote down vote up
@Override
public List<Category> getAllCategories() {
	EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	// begining of transaction
	em.getTransaction().begin();
	Query query = em.createQuery("Select c from Category c");
	return query.getResultList();
}
 
Example 27
Project: osc-core   File: AddDistributedApplianceService.java   View source code 5 votes vote down vote up
List<VirtualSystem> getVirtualSystems(EntityManager em, DistributedApplianceDto daDto, DistributedAppliance da) throws Exception {
    List<VirtualSystem> vsList = new ArrayList<VirtualSystem>();

    // build the list of associated VirtualSystems for this DA
    Set<VirtualSystemDto> vsDtoList = daDto.getVirtualizationSystems();

    for (VirtualSystemDto vsDto : vsDtoList) {
        VirtualizationConnector vc = VirtualizationConnectorEntityMgr.findById(em, vsDto.getVcId());

        // load the corresponding app sw version from db
        ApplianceSoftwareVersion av = ApplianceSoftwareVersionEntityMgr.findByApplianceVersionVirtTypeAndVersion(em,
                daDto.getApplianceId(), daDto.getApplianceSoftwareVersionName(), vc.getVirtualizationType(),
                vc.getVirtualizationSoftwareVersion());

        OSCEntityManager<Domain> oscEm = new OSCEntityManager<Domain>(Domain.class, em, this.txBroadcastUtil);
        Domain domain = vsDto.getDomainId() == null ? null : oscEm.findByPrimaryKey(vsDto.getDomainId());

        VirtualSystem vs = new VirtualSystem(da);

        vs.setApplianceSoftwareVersion(av);
        vs.setDomain(domain);
        vs.setVirtualizationConnector(vc);
        org.osc.sdk.controller.TagEncapsulationType encapsulationType = vsDto.getEncapsulationType();
        if(encapsulationType != null) {
            vs.setEncapsulationType(TagEncapsulationType.valueOf(
                encapsulationType.name()));
        }
        // generate key store and persist it as byte array in db
        vs.setKeyStore(PKIUtil.generateKeyStore());
        vsList.add(vs);
    }

    return vsList;
}
 
Example 28
Project: osc-core   File: ValidateDbCreate.java   View source code 5 votes vote down vote up
private Domain addDomainEntity(EntityManager em, ApplianceManagerConnector applianceMgrCon) {
    Domain domain = new Domain(applianceMgrCon);
    domain.setName("DC-1");
    domain.setMgrId("domain-id-3");

    OSCEntityManager.create(em, domain, this.txBroadcastUtil);

    // retrieve back and validate
    domain = em.find(Domain.class, domain.getId());
    assertNotNull(domain);
    return domain;
}
 
Example 29
Project: corso-lutech   File: Segnalazioni.java   View source code 5 votes vote down vote up
@WebMethod
public List<Segnalazione> elencoSegnalazioni() {
	EntityManager em = JPAConfig.getInstance().getEmf()
		.createEntityManager();
	
	return em.createQuery("select s from Segnalazione s", Segnalazione.class)
			.getResultList();
}
 
Example 30
Project: tasfe-framework   File: GenericJpaRepositoryFactory.java   View source code 5 votes vote down vote up
public GenericJpaRepositoryFactory(EntityManager entityManager , SqlSessionTemplate sqlSessionTemplate) {
	super(entityManager) ;
	//设置当前类的实体管理器
	this.entityManager = entityManager ;
	//设置sqlSessionTemplate,线程安全
	this.sqlSessionTemplate = sqlSessionTemplate ;

	this.extractor = PersistenceProvider.fromEntityManager(entityManager);
}
 
Example 31
Project: aries-jpa   File: TaskServiceImpl.java   View source code 5 votes vote down vote up
@Override
public void addTask(final Task task) {
    jpa.tx(new EmConsumer() {
        @Override
        public void accept(EntityManager em) {
                em.persist(task);
                em.flush();
        }
    });
}
 
Example 32
Project: Armory   File: UserResourceIntTest.java   View source code 5 votes vote down vote up
/**
 * Create a User.
 *
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which has a required relationship to the User entity.
 */
public static User createEntity(EntityManager em) {
    User user = new User();
    user.setLogin("test");
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.setEmail("[email protected]");
    user.setFirstName("test");
    user.setLastName("test");
    user.setImageUrl("http://placehold.it/50x50");
    user.setLangKey("en");
    em.persist(user);
    em.flush();
    return user;
}
 
Example 33
Project: MTC_Labrat   File: UserResourceIntTest.java   View source code 5 votes vote down vote up
/**
 * Create a User.
 *
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which has a required relationship to the User entity.
 */
public static User createEntity(EntityManager em) {
    User user = new User();
    user.setLogin(DEFAULT_LOGIN);
    user.setPassword(RandomStringUtils.random(60));
    user.setActivated(true);
    user.setEmail(DEFAULT_EMAIL);
    user.setFirstName(DEFAULT_FIRSTNAME);
    user.setLastName(DEFAULT_LASTNAME);
    user.setImageUrl(DEFAULT_IMAGEURL);
    user.setLangKey(DEFAULT_LANGKEY);
    return user;
}
 
Example 34
Project: osc-core   File: SetNetworkSettingsService.java   View source code 5 votes vote down vote up
@Override
public SetNetworkSettingsResponse exec(SetNetworkSettingsRequest request, EntityManager em) throws Exception {

    NetworkSettingsApi networkSettingsApi = new NetworkSettingsApi();
    NetworkSettingsDto networkSettingsDto = new NetworkSettingsDto();
    networkSettingsDto.setDhcp(request.isDhcp());
    if (!request.isDhcp()) {
        networkSettingsDto.setHostIpAddress(request.getHostIpAddress());
        networkSettingsDto.setHostSubnetMask(request.getHostSubnetMask());
        networkSettingsDto.setHostDefaultGateway(request.getHostDefaultGateway());
        networkSettingsDto.setHostDnsServer1(request.getHostDnsServer1());
        networkSettingsDto.setHostDnsServer2(request.getHostDnsServer2());
        validate(request);
    }
    boolean isIpChanged = !NetworkUtil.getHostIpAddress().equals(request.getHostIpAddress());

    if(isIpChanged) {
        // If IP is changed, these connections are no longer valid, shutdown so they get restarted again.
        this.server.shutdownRabbitMq();
        this.server.shutdownWebsocket();
    }

    networkSettingsApi.setNetworkSettings(networkSettingsDto);
    SetNetworkSettingsResponse response = new SetNetworkSettingsResponse();

    /*
     * IP address change needs to get propagated to security managers
     */
    if (isIpChanged) {
        response.setJobId(startIpPropagateJob());
        this.server.startRabbitMq();
        this.server.startWebsocket();
    }

    return response;
}
 
Example 35
Project: osc-core   File: DeleteK8sDAIInspectionPortTask.java   View source code 5 votes vote down vote up
@Override
public void executeTransaction(EntityManager em) throws Exception {
    OSCEntityManager<DistributedApplianceInstance> daiEmgr = new OSCEntityManager<DistributedApplianceInstance>(DistributedApplianceInstance.class, em, this.txBroadcastUtil);
    this.dai = daiEmgr.findByPrimaryKey(this.dai.getId());

    try (SdnRedirectionApi redirection = this.apiFactoryService.createNetworkRedirectionApi(this.dai.getVirtualSystem())) {
        DefaultInspectionPort inspectionPort = new DefaultInspectionPort(null, null, this.dai.getInspectionElementId(), this.dai.getInspectionElementParentId());
        redirection.removeInspectionPort(inspectionPort);
    }

    // After removing the inspection port from the SDN controller we can now delete this orphan DAI
    OSCEntityManager.delete(em, this.dai, this.txBroadcastUtil);
}
 
Example 36
Project: Mod-Tools   File: TaskTest.java   View source code 5 votes vote down vote up
@Override
public List<ProcessTask> handle(EntityManager manager) {
    ArrayList<ProcessTask> list = new ArrayList<>();
    list.add(new CounterProcessTask(1));
    list.add(new CounterProcessTask(2));
    list.add(new CounterProcessTask(3));
    return list;
}
 
Example 37
Project: Guestbook9001   File: DefaultEntryDao.java   View source code 5 votes vote down vote up
@Override
public Entry getEntry(long id) {
    EntityManager em = EntityManagerHelper.getEntityManager();
    EntityManagerHelper.beginTransaction();
    Entry entry = null;
    try {
        entry = em.find(Entry.class, id);
    } catch (Exception e) {
        throw new RuntimeException("Error getting entry", e);
    }
    EntityManagerHelper.commitAndCloseTransaction();
    return entry;
}
 
Example 38
Project: osc-core   File: SyncDistributedApplianceServiceTest.java   View source code 5 votes vote down vote up
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(this.em.find(eq(DistributedAppliance.class), eq(MARKED_FOR_DELETE_DA_ID)))
           .thenReturn(MARKED_FOR_DELETE_DA);
    when(this.em.find(eq(DistributedAppliance.class), eq(GOOD_DA_ID))).thenReturn(GOOD_DA);
    when(this.jobFactory.startDAConformJob(any(EntityManager.class), any(DistributedAppliance.class)))
           .thenAnswer(new Answer<Long>() {
               @Override
               public Long answer(InvocationOnMock invocation) throws Throwable {
                   DistributedAppliance result = invocation.getArgumentAt(1, DistributedAppliance.class);
                   return result.getId();
               }
           });
}
 
Example 39
Project: linq   File: JpaUtilTests.java   View source code 5 votes vote down vote up
@Test
@Transactional
public void testExists() {
	Assert.isTrue(!JpaUtil.exists(User.class), "Not Success.");
	User user = new User();
	user.setId(UUID.randomUUID().toString());
	user.setName("tom");
	User user2 = new User();
	user2.setName("kevin");
	user2.setId(UUID.randomUUID().toString());
	User user3 = new User();
	user3.setName("kevin");
	user3.setId(UUID.randomUUID().toString());
	
	JpaUtil.persist(user);
	JpaUtil.persist(user2);
	JpaUtil.persist(user3);
	
	Assert.isTrue(JpaUtil.exists(User.class), "Not Success.");
	
	EntityManager em = JpaUtil.getEntityManager(User.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<User> cq = cb.createQuery(User.class);
	Root<User> root = cq.from(User.class);

	Assert.isTrue(JpaUtil.exists(cq), "Not Success.");
	
	cq.where(cb.equal(root.get("name"), "tom"));
	Assert.isTrue(JpaUtil.exists(cq), "Not Success.");
	
	JpaUtil.removeAllInBatch(User.class);
}
 
Example 40
Project: osc-core   File: DeploymentSpecConformJobFactory.java   View source code 5 votes vote down vote up
private void updateDSJob(EntityManager em, final DeploymentSpec ds, Job job) {

        // TODO: It would be more sensible to make this decision
        // using if(txControl.activeTransaction()) {...}

        if (em != null) {
            ds.setLastJob(em.find(JobRecord.class, job.getId()));
            OSCEntityManager.update(em, ds, this.txBroadcastUtil);

        } else {

            try {
                EntityManager txEm = this.dbConnectionManager.getTransactionalEntityManager();
                TransactionControl txControl = this.dbConnectionManager.getTransactionControl();
                txControl.required(() -> {
                    DeploymentSpec ds1 = DeploymentSpecEntityMgr.findById(txEm, ds.getId());
                    if (ds1 != null) {
                        ds1.setLastJob(txEm.find(JobRecord.class, job.getId()));
                        OSCEntityManager.update(txEm, ds1, this.txBroadcastUtil);
                    }
                    return null;
                });
            } catch (ScopedWorkException e) {
                // Unwrap the ScopedWorkException to get the cause from
                // the scoped work (i.e. the executeTransaction() call.
                log.error("Fail to update DS job status.", e.getCause());
            }
        }
    }