@Override public void release() { final Lock lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); if (lock == null) { return; } // Only the current owner can release the lock final String owner = lock.getUniqueId(); if (uniqueId.equals(owner)) { lock.setUniqueId(null); lock.setExpirationDate(null); logger.debug("Releasing {} lock held by {}.", applicationId, uniqueId); entityManager.persist(lock); } else { throw new IllegalStateException("Cannot release lock owned by " + owner); } }
/** * {@inheritDoc} **/ @Override @Transactional(readOnly = false) public void release() { final Lock lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); if (lock == null) { return; } // Only the current owner can release the lock final String owner = lock.getUniqueId(); if (uniqueId.equals(owner)) { lock.setUniqueId(null); lock.setExpirationDate(null); logger.debug("Releasing {} lock held by {}.", applicationId, uniqueId); entityManager.persist(lock); } else { throw new IllegalStateException("Cannot release lock owned by " + owner); } }
/** * Delete the TGt and all of its service tickets. * * @param ticket the ticket */ private void deleteTicketAndChildren(final Ticket ticket) { final List<TicketGrantingTicketImpl> ticketGrantingTicketImpls = entityManager .createQuery("select t from TicketGrantingTicketImpl t where t.ticketGrantingTicket.id = :id", TicketGrantingTicketImpl.class) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .setParameter("id", ticket.getId()) .getResultList(); final List<ServiceTicketImpl> serviceTicketImpls = entityManager .createQuery("select s from ServiceTicketImpl s where s.ticketGrantingTicket.id = :id", ServiceTicketImpl.class) .setParameter("id", ticket.getId()) .getResultList(); for (final ServiceTicketImpl s : serviceTicketImpls) { removeTicket(s); } for (final TicketGrantingTicketImpl t : ticketGrantingTicketImpls) { deleteTicketAndChildren(t); } removeTicket(ticket); }
private <S> S aggregate(CriteriaBuilder builder, CriteriaQuery<S> query, Root<E> root, Specification<E> spec, List<Selection<?>> selectionList, LockModeType lockMode) { if (selectionList != null) { Predicate predicate = spec.toPredicate(root, query, builder); if (predicate != null) { query.where(predicate); } query.multiselect(selectionList); return (S) em.createQuery(query).setLockMode(lockMode).getSingleResult(); } return null; }
/** * 根据某些属性获取对象L * @param name 属性名称 * @param value 属性值 * @param lockMode 对象锁类型 * @return */ public T findOneByProperty(String name, Object value, LockModeType lockMode) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> query = cb.createQuery(entityClass); Root<T> root = query.from(entityClass); query.where(cb.equal(QueryFormHelper.getPath(root, name), value)); TypedQuery<T> typedQuery = em.createQuery(query); typedQuery.setLockMode(lockMode); try { List<T> list = typedQuery.getResultList(); if (list.isEmpty()) { return null; } else { return list.get(0); } } catch (NoResultException e) { return null; } }
private void deleteTicketAndChildren(final Ticket ticket) { final List<TicketGrantingTicketImpl> ticketGrantingTicketImpls = entityManager .createQuery("select t from TicketGrantingTicketImpl t where t.ticketGrantingTicket.id = :id", TicketGrantingTicketImpl.class) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .setParameter("id", ticket.getId()) .getResultList(); final List<ServiceTicketImpl> serviceTicketImpls = entityManager .createQuery("select s from ServiceTicketImpl s where s.ticketGrantingTicket.id = :id", ServiceTicketImpl.class) .setParameter("id", ticket.getId()) .getResultList(); for (final ServiceTicketImpl s : serviceTicketImpls) { removeTicket(s); } for (final TicketGrantingTicketImpl t : ticketGrantingTicketImpls) { deleteTicketAndChildren(t); } removeTicket(ticket); }
@Override public void executeTransaction(EntityManager em) throws Exception { log.debug("Start excecuting RegisterMgrPolicyNotificationTask Task. MC: '" + this.mc.getName() + "'"); this.mc = em.find(ApplianceManagerConnector.class, this.mc.getId(), LockModeType.PESSIMISTIC_WRITE); ManagerCallbackNotificationApi mgrApi = null; try { mgrApi = this.apiFactoryService.createManagerUrlNotificationApi(this.mc); mgrApi.createPolicyGroupNotificationRegistration(Server.getApiPort(), RestConstants.OSC_DEFAULT_LOGIN, this.passwordUtil.getOscDefaultPass()); this.mc.setLastKnownNotificationIpAddress(ServerUtil.getServerIP()); OSCEntityManager.update(em, this.mc, this.txBroadcastUtil); } finally { if (mgrApi != null) { mgrApi.close(); } } }
@Override public void executeTransaction(EntityManager em) throws Exception { log.debug("Start excecuting RegisterMgrDomainNotificationTask Task. MC: '" + this.mc.getName() + "'"); this.mc = em.find(ApplianceManagerConnector.class, this.mc.getId(), LockModeType.PESSIMISTIC_WRITE); ManagerCallbackNotificationApi mgrApi = null; try { mgrApi = this.apiFactoryService.createManagerUrlNotificationApi(this.mc); mgrApi.createDomainNotificationRegistration(Server.getApiPort(), RestConstants.OSC_DEFAULT_LOGIN, this.passwordUtil.getOscDefaultPass()); this.mc.setLastKnownNotificationIpAddress(ServerUtil.getServerIP()); OSCEntityManager.update(em, this.mc, this.txBroadcastUtil); } finally { if (mgrApi != null) { mgrApi.close(); } } }
@Override public void executeTransaction(EntityManager em) throws Exception { log.debug("Start excecuting RegisterMgrPolicyNotificationTask Task. MC: '" + this.mc.getName() + "'"); this.mc = em.find(ApplianceManagerConnector.class, this.mc.getId(), LockModeType.PESSIMISTIC_WRITE); ManagerCallbackNotificationApi mgrApi = null; try { mgrApi = this.apiFactoryService.createManagerUrlNotificationApi(this.mc); mgrApi.updatePolicyGroupNotificationRegistration(this.oldBrokerIp, Server.getApiPort(), RestConstants.OSC_DEFAULT_LOGIN, this.passwordUtil.getOscDefaultPass()); this.mc.setLastKnownNotificationIpAddress(ServerUtil.getServerIP()); OSCEntityManager.update(em, this.mc, this.txBroadcastUtil); } finally { if (mgrApi != null) { mgrApi.close(); } } }
/** * List all tags used within a VS and locate the next 'minimum' available tag starting with 2. If there are tags * 'holes' (i.e. for "1,2,3,6,7,9" - 4,5,8,10... will be available for allocation). If no 'holes' available, * will allocate the next minimum number (10 in our example). * * @param session * database session * @param vs * Virtual System Object to get tag for * @return Minimum and unique tag for given VS. */ @SuppressWarnings("unchecked") public static synchronized Long generateUniqueTag(EntityManager em, VirtualSystem vs) { vs = em.find(VirtualSystem.class, vs.getId(), LockModeType.PESSIMISTIC_WRITE); String sql = "SELECT CONVERT(SUBSTR(tag,LOCATE('-',tag)+1), LONG) AS tag_val " + "FROM security_group_interface WHERE virtual_system_fk = " + vs.getId() + " ORDER BY tag_val"; List<Object> list = em.createNativeQuery(sql).getResultList(); // Start with 2 as 1 is reserved in some cases // TODO: arvindn - Some security partners require tag's larger than 300. Remove once problem is fixed on the // partners side. Long prevVal = 301L; for (Object tag : list) { long tagValue = ((BigInteger) tag).longValue(); if (tagValue != prevVal) { return prevVal; } prevVal++; } return prevVal; }
@Before public void testInitialize() throws Exception { MockitoAnnotations.initMocks(this); Mockito.when(this.em.getTransaction()).thenReturn(this.tx); this.txControl.setEntityManager(this.em); Mockito.when(this.dbMgr.getTransactionalEntityManager()).thenReturn(this.em); Mockito.when(this.dbMgr.getTransactionControl()).thenReturn(this.txControl); this.vs = new VirtualSystem(); this.vs.setId(2L); this.vs.setName("vs"); Appliance appliance = new Appliance(); this.applianceSoftwareVersion = new ApplianceSoftwareVersion(appliance); this.applianceSoftwareVersion.setApplianceSoftwareVersion("applianceSoftwareVersion"); this.vs.setApplianceSoftwareVersion(this.applianceSoftwareVersion); Mockito.when(this.em.find(Mockito.eq(VirtualSystem.class), Mockito.eq(this.vs.getId()), Mockito.eq(LockModeType.PESSIMISTIC_WRITE))).thenReturn(this.vs); }
/** * Convert from the Hibernate specific LockMode to the JPA defined LockModeType. * * @param lockMode The Hibernate LockMode. * * @return The JPA LockModeType */ public static LockModeType convertToLockModeType(LockMode lockMode) { if ( lockMode == LockMode.NONE ) { return LockModeType.NONE; } else if ( lockMode == LockMode.OPTIMISTIC || lockMode == LockMode.READ ) { return LockModeType.OPTIMISTIC; } else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT || lockMode == LockMode.WRITE ) { return LockModeType.OPTIMISTIC_FORCE_INCREMENT; } else if ( lockMode == LockMode.PESSIMISTIC_READ ) { return LockModeType.PESSIMISTIC_READ; } else if ( lockMode == LockMode.PESSIMISTIC_WRITE || lockMode == LockMode.UPGRADE || lockMode == LockMode.UPGRADE_NOWAIT || lockMode == LockMode.UPGRADE_SKIPLOCKED) { return LockModeType.PESSIMISTIC_WRITE; } else if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT || lockMode == LockMode.FORCE ) { return LockModeType.PESSIMISTIC_FORCE_INCREMENT; } throw new AssertionFailure( "unhandled lock mode " + lockMode ); }
/** * {@inheritDoc} **/ @Override @Transactional(readOnly = false) public boolean acquire() { Lock lock; try { lock = entityManager.find(Lock.class, applicationId, LockModeType.PESSIMISTIC_WRITE); } catch (final PersistenceException e) { logger.debug("{} failed querying for {} lock.", uniqueId, applicationId, e); return false; } boolean result = false; if (lock != null) { final DateTime expDate = new DateTime(lock.getExpirationDate()); if (lock.getUniqueId() == null) { // No one currently possesses lock logger.debug("{} trying to acquire {} lock.", uniqueId, applicationId); result = acquire(entityManager, lock); } else if (new DateTime().isAfter(expDate)) { // Acquire expired lock regardless of who formerly owned it logger.debug("{} trying to acquire expired {} lock.", uniqueId, applicationId); result = acquire(entityManager, lock); } } else { // First acquisition attempt for this applicationId logger.debug("Creating {} lock initially held by {}.", applicationId, uniqueId); result = acquire(entityManager, new Lock()); } return result; }
/** * Gets the ticket from the database, as is. * * @param ticketId the ticket id * @return the raw ticket */ private Ticket getRawTicket(final String ticketId) { try { if (ticketId.startsWith(this.ticketGrantingTicketPrefix)) { return entityManager.find(TicketGrantingTicketImpl.class, ticketId, LockModeType.PESSIMISTIC_WRITE); } return entityManager.find(ServiceTicketImpl.class, ticketId); } catch (final Exception e) { logger.error("Error getting ticket {} from registry.", ticketId, e); } return null; }
@Override public boolean acquire() { final Lock lock; try { lock = this.entityManager.find(Lock.class, this.applicationId, LockModeType.OPTIMISTIC); } catch (final Exception e) { LOGGER.debug("[{}] failed querying for [{}] lock.", this.uniqueId, this.applicationId, e); return false; } boolean result = false; if (lock != null) { final ZonedDateTime expDate = lock.getExpirationDate(); if (lock.getUniqueId() == null) { // No one currently possesses lock LOGGER.debug("[{}] trying to acquire [{}] lock.", this.uniqueId, this.applicationId); result = acquire(lock); } else if (expDate == null || ZonedDateTime.now(ZoneOffset.UTC).isAfter(expDate)) { // Acquire expired lock regardless of who formerly owned it LOGGER.debug("[{}] trying to acquire expired [{}] lock.", this.uniqueId, this.applicationId); result = acquire(lock); } } else { // First acquisition attempt for this applicationId LOGGER.debug("Creating [{}] lock initially held by [{}].", applicationId, uniqueId); result = acquire(new Lock()); } return result; }
@Override public E findOne(Specification<E> spec, LockModeType lockMode) { try { return getQuery(spec, (Sort) null).setLockMode(lockMode).getSingleResult(); } catch (NoResultException e) { return null; } }
@Override public <S> S aggregate(Class<S> resultClass, Specification<E> spec, AggregateExpression<E> expression, LockModeType lockMode) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<S> query = builder.createQuery(resultClass); Root<E> root = query.from(getDomainClass()); List<Selection<?>> selectionList = expression.buildExpression(root, query, builder); return aggregate(builder, query, root, spec, selectionList, lockMode); }
@Override public <S> S sum(Class<S> resultClass, Specification<E> spec, LockModeType lockMode, List<SingularAttribute<E, ? extends Number>> properties) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<S> query = builder.createQuery(resultClass); Root<E> root = query.from(getDomainClass()); List<Selection<?>> selectionList = Lists.newArrayList(); for (SingularAttribute<E, ? extends Number> property : properties) { selectionList.add(builder.sum(root.get(property))); } return aggregate(builder, query, root, spec, selectionList, lockMode); }
/** * Check if some known parameter is setted in query definition and apply behaviour to query * @param query Query * @param configuration Query configuration */ @SuppressWarnings("rawtypes") private static void processQueryParameters(JPQLQuery<?> query, QueryConfiguration configuration) { ObjectUtils.argumentNotNull(query, "Query must be not null"); if (query instanceof AbstractJPAQuery) { configuration.getParameter(JpaQueryHint.QUERY_PARAMETER_HINT, JpaQueryHint.class) .ifPresent(p -> ((AbstractJPAQuery) query).setHint(p.getName(), p.getValue())); configuration.getParameter(JpaDatastore.QUERY_PARAMETER_LOCK_MODE, LockModeType.class) .ifPresent(p -> ((AbstractJPAQuery) query).setLockMode(p)); } }
private Ticket getRawTicket(final String ticketId) { try { if (ticketId.startsWith(this.ticketGrantingTicketPrefix)) { return entityManager.find(TicketGrantingTicketImpl.class, ticketId, LockModeType.PESSIMISTIC_WRITE); } return entityManager.find(ServiceTicketImpl.class, ticketId); } catch (final Exception e) { logger.error("Error getting ticket {} from registry.", ticketId, e); } return null; }
private void handleResponse( EntityManager em, List<AgentStatusResponse> agentStatusList, List<ManagerDeviceMemberStatusElement> agentElems, ApplianceManagerConnector mc) { for (ManagerDeviceMemberStatusElement agentElem : agentElems){ AgentStatusResponse agentStatus = new AgentStatusResponse(); VersionUtil.Version version = new VersionUtil.Version(); version.setVersionStr(agentElem.getVersion()); agentStatus.setVersion(version.getVersionStr()); agentStatus.setApplianceId(agentElem.getDistributedApplianceInstanceElement().getId()); agentStatus.setApplianceName(agentElem.getDistributedApplianceInstanceElement().getName()); agentStatus.setApplianceIp(agentElem.getApplianceIp()); agentStatus.setManagerIp(mc.getIpAddress()); agentStatus.setApplianceGateway(agentElem.getApplianceGateway()); agentStatus.setDiscovered(agentElem.isDiscovered().booleanValue()); agentStatus.setInspectionReady(agentElem.isInspectionReady().booleanValue()); AgentDpaInfo agentDpaInfo = new AgentDpaInfo(); agentDpaInfo.netXDpaRuntimeInfo.rx = agentElem.getRx(); agentDpaInfo.netXDpaRuntimeInfo.txSva = agentElem.getTxSva(); agentDpaInfo.netXDpaRuntimeInfo.dropSva = agentElem.getDropSva(); agentStatus.setAgentDpaInfo(agentDpaInfo); agentStatus.setCurrentServerTime(agentElem.getCurrentServerTime()); agentStatus.setPublicIp(agentElem.getPublicIp()); agentStatus.setBrokerIp(agentElem.getBrokerIp()); DistributedApplianceInstance dai = em.find(DistributedApplianceInstance.class, agentElem.getDistributedApplianceInstanceElement().getId(), LockModeType.PESSIMISTIC_WRITE); updateDaiAgentStatusInfo(em, agentStatus, dai); agentStatus.setVirtualServer(dai.getHostName()); agentStatus.setPublicIp(dai.getIpAddress()); agentStatusList.add(agentStatus); } }
@Override public void executeTransaction(EntityManager em) throws Exception { this.sgi = em.find(SecurityGroupInterface.class, this.sgi.getId()); this.dai = em.find(DistributedApplianceInstance.class, this.dai.getId(), LockModeType.PESSIMISTIC_WRITE); if (this.sgi.getSecurityGroup() == null || this.sgi.getSecurityGroup().getSecurityGroupMembers() == null) { LOG.info(String.format("The SGI %s security group does not have members.", this.sgi.getName())); return; } Set<VirtualPort> ports = new HashSet<>(); for (SecurityGroupMember sgm : this.sgi.getSecurityGroup().getSecurityGroupMembers()) { // If SGM is marked for deletion, previous tasks should have removed the hooks and deleted the member from D. if (!sgm.getMarkedForDeletion()) { if (sgm.getType().equals(SecurityGroupMemberType.LABEL)) { ports.addAll(sgm.getPodPorts()); } else { ports.addAll(sgm.getVmPorts()); } } } LOG.info(String.format("Retrieved %s ports in the SGI %s", ports.size(), this.sgi.getName())); for (VirtualPort port : ports) { updatePortProtection(port); OSCEntityManager.update(em, (IscEntity)port, this.txBroadcastUtil); OSCEntityManager.update(em, this.dai, this.txBroadcastUtil); } }
public LockOptions determineLockOptions(NamedQuery namedQueryAnnotation) { LockModeType lockModeType = namedQueryAnnotation.lockMode(); Integer lockTimeoutHint = getInteger( namedQueryAnnotation.name(), "javax.persistence.lock.timeout" ); LockOptions lockOptions = new LockOptions( LockModeConverter.convertToLockMode( lockModeType ) ); if ( lockTimeoutHint != null ) { lockOptions.setTimeOut( lockTimeoutHint ); } return lockOptions; }
/** * Convert from JPA defined LockModeType to Hibernate specific LockMode. * * @param lockMode The JPA LockModeType * * @return The Hibernate LockMode. */ public static LockMode convertToLockMode(LockModeType lockMode) { switch ( lockMode ) { case READ: case OPTIMISTIC: { return LockMode.OPTIMISTIC; } case OPTIMISTIC_FORCE_INCREMENT: case WRITE: { return LockMode.OPTIMISTIC_FORCE_INCREMENT; } case PESSIMISTIC_READ: { return LockMode.PESSIMISTIC_READ; } case PESSIMISTIC_WRITE: { return LockMode.PESSIMISTIC_WRITE; } case PESSIMISTIC_FORCE_INCREMENT: { return LockMode.PESSIMISTIC_FORCE_INCREMENT; } case NONE: { return LockMode.NONE; } default: { throw new AssertionFailure( "Unknown LockModeType: " + lockMode ); } } }
@Override public LockModeType getLockMode() { return _q.getLockMode(); }
@Override public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String, Object> arg3) { return this.original.find(arg0, arg1, arg2, arg3); }
public JpaTicketRegistry(final LockModeType lockType, final TicketCatalog ticketCatalog) { this.lockType = lockType; this.ticketCatalog = ticketCatalog; }
public LockModeType getTicketLockType() { return ticketLockType; }
public void setTicketLockType(final LockModeType ticketLockType) { this.ticketLockType = ticketLockType; }
@Override public void lock(Object arg0, LockModeType arg1, Map<String, Object> arg2) { this.original.lock(arg0, arg1, arg2); }
@Override public <T> T find(Class<T> type, Object o, LockModeType lmt, Map<String, Object> map) { return em.find(type, o, lmt, map); }
@Override public void lock(Object o, LockModeType lmt) { em.lock(o, lmt); }
@Override public void lock(Object entity, LockModeType lockMode) { // TODO Auto-generated method stub }
@Override public void refresh(Object o, LockModeType lmt) { em.refresh(o, lmt); }
@Override public <T> T find(Class<T> entityClass, Object primaryKey, LockModeType lockMode) { // TODO Auto-generated method stub return null; }
@Override public LockModeType getLockMode(Object o) { return em.getLockMode(o); }
@Override public <T> T find(Class<T> type, Object o, LockModeType lmt) { return em.find(type, o, lmt); }