@Override
public <T extends Resource> T attach(String attachmentId, ResourceId resourceId, Class<? extends T> clazz) {
checkNotNull(attachmentId,"Attachment identifier cannot be null");
checkNotNull(resourceId,"Attached resource identifier cannot be null");
checkNotNull(clazz,"Attached resource class cannot be null");
AttachmentId aId = AttachmentId.createId(attachmentId,resourceId);
checkState(!attachments.containsKey(aId),"Resource '%s' is already attached as '%s'",resourceId,attachmentId);
checkState(!attachmentsById.containsKey(attachmentId),"A resource is already attached as '%s'",attachmentId);
checkState(!attachmentsByResourceId.containsKey(resourceId),"Resource '%s' is already attached",resourceId);
ResourceTemplate attachmentTemplate=super.getTemplate(resourceId);
checkState(Resources.areCompatible(clazz,attachmentTemplate),"Attachment '%s' is not of type '%s' (%s)",attachmentId,clazz.getCanonicalName(),attachmentTemplate.getClass().getCanonicalName());
InMemoryResource newResource=createChild(resourceId,attachmentTemplate);
InMemoryAttachment newAttachment = new InMemoryAttachment(aId,this.versionGenerator.nextVersion(attachmentId));
attachments.put(newAttachment.attachmentId(),newAttachment);
attachmentsById.put(aId.id(),aId);
attachmentsByResourceId.put(aId.resourceId(),aId);
return clazz.cast(newResource);
}