Java 类javax.persistence.EntityManager 实例源码

项目:Pet-Supply-Store    文件:OrderRepository.java   
/**
 * {@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;
}
项目:OperatieBRP    文件:CustomJpaRepositoryFactory.java   
@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);
}
项目:Mod-Tools    文件:ZipContentParserTest.java   
/**
 * 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());
    }
}
项目:osc-core    文件:ForceDeleteDSTask.java   
@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);
}
项目:bibliometrics    文件:UserDAO.java   
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;
}
项目:osc-core    文件:ListJobService.java   
@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;
}
项目:comms-router    文件:CoreTaskService.java   
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());
  }
}
项目:full-javaee-app    文件:ClientPipelineDataAccessObject.java   
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;
}
项目:aries-jpa    文件:TaskServiceImplTest.java   
@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();
}
项目:full-javaee-app    文件:CompanyDataAccessObject.java   
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;
}
项目:osc-core    文件:SecurityGroupEntityMgr.java   
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;
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * 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();
    }
}
项目:osc-core    文件:VmPortHookFailurePolicyUpdateTask.java   
@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();
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
/**
 * @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();
    }
}
项目:holon-datastore-jpa    文件:DefaultJpaDatastore.java   
/**
 * 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);
    }
}
项目:SqlSauce    文件:DatabaseWrapper.java   
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();
    }
}
项目:osc-core    文件:ListAlertService.java   
@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;
}
项目:full-javaee-app    文件:ConversationDataAccessObject.java   
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;
}
项目:osc-core    文件:CheckK8sSecurityGroupLabelMetaTaskTestData.java   
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();
}
项目:Pet-Supply-Store    文件:OrderItemRepository.java   
/**
 * {@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();
}
项目:osc-core    文件:ValidateSecurityGroupProjectTask.java   
@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);
            }
        }
    }
}
项目:osc-core    文件:OsProjectNotificationListener.java   
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);
        }
    }
}
项目:osc-core    文件:ListSslCertificatesService.java   
@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);
}
项目:bdf2    文件:JpaEntityManagerRepository.java   
public EntityManager getEntityManager(String dataSourceName){
    if(dataSourceName==null){
        return getEntityManager();
    }else{
        if(entityManagerMap.containsKey(dataSourceName)){
            return entityManagerMap.get(dataSourceName);
        }else{
            return getEntityManager();
        }
    }
}
项目:Mod-Tools    文件:OriginalFileFillerTest.java   
/**
 * 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();
}
项目:BecomeJavaHero    文件:JPACategoryService.java   
@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();
}
项目:osc-core    文件:AddDistributedApplianceService.java   
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;
}
项目:osc-core    文件:ValidateDbCreate.java   
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;
}
项目:corso-lutech    文件:Segnalazioni.java   
@WebMethod
public List<Segnalazione> elencoSegnalazioni() {
    EntityManager em = JPAConfig.getInstance().getEmf()
        .createEntityManager();

    return em.createQuery("select s from Segnalazione s", Segnalazione.class)
            .getResultList();
}
项目:tasfe-framework    文件:GenericJpaRepositoryFactory.java   
public GenericJpaRepositoryFactory(EntityManager entityManager , SqlSessionTemplate sqlSessionTemplate) {
    super(entityManager) ;
    //设置当前类的实体管理器
    this.entityManager = entityManager ;
    //设置sqlSessionTemplate,线程安全
    this.sqlSessionTemplate = sqlSessionTemplate ;

    this.extractor = PersistenceProvider.fromEntityManager(entityManager);
}
项目:aries-jpa    文件:TaskServiceImpl.java   
@Override
public void addTask(final Task task) {
    jpa.tx(new EmConsumer() {
        @Override
        public void accept(EntityManager em) {
                em.persist(task);
                em.flush();
        }
    });
}
项目:MTC_Labrat    文件:UserResourceIntTest.java   
/**
 * 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;
}
项目:osc-core    文件:SetNetworkSettingsService.java   
@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;
}
项目:osc-core    文件:DeleteK8sDAIInspectionPortTask.java   
@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);
}
项目:Mod-Tools    文件:TaskTest.java   
@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;
}
项目:Guestbook9001    文件:DefaultEntryDao.java   
@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;
}
项目:osc-core    文件:SyncDistributedApplianceServiceTest.java   
@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();
               }
           });
}
项目:linq    文件:JpaUtilTests.java   
@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);
}
项目:osc-core    文件:DeploymentSpecConformJobFactory.java   
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());
            }
        }
    }