项目: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 JpaEntity@R_628_4045@ion<?,Serializable> entity@R_628_4045@ion = getEntity@R_628_4045@ion(Metadata.getDomainType());
if (isQueryDslSpecificExecutor(repositoryInterface)) {
throw new IllegalArgumentException("QueryDSL interface niet toegestaan");
}
return isMaxedRepository(repositoryInterface)
? new CustomSimpleMaxedJpaRepository(entity@R_628_4045@ion,entityManager)
: isQuerycostRepository(repositoryInterface)
? new CustomSimpleQuerycostJpaRepository(entity@R_628_4045@ion,entityManager,maxCostsQueryPlan)
: new CustomSimpleJpaRepository(entity@R_628_4045@ion,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",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;
}
@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;
}
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;
}
}
/**
* 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();
}
}
/**
* @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(),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);
}
}
public <E extends IEntity<I,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(),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,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;
}
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();
}
@Override
public void executeTransaction(EntityManager em) throws Exception {
OSCEntityManager<SecurityGroup> sgEmgr = new OSCEntityManager<SecurityGroup>(SecurityGroup.class,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.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,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,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
项目: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());
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。