Java Code Examples for java.io.Serializable.equals()

The following are Jave code examples for showing how to use equals() of the java.io.Serializable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: xproject   File: SimpleSession.java   View Source Code Vote up 6 votes
/**
 * Returns {@code true} if the specified argument is an {@code instanceof} {@code PersistentSession} and both
 * {@link #getId() id}s are equal.  If the argument is a {@code PersistentSession} and either 'this' or the argument
 * does not yet have an ID assigned, the value of {@link #onEquals(SimpleSession) onEquals} is returned, which
 * does a necessary attribute-based comparison when IDs are not available.
 * <p/>
 * Do your best to ensure {@code PersistentSession} instances receive an ID very early in their lifecycle to
 * avoid the more expensive attributes-based comparison.
 *
 * @param obj the object to compare with this one for equality.
 * @return {@code true} if this object is equivalent to the specified argument, {@code false} otherwise.
 */
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof SimpleSession) {
        SimpleSession other = (SimpleSession) obj;
        Serializable thisId = getId();
        Serializable otherId = other.getId();
        if (thisId != null && otherId != null) {
            return thisId.equals(otherId);
        } else {
            //fall back to an attribute based comparison:
            return onEquals(other);
        }
    }
    return false;
}
 
Example 2
Project: alfresco-repository   File: VirtualStoreImpl.java   View Source Code Vote up 6 votes
@Override
public List<ChildAssociationRef> getChildAssocsByPropertyValue(Reference parentReference, QName propertyQName,
            Serializable value)
{
    List<ChildAssociationRef> allAssociations = getChildAssocs(parentReference,
                                                               RegexQNamePattern.MATCH_ALL,
                                                               RegexQNamePattern.MATCH_ALL,
                                                               Integer.MAX_VALUE,
                                                               false);

    List<ChildAssociationRef> associations = new LinkedList<>();

    for (ChildAssociationRef childAssociationRef : allAssociations)
    {
        Serializable propertyValue = environment.getProperty(childAssociationRef.getChildRef(),
                                                             propertyQName);

        if ((value == null && propertyValue == null) || (value != null && value.equals(propertyValue)))
        {
            associations.add(childAssociationRef);
        }
    }

    return associations;
}
 
Example 3
Project: parabuild-ci   File: PersistentCollection.java   View Source Code Vote up 6 votes
static void identityRemove(Collection list, Object object, SessionImplementor session) 
throws HibernateException {
	
	if ( object!=null && session.isSaved(object) ) {
	
		Serializable idOfCurrent = session.getEntityIdentifierIfNotUnsaved(object);
		Iterator iter = list.iterator();
		while ( iter.hasNext() ) {
			Serializable idOfOld = session.getEntityIdentifierIfNotUnsaved( iter.next() );
			if ( idOfCurrent.equals(idOfOld) ) {
				iter.remove();
				break;
			}
		}
		
	}
}
 
Example 4
Project: parabuild-ci   File: SessionImpl.java   View Source Code Vote up 6 votes
/**
 * Save a transient object with a manually assigned ID.
 */
public void save(Object obj, Serializable id) throws HibernateException {

	if (obj==null) throw new NullPointerException("attempted to insert null");
	if (id==null) throw new NullPointerException("null identifier passed to insert()");

	Object object = unproxy(obj); //throws exception if uninitialized!

	EntityEntry e = getEntry(object);
	if ( e!=null ) {
		if ( e.status==DELETED ) {
			forceFlush(e);
		}
		else {
			if ( !id.equals(e.id) ) throw new PersistentObjectException(
				"object passed to save() was already persistent: " +
				MessageHelper.infoString(e.persister, id)
			);
			log.trace( "object already associated with session" );
		}
	}

	doSave(object, id, getPersister(object), false, Cascades.ACTION_SAVE_UPDATE, null);

	reassociateProxy(obj, id);
}
 
Example 5
Project: parabuild-ci   File: SessionImpl.java   View Source Code Vote up 6 votes
public Serializable[] getCollectionBatch(CollectionPersister collectionPersister, Serializable id, int batchSize) {
	Serializable[] keys = new Serializable[batchSize];
	keys[0] = id;
	int i=0;
	Iterator iter = collectionEntries.values().iterator();
	while ( iter.hasNext() ) {
		CollectionEntry ce = (CollectionEntry) iter.next();
		if (
			!ce.initialized &&
			ce.loadedPersister==collectionPersister &&
			!id.equals(ce.loadedKey)
		) {
			keys[++i] = ce.loadedKey;
			if (i==batchSize-1) return keys;
		}
	}
	return keys;
}
 
Example 6
Project: parabuild-ci   File: SessionImpl.java   View Source Code Vote up 6 votes
public Serializable[] getClassBatch(Class clazz, Serializable id, int batchSize) {
	Serializable[] ids = new Serializable[batchSize];
	ids[0] = id;
	int i=0;
	Iterator iter = batchLoadableEntityKeys.keySet().iterator();
	while ( iter.hasNext() ) {
		Key key = (Key) iter.next();
		if (
			key.getMappedClass()==clazz &&
			!id.equals( key.getIdentifier() )
		) {
			ids[++i] = key.getIdentifier();
			if (i==batchSize-1) return ids;
		}
	}
	return ids;
}
 
Example 7
Project: alfresco-repository   File: WorkflowPackageImpl.java   View Source Code Vote up 5 votes
/**
* {@inheritDoc}
 */
@Extend(traitAPI=WorkflowPackageTrait.class,extensionAPI=WorkflowPackageExtension.class)
public boolean setWorkflowForPackage(WorkflowInstance instance)
{
    NodeRef packageNode = instance.getWorkflowPackage();
    if(packageNode==null)
        return false;
    
    Serializable pckgInstanceId = nodeService.getProperty(packageNode, WorkflowModel.PROP_WORKFLOW_INSTANCE_ID);
    if(pckgInstanceId != null)
    {
        if(pckgInstanceId.equals(instance.getId()))
        {
            return false;
        }
        String msg = messageService.getMessage(ERR_PACKAGE_ALREADY_ASSOCIATED, packageNode,
                    instance.getId(), pckgInstanceId);
        throw new WorkflowException(msg);
    }
    
    if (nodeService.hasAspect(packageNode, WorkflowModel.ASPECT_WORKFLOW_PACKAGE)==false)
    {
        createPackage(packageNode);
    }

    String definitionId = instance.getDefinition().getId();
    String definitionName = instance.getDefinition().getName();
    String instanceId = instance.getId();
    nodeService.setProperty(packageNode, WorkflowModel.PROP_WORKFLOW_DEFINITION_ID, definitionId);
    nodeService.setProperty(packageNode, WorkflowModel.PROP_WORKFLOW_DEFINITION_NAME, definitionName);
    nodeService.setProperty(packageNode, WorkflowModel.PROP_WORKFLOW_INSTANCE_ID, instanceId);
    return true;
}
 
Example 8
Project: alfresco-repository   File: WorkflowServiceImpl.java   View Source Code Vote up 5 votes
/**
 * Determines if the given user is a member of the pooled actors assigned to the task
 * 
 * @param task The task instance to check
 * @param username The username to check
 * @return true if the user is a pooled actor, false otherwise
 */
@SuppressWarnings("unchecked")
private boolean isUserInPooledActors(WorkflowTask task, String username)
{
    // Get the pooled actors
    Collection<NodeRef> actors = (Collection<NodeRef>)task.getProperties().get(WorkflowModel.ASSOC_POOLED_ACTORS);
    if (actors != null)
    {
        for (NodeRef actor : actors)
        {
            QName type = nodeService.getType(actor);
            if (dictionaryService.isSubClass(type, ContentModel.TYPE_PERSON))
            {
                Serializable name = nodeService.getProperty(actor, ContentModel.PROP_USERNAME);
                if(name!=null && name.equals(username))
                {
                    return true;
                }
            }
            else if (dictionaryService.isSubClass(type, ContentModel.TYPE_AUTHORITY_CONTAINER))
            {
                if (isUserInGroup(username, actor))
                {
                    // The user is a member of the group
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 9
Project: lams   File: ProxyVisitor.java   View Source Code Vote up 5 votes
/**
 * Has the owner of the collection changed since the collection
 * was snapshotted and detached?
 */
protected static boolean isOwnerUnchanged(
		final PersistentCollection snapshot, 
		final CollectionPersister persister, 
		final Serializable id
) {
	return isCollectionSnapshotValid(snapshot) &&
			persister.getRole().equals( snapshot.getRole() ) &&
			id.equals( snapshot.getKey() );
}
 
Example 10
Project: parabuild-ci   File: BatchingEntityLoader.java   View Source Code Vote up 5 votes
public Object load(SessionImplementor session, Serializable id, Object optionalObject)
	throws SQLException, HibernateException {
	Serializable[] batch = session.getClassBatch( persister.getMappedClass(), id, batchSize );
	List list;
	if ( smallBatchSize==1 || batch[smallBatchSize-1]==null ) {
		return ( (UniqueEntityLoader) nonBatchLoader ).load(session, id, optionalObject);
	}
	else if ( batch[batchSize-1]==null ) {
		if ( log.isDebugEnabled() ) log.debug( "batch loading entity (smaller batch): " + persister.getMappedClass().getName() );
		Serializable[] smallBatch = new Serializable[smallBatchSize];
		System.arraycopy(batch, 0, smallBatch, 0, smallBatchSize);
		list = smallBatchLoader.loadEntityBatch(session, smallBatch, idType, optionalObject, id);
		log.debug("done batch load");
	}
	else {
		if ( log.isDebugEnabled() ) log.debug( "batch loading entity: " + persister.getMappedClass().getName() );
		list = batchLoader.loadEntityBatch(session, batch, idType, optionalObject, id);
		log.debug("done batch load");
	}
	
	// get the right object from the list ... would it be easier to just call getEntity() ??
	Iterator iter = list.iterator();
	while ( iter.hasNext() ) {
		Object obj = iter.next();
		if ( id.equals( session.getEntityIdentifier(obj) ) ) return obj;
	}
	return null;
}
 
Example 11
Project: parabuild-ci   File: SessionImpl.java   View Source Code Vote up 5 votes
private static void checkId(Object object, ClassPersister persister, Serializable id) throws HibernateException {
	// make sure user didn't mangle the id
	if ( persister.hasIdentifierPropertyOrEmbeddedCompositeIdentifier() ) {
		Serializable oid = persister.getIdentifier(object);
		if (id==null) throw new AssertionFailure("null id in entry (don't flush the Session after an exception occurs)");
		if ( !id.equals(oid) ) throw new HibernateException(
			"identifier of an instance of " +
			persister.getClassName() +
			" altered from " +
			id +
			" to " + oid
		);
	}

}
 
Example 12
Project: alfresco-repository   File: Node2ServiceImpl.java   View Source Code Vote up 4 votes
/**
 * {@inheritDoc}
 * <p>
 * 
 * Implementation for version store v2
 */
@Override
public List<AssociationRef> getTargetAssocsByPropertyValue(NodeRef sourceRef, QNamePattern qnamePattern, QName propertyQName, Serializable propertyValue)
{
    // If lightWeightVersionStore call default version store implementation.
    if (sourceRef.getStoreRef().getIdentifier().equals(VersionModel.STORE_ID))
    {
        return super.getTargetAssocsByPropertyValue(sourceRef, qnamePattern, propertyQName, propertyValue);
    }

    // Get the assoc references from the version store.
    List<ChildAssociationRef> childAssocRefs = this.dbNodeService.getChildAssocs(VersionUtil.convertNodeRef(sourceRef),
            Version2Model.CHILD_QNAME_VERSIONED_ASSOCS, qnamePattern);

    List<AssociationRef> result = new ArrayList<AssociationRef>(childAssocRefs.size());

    for (ChildAssociationRef childAssocRef : childAssocRefs)
    {
        // Get the assoc reference.
        NodeRef childRef = childAssocRef.getChildRef();
        NodeRef referencedNode = (NodeRef) this.dbNodeService.getProperty(childRef, ContentModel.PROP_REFERENCE);

        if (this.dbNodeService.exists(referencedNode))
        {
            Long assocDbId = (Long) this.dbNodeService.getProperty(childRef, Version2Model.PROP_QNAME_ASSOC_DBID);

            // Check if property type validation has to be done.
            if (propertyQName != null)
            {
                Serializable propertyValueRetrieved = this.dbNodeService.getProperty(referencedNode, propertyQName);

                // Check if property value has been retrieved (property
                // exists) and is equal to the requested value.
                if (propertyValueRetrieved == null || !propertyValueRetrieved.equals(propertyValue))
                {
                    continue;
                }
            }

            // Build an assoc ref to add to the returned list.
            AssociationRef newAssocRef = new AssociationRef(assocDbId, sourceRef, childAssocRef.getQName(), referencedNode);
            result.add(newAssocRef);
        }
    }

    return result;
}
 
Example 13
Project: alfresco-repository   File: AbstractNodeServiceImpl.java   View Source Code Vote up 4 votes
/**
 * @see NodeServicePolicies.OnUpdatePropertiesPolicy#onUpdateProperties(NodeRef, Map, Map)
 */
protected void invokeOnUpdateProperties(
        NodeRef nodeRef,
        Map<QName, Serializable> before,
        Map<QName, Serializable> after)
{
    if (ignorePolicy(nodeRef))
    {
        return;
    }
    
    // Some logging so we can see which properties have been modified
    if (logger.isDebugEnabled() == true)
    {
        if (before == null)
        {
            logger.debug("The properties are being set for the first time.  (nodeRef=" + nodeRef.toString() + ")");
        }
        else if (after == null)
        {
            logger.debug("All the properties are being cleared.  (nodeRef=" + nodeRef.toString() + ")");                
        }
        else
        {
            logger.debug("The following properties have been updated:  (nodeRef=" + nodeRef.toString() + ")");
            for (Map.Entry<QName, Serializable> entry : after.entrySet())
            {
                Serializable beforeValue = before.get(entry.getKey());
                if (beforeValue == null)
                {
                    // Property has been set for the first time
                    logger.debug("   - The property " + entry.getKey().toString() + " has been set for the first time.");
                }
                else
                {
                    // Compare the before and after value
                    if (beforeValue.equals(entry.getValue()) == false)
                    {
                        logger.debug("   - The property " + entry.getKey().toString() + " has been updated.");
                    }
                }
                
            }
        }
        
    }
            
    // get qnames to invoke against
    Set<QName> qnames = getTypeAndAspectQNames(nodeRef);
    // execute policy for node type and aspects
    NodeServicePolicies.OnUpdatePropertiesPolicy policy = onUpdatePropertiesDelegate.get(nodeRef, qnames);
    policy.onUpdateProperties(nodeRef, before, after);
}
 
Example 14
Project: alfresco-repository   File: VirtualizationIntegrationTest.java   View Source Code Vote up 4 votes
protected void assertVirtualNode(NodeRef nodeRef, Map<QName, Serializable> expectedProperties)
{
    assertNotNull(Reference.fromNodeRef(nodeRef));

    assertTrue(nodeService.hasAspect(nodeRef,
                                     VirtualContentModel.ASPECT_VIRTUAL));
    Set<QName> aspects = nodeService.getAspects(nodeRef);
    assertTrue("Smart virtual node missing virtual aspect",aspects.contains(VirtualContentModel.ASPECT_VIRTUAL));
    //ACE-5303 injected properties title and description  require the titled aspect 
    assertTrue("Smaft virtual node missing titled aspect",aspects.contains(ContentModel.ASPECT_TITLED));

    Map<QName, Serializable> nodeProperties = nodeService.getProperties(nodeRef);

    List<QName> mandatoryProperties = Arrays.asList(ContentModel.PROP_STORE_IDENTIFIER,
                                                    ContentModel.PROP_STORE_PROTOCOL,
                                                    ContentModel.PROP_LOCALE,
                                                    ContentModel.PROP_MODIFIED,
                                                    ContentModel.PROP_MODIFIER,
                                                    ContentModel.PROP_CREATED,
                                                    ContentModel.PROP_CREATOR,
                                                    ContentModel.PROP_NODE_DBID,
                                                    ContentModel.PROP_DESCRIPTION);

    Set<QName> missingPropreties = new HashSet<>(mandatoryProperties);
    missingPropreties.removeAll(nodeProperties.keySet());

    assertTrue("Mandatory properties are missing" + missingPropreties,
               missingPropreties.isEmpty());

    assertFalse("ACE-5303 : ContentModel.PROP_TITLE should remain unset",nodeProperties.containsKey(ContentModel.PROP_TITLE));
    
    Set<Entry<QName, Serializable>> epEntries = expectedProperties.entrySet();
    StringBuilder unexpectedBuilder = new StringBuilder();
    for (Entry<QName, Serializable> entry : epEntries)
    {
        Serializable actualValue = nodeProperties.get(entry.getKey());
        Serializable expectedValue = expectedProperties.get(entry.getKey());
        boolean fail = false;
        String expectedValueStr = null;

        if (expectedValue != null)
        {
            expectedValueStr = expectedValue.toString();

            if (!expectedValue.equals(actualValue))
            {
                fail = true;
            }

        }
        else if (actualValue != null)
        {
            fail = true;
            expectedValueStr = "<null>";
        }

        if (fail)
        {
            unexpectedBuilder.append("\n");
            unexpectedBuilder.append(entry.getKey());
            unexpectedBuilder.append(" expected[");
            unexpectedBuilder.append(expectedValueStr);
            unexpectedBuilder.append("] != actua[");
            unexpectedBuilder.append(actualValue);
            unexpectedBuilder.append("]");
        }
    }
    String unexpectedStr = unexpectedBuilder.toString();
    assertTrue("Unexpected property values : " + unexpectedStr,
               unexpectedStr.isEmpty());
}
 
Example 15
Project: lams   File: CollectionCacheInvalidator.java   View Source Code Vote up 4 votes
private void evictCache(Object entity, EntityPersister persister, EventSource session, Object[] oldState) {
	try {
		SessionFactoryImplementor factory = persister.getFactory();

		Set<String> collectionRoles = factory.getCollectionRolesByEntityParticipant( persister.getEntityName() );
		if ( collectionRoles == null || collectionRoles.isEmpty() ) {
			return;
		}
		for ( String role : collectionRoles ) {
			CollectionPersister collectionPersister = factory.getCollectionPersister( role );
			if ( !collectionPersister.hasCache() ) {
				// ignore collection if no caching is used
				continue;
			}
			// this is the property this OneToMany relation is mapped by
			String mappedBy = collectionPersister.getMappedByProperty();
			if ( mappedBy != null ) {
				int i = persister.getEntityMetamodel().getPropertyIndex( mappedBy );
				Serializable oldId = null;
				if ( oldState != null ) {
					// in case of updating an entity we perhaps have to decache 2 entity collections, this is the
					// old one
					oldId = session.getIdentifier( oldState[i] );
				}
				Object ref = persister.getPropertyValue( entity, i );
				Serializable id = null;
				if ( ref != null ) {
					id = session.getIdentifier( ref );
				}
				// only evict if the related entity has changed
				if ( id != null && !id.equals( oldId ) ) {
					evict( id, collectionPersister, session );
					if ( oldId != null ) {
						evict( oldId, collectionPersister, session );
					}
				}
			}
			else {
				LOG.debug( "Evict CollectionRegion " + role );
				collectionPersister.getCacheAccessStrategy().evictAll();
			}
		}
	}
	catch ( Exception e ) {
		// don't let decaching influence other logic
		LOG.error( "", e );
	}
}
 
Example 16
Project: parabuild-ci   File: SessionImpl.java   View Source Code Vote up 4 votes
static boolean isOwnerUnchanged(CollectionSnapshot snapshot, CollectionPersister persister, Serializable id) {
	return isCollectionSnapshotValid(snapshot) &&
		persister.getRole().equals( snapshot.getRole() ) &&
		id.equals( snapshot.getKey() );
}