public AddResult < L > addResource ( Resource < L > newResource ) throws IllegalArgumentException { AddResult < L > result ; graphLockWrite . lock ( ) ; try { // Need to make sure we keep our resources consistent. If the newResource has a parent, // and that parent is not the same instance we have in our graph, we need to recreate the // newResource such that it refers to our instance of the parent. // Do this BEFORE we attempt to add the new resource to the graph. if ( newResource . getParent ( ) != null ) { Resource < L > parentInGraph = getResource ( newResource . getParent ( ) . getID ( ) ) ; if ( parentInGraph == null ) { throw new IllegalArgumentException ( String . format ( "The new resource [%s] has a parent [%s] that has not been added yet" , newResource , newResource . getParent ( ) ) ) ; } // if parents are not the same instance, create a new resource with the parent we have in the graph if ( parentInGraph != newResource . getParent ( ) ) { newResource = Resource . < L > builder ( newResource ) . parent ( parentInGraph ) . build ( ) ; } } boolean added = this . resourcesGraph . addVertex ( newResource ) ; if ( ! added ) { // Looks like this resource already exists. // If the resource changed, we want to replace it but keep all edges intact. // If the resource did not change, we don't do anything. Resource < L > oldResource = getResource ( newResource . getID ( ) ) ; if ( new ResourceComparator ( ) . compare ( oldResource , newResource ) != 0 ) { Set < Resource < L >> children = getChildren ( oldResource ) ; this . resourcesGraph . removeVertex ( oldResource ) ; // removes all edges! remember to put parent back this . resourcesGraph . addVertex ( newResource ) ; for ( Resource < L > child : children ) { ResourceManager . this . resourcesGraph . addEdge ( newResource , child ) ; } result = new AddResult <> ( AddResult . Effect . MODIFIED , newResource ) ; } else { result = new AddResult <> ( AddResult . Effect . UNCHANGED , oldResource ) ; } } else { result = new AddResult <> ( AddResult . Effect . ADDED , newResource ) ; } if ( ( result . getEffect ( ) != AddResult . Effect . UNCHANGED ) && ( newResource . getParent ( ) != null ) ) { this . resourcesGraph . addEdge ( newResource . getParent ( ) , newResource ) ; } return result ; } finally { graphLockWrite . unlock ( ) ; } }
Adds the given resource to the resource hierarchy replacing the resource if it already exist but has changed .