Index: /ComponentRegistry/trunk/ComponentRegistry/nbactions.xml
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/nbactions.xml	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/nbactions.xml	(revision 5549)
@@ -35,3 +35,17 @@
             </properties>
         </action>
+        <action>
+            <actionName>debug.test.single</actionName>
+            <goals>
+                <goal>test-compile</goal>
+                <goal>surefire:test</goal>
+            </goals>
+            <properties>
+                <test>${packageClassName}</test>
+                <forkMode>once</forkMode>
+                <maven.surefire.debug>-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -Xmx512m</maven.surefire.debug>
+                <jpda.listen>true</jpda.listen>
+                
+            </properties>
+        </action>
     </actions>
Index: /ComponentRegistry/trunk/ComponentRegistry/pom.xml
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/pom.xml	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/pom.xml	(revision 5549)
@@ -31,5 +31,5 @@
 		<flexDebug>0</flexDebug>
 		<spring-data-jpa.version>1.3.4.RELEASE</spring-data-jpa.version>
-		<spring.version>3.2.4.RELEASE</spring.version>
+		<spring.version>3.2.10.RELEASE</spring.version>
 		<jackson.version>1.9.13</jackson.version>
 		<jersey.version>1.17.1</jersey.version>
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/AuthenticationFailException.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/AuthenticationFailException.java	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/AuthenticationFailException.java	(revision 5549)
@@ -0,0 +1,17 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package clarin.cmdi.componentregistry;
+
+/**
+ *
+ * @author olhsha
+ */
+public class AuthenticationFailException extends Exception{
+    
+    public AuthenticationFailException(String message){
+        super(message);
+    }
+    
+}
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistry.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistry.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistry.java	(revision 5549)
@@ -23,20 +23,28 @@
     public static final String PUBLIC_NAME = "Public Registry";
 
+    
+   
+    public Owner getRegistryOwner();  
+    public void setRegistryOwner(Owner registryOwner);     
+    
+    public RegistrySpace getRegistrySpace(); 
+    public void setRegistrySpace(RegistrySpace registrySpace); 
+    
+    public Number getGroupId(); 
+    public void setGroupId(Number groupId); 
+    
+    public Number getBaseDescriptionOwnerId(String cmdId);
+    
+    public List<Number> getItemGroups(String cmdId);
     /**
      * @return List of component descriptions ordered by name ascending
      * @throws ComponentRegistryException
      */
-    List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException;
-
-    /**
-     * @param principalName
-     * @param groupId
-     * @return List of component descriptions ordered by name ascending
-     * @throws ComponentRegistryException
-     */
-    List<ComponentDescription> getComponentDescriptionsInGroup(String principalName, String groupId) throws ComponentRegistryException;
-
-    ComponentDescription getComponentDescription(String id) throws ComponentRegistryException;
-
+    List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException, UserUnauthorizedException;
+
+   
+    ComponentDescription getComponentDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    
     /**
      *
@@ -44,12 +52,6 @@
      * @throws ComponentRegistryException
      */
-    List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException;
-
-    /**
-    * @param groupId
-    * @return List of profile descriptions ordered by name ascending
-    * @throws ComponentRegistryException
-    */
-   List<ProfileDescription> getProfileDescriptionsInGroup(String groupId) throws ComponentRegistryException;
+    List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException, UserUnauthorizedException;
+
 
    /**
@@ -65,12 +67,13 @@
     * @throws ComponentRegistryException
     */
-   List<ProfileDescription> getProfileDescriptionsForMetadaEditor(String groupId) throws ComponentRegistryException;
-
-   ProfileDescription getProfileDescription(String id) throws ComponentRegistryException;
-
-    CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException;
+   List<ProfileDescription> getProfileDescriptionsForMetadaEditor(Number groupId) throws ComponentRegistryException, UserUnauthorizedException;
+
+   ProfileDescription getProfileDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    CMDComponentSpec getMDProfileAccessControled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    CMDComponentSpec getMDComponentAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
 
     CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException;
-
     /**
      *
@@ -84,5 +87,5 @@
      * @return -1 if comment could not be registered
      */
-    int registerComment(Comment comment, String userId) throws ComponentRegistryException;
+    int registerComment(Comment comment, String userId) throws ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException;
 
     /**
@@ -90,5 +93,5 @@
      * @return -1 if component could not be updated
      */
-    int update(BaseDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate);
+    int update(BaseDescription description, CMDComponentSpec spec, boolean forceUpdate)  throws UserUnauthorizedException, ItemNotFoundException;
 
     /**
@@ -97,18 +100,17 @@
      * current (private) workspace to public workspace.
      */
-    int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal);
-
-    void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException;
-
-    void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException;
-
-    void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException;
-
-    void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException;
-
-    /**
-     *
-     * @param profileId
-     * @param principal
+    int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal)  throws UserUnauthorizedException, ItemNotFoundException;
+
+    void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
+
+    /**
+     *
+     * @param profileIds
      * @throws IOException
      * @throws UserUnauthorizedException
@@ -116,5 +118,5 @@
      * @throws DeleteFailedException
      */
-    void deleteMDProfile(String profileId, Principal principal) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException;
+    void deleteMDProfile(String profileId) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException, ItemNotFoundException;
 
     /**
@@ -130,6 +132,6 @@
      * @throws DeleteFailedException
      */
-    void deleteMDComponent(String componentId, Principal principal, boolean forceDelete) throws IOException, ComponentRegistryException, UserUnauthorizedException,
-	    DeleteFailedException;
+    void deleteMDComponent(String componentId, boolean forceDelete) throws IOException, ComponentRegistryException, UserUnauthorizedException,
+	    DeleteFailedException, ItemNotFoundException;
 
     /**
@@ -149,13 +151,5 @@
     List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException;
 
-    /**
-     * Return true if this registry is the public registry as opposed to a
-     * registry used for the user privately.
-     * */
-    boolean isPublic();
-
-    ComponentStatus getStatus();
-
-    Owner getOwner();
+  
 
     /**
@@ -168,5 +162,5 @@
      * @return List of profile descriptions ordered by name ascending
      */
-    List<ProfileDescription> getDeletedProfileDescriptions();
+    List<ProfileDescription> getDeletedProfileDescriptions()throws ComponentRegistryException;
 
     /**
@@ -174,5 +168,5 @@
      * @return List of component descriptions ordered by name ascending
      */
-    List<ComponentDescription> getDeletedComponentDescriptions();
+    List<ComponentDescription> getDeletedComponentDescriptions() throws ComponentRegistryException;
 
     /**
@@ -182,5 +176,5 @@
      * @throws ComponentRegistryException
      */
-    List<Comment> getCommentsInProfile(String profileId, Principal principal) throws ComponentRegistryException;
+    List<Comment> getCommentsInProfile(String profileId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
 
     /**
@@ -191,5 +185,5 @@
      * @throws ComponentRegistryException
      */
-    Comment getSpecifiedCommentInProfile(String profileId, String commentId, Principal principal) throws ComponentRegistryException;
+    Comment getSpecifiedCommentInProfile(String profileId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
 
     /**
@@ -199,5 +193,5 @@
      * @throws ComponentRegistryException
      */
-    List<Comment> getCommentsInComponent(String componentId, Principal principal) throws ComponentRegistryException;
+    List<Comment> getCommentsInComponent(String componentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
 
     /**
@@ -208,5 +202,5 @@
      * @throws ComponentRegistryException
      */
-    Comment getSpecifiedCommentInComponent(String componentId, String commentId, Principal principal) throws ComponentRegistryException;
+    Comment getSpecifiedCommentInComponent(String componentId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
 
     /**
@@ -219,6 +213,6 @@
      * @throws DeleteFailedException
      */
-    public void deleteComment(String commentId, Principal principal) throws IOException, ComponentRegistryException, UserUnauthorizedException,
-	    DeleteFailedException;
+    public void deleteComment(String commentId) throws IOException, ComponentRegistryException, UserUnauthorizedException,
+	    DeleteFailedException, ItemNotFoundException;
 
     /**
@@ -239,3 +233,6 @@
      */
     List<String> getAllNonDeletedComponentIds();
+    
+    Boolean isItemPublic(String id) throws ItemNotFoundException;
+    
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistryFactory.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistryFactory.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistryFactory.java	(revision 5549)
@@ -23,9 +23,11 @@
      * @return
      */
-    ComponentRegistry getComponentRegistry(ComponentStatus status, Owner owner, UserCredentials credentials) throws UserUnauthorizedException;
-
-    ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, ComponentStatus status, Owner owner);
+    ComponentRegistry getComponentRegistry(RegistrySpace space, Owner owner, UserCredentials credentials, Number groupId) throws UserUnauthorizedException;
 
     ComponentRegistry getPublicRegistry();
+    
+    ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, Owner owner);
+    
+    ComponentRegistry getBaseRegistry(UserCredentials credentials);
 
     RegistryUser getOrCreateUser(UserCredentials credentials);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentStatus.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentStatus.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentStatus.java	(revision 5549)
@@ -7,34 +7,10 @@
 public enum ComponentStatus {
 
-    /**
-     * Private mode, editable non-public
-     */
-    PRIVATE(false, true),
-    /**
-     * Development mode, editable and publicly visible
-     */
-    DEVELOPMENT(false, true),
-    /**
-     * Published mode, non-editable and publicly visible
-     */
-    PUBLISHED(true, false),
-    /**
-     * Deprecated mode, non-editable and not publicly listed
-     */
-    DEPRECATED(false, false);
-    final boolean publiclyListable;
-    final boolean editable;
-
-    private ComponentStatus(boolean publiclyListable, boolean editable) {
-	this.publiclyListable = publiclyListable;
-	this.editable = editable;
-    }
-
-    public boolean isEditable() {
-	return editable;
-    }
-
-    public boolean isPubliclyListable() {
-	return publiclyListable;
-    }
+   
+    DEVELOPMENT,
+   
+    PRIDUCTION,
+    
+    DEPRECATED;
+    
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/Configuration.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/Configuration.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/Configuration.java	(revision 5549)
@@ -74,9 +74,18 @@
     }
 
+    public boolean isAdminUser(String name) {
+	if (name != null) {
+	    return name.trim().length() > 0 // user name must be set (in case an empty entry is in admin users list)
+		    && adminUsers.contains(name);
+	}
+	return false;
+    }
+    
     public void setAdminUsers(Collection<String> adminUsers) {
 	LOG.debug("Setting adminUsers to {}", Arrays.toString(adminUsers.toArray()));
 	this.adminUsers = adminUsers;
     }
-
+    
+   
     /**
      *
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ItemNotFoundException.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ItemNotFoundException.java	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ItemNotFoundException.java	(revision 5549)
@@ -0,0 +1,17 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package clarin.cmdi.componentregistry;
+
+/**
+ *
+ * @author olhsha
+ */
+public class ItemNotFoundException  extends Exception {
+
+    public ItemNotFoundException(String message) {
+	super(message);
+    }
+    
+}
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/NullIdException.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/NullIdException.java	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/NullIdException.java	(revision 5549)
@@ -0,0 +1,17 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package clarin.cmdi.componentregistry;
+
+/**
+ *
+ * @author olhsha
+ */
+public class NullIdException extends Exception{
+    
+    public NullIdException(String message){
+        super(message);
+    }
+    
+}
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RegistrySpace.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RegistrySpace.java	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RegistrySpace.java	(revision 5549)
@@ -0,0 +1,21 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package clarin.cmdi.componentregistry;
+
+/**
+ *
+ * @author olhsha
+ */
+public enum RegistrySpace {    
+     
+    PRIVATE,    
+    
+    PUBLISHED,
+   
+    GROUP,
+    
+    REVIEW;
+    
+}
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java	(revision 5549)
@@ -29,6 +29,7 @@
 import clarin.cmdi.componentregistry.ComponentRegistryException;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.RegistrySpace;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.impl.database.AdminRegistry;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -43,5 +44,5 @@
     private final static Logger LOG = LoggerFactory.getLogger(AdminHomePage.class);
     private final CMDItemInfo info;
-    private final LinkTree tree;
+    private LinkTree tree;
     private transient AdminRegistry adminRegistry = new AdminRegistry();
     @SpringBean(name = "componentRegistryFactory")
@@ -53,246 +54,246 @@
 
     public AdminHomePage(final PageParameters parameters) throws ComponentRegistryException {
-	super(parameters);
-	adminRegistry.setComponentRegistryFactory(componentRegistryFactory);
-	adminRegistry.setComponentDao(componentDao);
-	adminRegistry.setMarshaller(marshaller);
-	info = new CMDItemInfo(marshaller);
-	addLinks();
-	final FeedbackPanel feedback = new FeedbackPanel("feedback");
-	feedback.setOutputMarkupId(true);
-	add(feedback);
-	Form form = new ItemEditForm("form");
-	add(form);
-
-	Button deleteButton = new AjaxFallbackButton("delete", form) {
-
-	    @Override
-	    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
-		CMDItemInfo info = (CMDItemInfo) form.getModelObject();
-		info("deleting:" + info.getName());
-		Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
-		try {
-		    adminRegistry.delete(info, userPrincipal);
-		    info("Item deleted.");
-		    reloadTreeModel(info);
-		} catch (SubmitFailedException e) {
-		    LOG.error("Admin: ", e);
-		    error("Cannot delete: " + info.getName() + "\n error=" + e);
-		}
-		if (target != null) {
-		    target.addComponent(form);
-		    target.addComponent(tree);
-		    target.addComponent(feedback);
-		}
-	    }
-
-	    @Override
-	    public boolean isEnabled() {
-		return info.isDeletable();
-
-	    }
-	;
-	};
+        super(parameters);
+        adminRegistry.setComponentRegistryFactory(componentRegistryFactory);
+        adminRegistry.setComponentDao(componentDao);
+        adminRegistry.setMarshaller(marshaller);
+        info = new CMDItemInfo(marshaller);
+        addLinks();
+        final FeedbackPanel feedback = new FeedbackPanel("feedback");
+        feedback.setOutputMarkupId(true);
+        add(feedback);
+        Form form = new ItemEditForm("form");
+        add(form);
+
+        Button deleteButton = new AjaxFallbackButton("delete", form) {
+            @Override
+            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
+                info("deleting:" + info.getName());
+                Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
+                try {
+                    adminRegistry.delete(info, userPrincipal);
+                    info("Item deleted.");
+                    reloadTreeModel(info);
+                } catch (Exception e) {
+                    LOG.error("Admin: ", e);
+                    error("Cannot delete: " + info.getName() + "\n error=" + e);
+                }
+                if (target != null) {
+                    target.addComponent(form);
+                    target.addComponent(tree);
+                    target.addComponent(feedback);
+                }
+            }
+
+            @Override
+            public boolean isEnabled() {
+                return info.isDeletable();
+
+            }
+        ;
+        };
 	form.add(deleteButton);
 
-	Button undeleteButton = new AjaxFallbackButton("undelete", form) {
-
-	    @Override
-	    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
-		CMDItemInfo info = (CMDItemInfo) form.getModelObject();
-		info("undeleting:" + info.getName());
-		try {
-		    adminRegistry.undelete(info);
-		    info("Item put back.");
-		    reloadTreeModel(info);
-		} catch (SubmitFailedException e) {
-		    LOG.error("Admin: ", e);
-		    error("Cannot undelete: " + info.getName() + "\n error=" + e);
-		}
-		if (target != null) {
-		    target.addComponent(form);
-		    target.addComponent(tree);
-		    target.addComponent(feedback);
-		}
-	    }
-
-	    @Override
-	    public boolean isEnabled() {
-		return info.isUndeletable();
-	    }
-	};
-	form.add(undeleteButton);
-
-	CheckBox forceUpdateCheck = new CheckBox("forceUpdate");
-	form.add(forceUpdateCheck);
-
-	Button submitButton = new AjaxFallbackButton("submit", form) {
-
-	    @Override
-	    protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
-		CMDItemInfo info = (CMDItemInfo) form.getModelObject();
-		Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
-		info("submitting:" + info.getName() + " id=(" + info.getDataNode().getDescription().getId() + ")");
-		try {
-		    adminRegistry.submitFile(info, userPrincipal);
-		    info("submitting done.");
-		    reloadTreeModel(info);
-		} catch (SubmitFailedException e) {
-		    LOG.error("Admin: ", e);
-		    error("Cannot submit: " + info.getName() + "\n error=" + e);
-		}
-		if (target != null) {
-		    target.addComponent(form);
-		    target.addComponent(tree);
-		    target.addComponent(feedback);
-		}
-	    }
-
-	    @Override
-	    public boolean isEnabled() {
-		return info.isEditable();
-	    }
-	};
-	form.add(submitButton);
-
-	tree = createTree("tree", form, createDBTreeModel());
-	add(tree);
-	add(new Link("expandAll") {
-
-	    @Override
-	    public void onClick() {
-		tree.getTreeState().expandAll();
-	    }
-	});
-
-	add(new Link("collapseAll") {
-
-	    @Override
-	    public void onClick() {
-		tree.getTreeState().collapseAll();
-	    }
-	});
-
-    }
-
-    private void reloadTreeModel(CMDItemInfo info) {
-	try {
-	    tree.setModelObject(createDBTreeModel());
-	} catch (ComponentRegistryException e) {
-	    LOG.error("Admin: ", e);
-	    error("Cannot reload tree: " + info.getName() + "\n error=" + e);
-	}
+        Button undeleteButton = new AjaxFallbackButton("undelete", form) {
+            @Override
+            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
+                info("undeleting:" + info.getName());
+                try {
+                    adminRegistry.undelete(info);
+                    info("Item put back.");
+                    reloadTreeModel(info);
+                } catch (Exception e) {
+                    LOG.error("Admin: ", e);
+                    error("Cannot undelete: " + info.getName() + "\n error=" + e);
+                }
+                if (target != null) {
+                    target.addComponent(form);
+                    target.addComponent(tree);
+                    target.addComponent(feedback);
+                }
+            }
+
+            @Override
+            public boolean isEnabled() {
+                return info.isUndeletable();
+            }
+        };
+        form.add(undeleteButton);
+
+        CheckBox forceUpdateCheck = new CheckBox("forceUpdate");
+        form.add(forceUpdateCheck);
+
+        Button submitButton = new AjaxFallbackButton("submit", form) {
+            @Override
+            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
+                Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
+                info("submitting:" + info.getName() + " id=(" + info.getDataNode().getDescription().getId() + ")");
+                try {
+                    adminRegistry.submitFile(info, userPrincipal);
+                    info("submitting done.");
+                    reloadTreeModel(info);
+                } catch (Exception e) {
+                    LOG.error("Admin: ", e);
+                    error("Cannot submit: " + info.getName() + "\n error=" + e);
+                }
+                if (target != null) {
+                    target.addComponent(form);
+                    target.addComponent(tree);
+                    target.addComponent(feedback);
+                }
+            }
+
+            @Override
+            public boolean isEnabled() {
+                return info.isEditable();
+            }
+        };
+        form.add(submitButton);
+
+
+
+
+        try {
+            tree = createTree("tree", form, createDBTreeModel());
+            add(tree);
+            add(new Link("expandAll") {
+                @Override
+                public void onClick() {
+                    tree.getTreeState().expandAll();
+                }
+            });
+
+            add(new Link("collapseAll") {
+                @Override
+                public void onClick() {
+                    tree.getTreeState().collapseAll();
+                }
+            });
+
+        } catch (UserUnauthorizedException e) {            
+            LOG.error("Admin: ", e);
+            error("Cannot create tree: error = " + e);
+        }
+        
+    }
+
+    private void reloadTreeModel(CMDItemInfo info) throws UserUnauthorizedException {
+        try {
+            tree.setModelObject(createDBTreeModel());
+        } catch (ComponentRegistryException e) {
+            LOG.error("Admin: ", e);
+            error("Cannot reload tree: " + info.getName() + "\n error=" + e);
+        }
     }
 
     private void addLinks() {
-	add(new Label("linksMessage", "Browse the data below or choose on of the following options:"));
-	add(new Link("massMigrate") {
-
-	    @Override
-	    public void onClick() {
-		setResponsePage(MassMigratePage.class);
-	    }
-	});
-	add(new Link("log") {
-
-	    @Override
-	    public void onClick() {
-		setResponsePage(ViewLogPage.class);
-	    }
-	});
-	add(new Link("statistics") {
-
-	    @Override
-	    public void onClick() {
-		setResponsePage(StatisticsPage.class);
-	    }
-	});
+        add(new Label("linksMessage", "Browse the data below or choose on of the following options:"));
+        add(new Link("massMigrate") {
+            @Override
+            public void onClick() {
+                setResponsePage(MassMigratePage.class);
+            }
+        });
+        add(new Link("log") {
+            @Override
+            public void onClick() {
+                setResponsePage(ViewLogPage.class);
+            }
+        });
+        add(new Link("statistics") {
+            @Override
+            public void onClick() {
+                setResponsePage(StatisticsPage.class);
+            }
+        });
     }
 
     private LinkTree createTree(String id, final Form form, TreeModel treeModel) {
-	final LinkTree adminTree = new LinkTree(id, treeModel) {
-
-	    @Override
-	    protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
-		super.onNodeLinkClicked(node, tree, target);
-		ITreeState treeState = tree.getTreeState();
-		if (treeState.isNodeExpanded(node)) {
-		    treeState.collapseNode(node);
-		} else {
-		    treeState.expandNode(node);
-		}
-		DisplayDataNode dn = (DisplayDataNode) ((DefaultMutableTreeNode) node).getUserObject();
-		info.setDataNode(dn);
-		BaseDescription desc = dn.getDescription();
-		if (desc != null) {
-		    String content = componentDao.getContent(dn.isDeleted(), desc.getId());
-		    info.setContent(content);
-		}
-		if (target != null) {
-		    target.addComponent(form);
-		}
-	    }
-	};
-	return adminTree;
+        final LinkTree adminTree = new LinkTree(id, treeModel) {
+            @Override
+            protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
+                super.onNodeLinkClicked(node, tree, target);
+                ITreeState treeState = tree.getTreeState();
+                if (treeState.isNodeExpanded(node)) {
+                    treeState.collapseNode(node);
+                } else {
+                    treeState.expandNode(node);
+                }
+                DisplayDataNode dn = (DisplayDataNode) ((DefaultMutableTreeNode) node).getUserObject();
+                info.setDataNode(dn);
+                BaseDescription desc = dn.getDescription();
+                if (desc != null) {
+                    String content = componentDao.getContent(dn.isDeleted(), desc.getId());
+                    info.setContent(content);
+                }
+                if (target != null) {
+                    target.addComponent(form);
+                }
+            }
+        };
+        return adminTree;
     }
 
     private class ItemEditForm extends Form<CMDItemInfo> {
 
-	public ItemEditForm(String name) {
-	    super(name);
-	    CompoundPropertyModel model = new CompoundPropertyModel(info);
-	    setModel(model);
-
-	    TextArea descriptionArea = new TextArea("description");
-	    descriptionArea.setOutputMarkupId(true);
-	    add(descriptionArea);
-	    TextArea contentArea = new TextArea("content");
-	    contentArea.setOutputMarkupId(true);
-	    add(contentArea);
-	}
-    }
-
-    private TreeModel createDBTreeModel() throws ComponentRegistryException {
-	DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new DisplayDataNode("ComponentRegistry", false));
-	DefaultMutableTreeNode publicNode = new DefaultMutableTreeNode(new DisplayDataNode("Public", false));
-	rootNode.add(publicNode);
-	ComponentRegistry publicRegistry = componentRegistryFactory.getPublicRegistry();
-	add(publicNode, publicRegistry);
-	List<ComponentRegistry> userRegistries = componentRegistryFactory.getAllUserRegistries();
-	for (ComponentRegistry registry : userRegistries) {
-	    DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(new DisplayDataNode(registry.getName(), false));
-	    rootNode.add(userNode);
-	    add(userNode, registry);
-	}
-	TreeModel model = new DefaultTreeModel(rootNode);
-	return model;
-    }
-
-    private void add(DefaultMutableTreeNode parent, ComponentRegistry registry) throws ComponentRegistryException {
-	DefaultMutableTreeNode componentsNode = new DefaultMutableTreeNode(new DisplayDataNode("Components", false));
-	parent.add(componentsNode);
-	add(componentsNode, registry.getComponentDescriptions(), false, registry.getStatus());
-
-	DefaultMutableTreeNode profilesNode = new DefaultMutableTreeNode(new DisplayDataNode("Profiles", false));
-	parent.add(profilesNode);
-	add(profilesNode, registry.getProfileDescriptions(), false, registry.getStatus());
-
-	DefaultMutableTreeNode deletedCompNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Components", true));
-	parent.add(deletedCompNode);
-
-	List<ComponentDescription> deletedComponentDescriptions = registry.getDeletedComponentDescriptions();
-	add(deletedCompNode, deletedComponentDescriptions, true, registry.getStatus());
-
-	DefaultMutableTreeNode deletedProfNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Profiles", true));
-	parent.add(deletedProfNode);
-	List<ProfileDescription> deletedProfileDescriptions = registry.getDeletedProfileDescriptions();
-	add(deletedProfNode, deletedProfileDescriptions, true, registry.getStatus());
-    }
-
-    private void add(DefaultMutableTreeNode parent, List<? extends BaseDescription> descs, boolean isDeleted, ComponentStatus status) {
-	for (BaseDescription desc : descs) {
-	    DefaultMutableTreeNode child = new DefaultMutableTreeNode(new DisplayDataNode(desc.getName(), isDeleted, desc, status));
-	    parent.add(child);
-	}
+        public ItemEditForm(String name) {
+            super(name);
+            CompoundPropertyModel model = new CompoundPropertyModel(info);
+            setModel(model);
+
+            TextArea descriptionArea = new TextArea("description");
+            descriptionArea.setOutputMarkupId(true);
+            add(descriptionArea);
+            TextArea contentArea = new TextArea("content");
+            contentArea.setOutputMarkupId(true);
+            add(contentArea);
+        }
+    }
+
+    private TreeModel createDBTreeModel() throws ComponentRegistryException, UserUnauthorizedException {
+        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new DisplayDataNode("ComponentRegistry", false));
+        DefaultMutableTreeNode publicNode = new DefaultMutableTreeNode(new DisplayDataNode("Public", false));
+        rootNode.add(publicNode);
+        ComponentRegistry publicRegistry = componentRegistryFactory.getPublicRegistry();
+        add(publicNode, publicRegistry);
+        List<ComponentRegistry> userRegistries = componentRegistryFactory.getAllUserRegistries();
+        for (ComponentRegistry registry : userRegistries) {
+            DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(new DisplayDataNode(registry.getName(), false));
+            rootNode.add(userNode);
+            add(userNode, registry);
+        }
+        TreeModel model = new DefaultTreeModel(rootNode);
+        return model;
+    }
+
+    private void add(DefaultMutableTreeNode parent, ComponentRegistry registry) throws ComponentRegistryException, UserUnauthorizedException {
+        DefaultMutableTreeNode componentsNode = new DefaultMutableTreeNode(new DisplayDataNode("Components", false));
+        parent.add(componentsNode);
+        add(componentsNode, registry.getComponentDescriptions(), false, registry.getRegistrySpace());
+
+        DefaultMutableTreeNode profilesNode = new DefaultMutableTreeNode(new DisplayDataNode("Profiles", false));
+        parent.add(profilesNode);
+        add(profilesNode, registry.getProfileDescriptions(), false, registry.getRegistrySpace());
+
+        DefaultMutableTreeNode deletedCompNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Components", true));
+        parent.add(deletedCompNode);
+
+        List<ComponentDescription> deletedComponentDescriptions = registry.getDeletedComponentDescriptions();
+        add(deletedCompNode, deletedComponentDescriptions, true, registry.getRegistrySpace());
+
+        DefaultMutableTreeNode deletedProfNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Profiles", true));
+        parent.add(deletedProfNode);
+        List<ProfileDescription> deletedProfileDescriptions = registry.getDeletedProfileDescriptions();
+        add(deletedProfNode, deletedProfileDescriptions, true, registry.getRegistrySpace());
+    }
+
+    private void add(DefaultMutableTreeNode parent, List<? extends BaseDescription> descs, boolean isDeleted, RegistrySpace space) {
+        for (BaseDescription desc : descs) {
+            DefaultMutableTreeNode child = new DefaultMutableTreeNode(new DisplayDataNode(desc.getName(), isDeleted, desc, space));
+            parent.add(child);
+        }
     }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/CMDItemInfo.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/CMDItemInfo.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/CMDItemInfo.java	(revision 5549)
@@ -1,8 +1,8 @@
 package clarin.cmdi.componentregistry.frontend;
 
-import clarin.cmdi.componentregistry.ComponentStatus;
 import java.io.Serializable;
 
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.model.BaseDescription;
 
@@ -99,6 +99,6 @@
 
     
-    public ComponentStatus getStatus() {
-	return displayNode.getStatus();
+    public RegistrySpace getSpace() {
+	return displayNode.getSpace();
     }
 	
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/DisplayDataNode.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/DisplayDataNode.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/DisplayDataNode.java	(revision 5549)
@@ -2,4 +2,5 @@
 
 import clarin.cmdi.componentregistry.ComponentStatus;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import java.io.Serializable;
 
@@ -12,16 +13,16 @@
     private final boolean isDeleted;
     private BaseDescription desc;
-    private final ComponentStatus status;
+    private final RegistrySpace space;
 
     public DisplayDataNode(String name, boolean isDeleted) {
 	// TODO: what is sensible default status?
-	this(name, isDeleted, null, ComponentStatus.PRIVATE);
+	this(name, isDeleted, null, RegistrySpace.PRIVATE);
     }
 
-    public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, ComponentStatus status) {
+    public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, RegistrySpace space) {
 	this.name = name;
 	this.isDeleted = isDeleted;
 	this.desc = desc;
-	this.status = status;
+	this.space = space;
     }
 
@@ -44,6 +45,6 @@
     }
 
-    public ComponentStatus getStatus() {
-	return status;
+    public RegistrySpace getSpace() {
+	return space;
     }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/StatisticsPage.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/StatisticsPage.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/StatisticsPage.java	(revision 5549)
@@ -14,4 +14,6 @@
 import clarin.cmdi.componentregistry.ComponentRegistryException;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
+import clarin.cmdi.componentregistry.RegistrySpace;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.components.CMDComponentType;
@@ -40,12 +42,12 @@
     }
 
-    public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException {
+    public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException, UserUnauthorizedException {
         super(pageParameters);
-        ComponentRegistry registry = componentRegistryFactory.getPublicRegistry();
+        ComponentRegistry registry = componentRegistryFactory.getComponentRegistry(RegistrySpace.PUBLISHED, null, null, null);
         addLinks();
         displayStatistics(registry);
     }
 
-    private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException {
+    private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException, UserUnauthorizedException {
         List<ProfileDescription> profileList = registry.getProfileDescriptions();
         RepeatingView repeating = new RepeatingView("repeating");
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentRegistryImplBase.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentRegistryImplBase.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentRegistryImplBase.java	(revision 5549)
@@ -14,11 +14,10 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
-import clarin.cmdi.componentregistry.DeleteFailedException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
-import clarin.cmdi.componentregistry.components.CMDComponentType;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec.Header;
 import clarin.cmdi.componentregistry.model.BaseDescription;
-import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
 
@@ -33,32 +32,5 @@
     protected abstract MDMarshaller getMarshaller();
 
-    @Override
-    public List<ComponentDescription> getUsageInComponents(String componentId) throws ComponentRegistryException {
-        LOG.debug("Checking usage of component {} in components", componentId);
-        List<ComponentDescription> result = new ArrayList<ComponentDescription>();
-        List<String> ids = getAllNonDeletedComponentIds();
-        for (String id : ids) {
-            CMDComponentSpec spec = getMDComponent(id);
-            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
-                LOG.debug("Component {} used in component {}", componentId, spec.getHeader().getID());
-                result.add(getComponentDescription(id));
-            }
-        }
-        return result;
-    }
-
-    @Override
-    public List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException {
-        LOG.debug("Checking usage of component {} in profiles", componentId);
-        List<ProfileDescription> result = new ArrayList<ProfileDescription>();
-        for (String id : getAllNonDeletedProfileIds()) {
-            CMDComponentSpec profile = getMDProfile(id);
-            if (profile != null && hasComponentId(componentId, profile.getCMDComponent())) {
-                LOG.debug("Component {} used in profile {}", componentId, profile.getHeader().getID());
-                result.add(getProfileDescription(id));
-            }
-        }
-        return result;
-    }
+    
 
     /**
@@ -70,5 +42,5 @@
     @Override
     public List<ProfileDescription> getProfileDescriptionsForMetadaEditor() throws ComponentRegistryException {
-	// TODO: Below can also be done by accepting and passing a parameter in the ProfileDescriptionDaoImpl, should have better performance
+        // TODO: Below can also be done by accepting and passing a parameter in the ProfileDescriptionDaoImpl, should have better performance
 
         // Get all profile descriptions
@@ -77,8 +49,13 @@
         ArrayList<ProfileDescription> descriptions = new ArrayList<ProfileDescription>();
         for (String id : descriptionsCollectionIds) {
-            ProfileDescription profile = getProfileDescription(id);
-            if (profile.isShowInEditor()) {
-                descriptions.add(profile);
+            try {
+                ProfileDescription profile = getProfileDescriptionAccessControlled(id);
+                if (profile.isShowInEditor()) {
+                    descriptions.add(profile);
+                }
+            } catch (UserUnauthorizedException e) {
+            } catch (ItemNotFoundException e) {
             }
+
         }
         // Return filtered list
@@ -102,22 +79,7 @@
     }
 
-    protected static boolean findComponentId(String componentId, List<CMDComponentType> componentReferences) {
-        for (CMDComponentType cmdComponent : componentReferences) {
-            if (hasComponentId(componentId, cmdComponent)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    private static boolean hasComponentId(String componentId, CMDComponentType cmdComponent) {
-        if (componentId.equals(cmdComponent.getComponentId())) {
-            return true;
-        } else if (findComponentId(componentId, cmdComponent.getCMDComponent())) {
-            return true;
-        } else {
-            return false;
-        }
-    }
+    
+   
+    
 
     protected void writeXsd(CMDComponentSpec expandedSpec, OutputStream outputStream) {
@@ -135,24 +97,3 @@
     }
 
-    protected void checkStillUsed(String componentId) throws DeleteFailedException, ComponentRegistryException {
-        for (String id : getAllNonDeletedProfileIds()) {
-            CMDComponentSpec spec = getMDProfile(id);
-            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
-                LOG.warn("Cannot delete component {}, still used in profile {} and possibly other profiles and/or components", componentId, spec.getHeader().getID());
-                // Profile match - throw
-                throw new DeleteFailedException("Component is still in use by other components or profiles. Request component usage for details.");
-            }
-        }
-
-        LOG.debug("Component {} is not used in any profiles", componentId);
-
-        for (String id : getAllNonDeletedComponentIds()) {
-            CMDComponentSpec spec = getMDComponent(id);
-            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
-                LOG.warn("Cannot delete component {}, still used in component {} and possibly other components", componentId, spec.getHeader().getID());
-                // Component match -> throw
-                throw new DeleteFailedException("Component is still in use by one or more other components. Request component usage for details.");
-            }
-        }
-    }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentUtils.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentUtils.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentUtils.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.impl;
 
+import clarin.cmdi.componentregistry.ComponentRegistryException;
 import java.text.ParseException;
 import java.util.ArrayList;
@@ -11,5 +12,4 @@
 import org.springframework.beans.BeanUtils;
 
-import clarin.cmdi.componentregistry.DatesHelper;
 import clarin.cmdi.componentregistry.model.BaseDescription;
 import clarin.cmdi.componentregistry.model.ComponentDescription;
@@ -18,58 +18,56 @@
 /**
  * Utilities for working with {@link BaseDescription}s
- * 
+ *
  * @author george.georgovassilis@mpi.nl
- * 
+ *
  */
 public class ComponentUtils {
 
     public static boolean isProfileId(String componentId) {
-	return ("" + componentId).startsWith(ProfileDescription.PROFILE_PREFIX);
+        return ("" + componentId).startsWith(ProfileDescription.PROFILE_PREFIX);
     }
 
     public static boolean isComponentId(String componentId) {
-	return ("" + componentId)
-		.startsWith(ComponentDescription.COMPONENT_PREFIX);
+        return ("" + componentId)
+                .startsWith(ComponentDescription.COMPONENT_PREFIX);
     }
 
     public static void copyPropertiesFrom(BaseDescription from, BaseDescription to) {
-	BeanUtils.copyProperties(from, to);
+        BeanUtils.copyProperties(from, to);
     }
 
     public static Date getDate(String registrationDate) throws ParseException {
-	return DateUtils.parseDate(registrationDate,
-		new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
-			.getPattern() });
+        return DateUtils.parseDate(registrationDate,
+                new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
+                    .getPattern()});
     }
 
     public static String createPublicHref(String href) {
-	String result = href;
-	if (href != null) {
-	    int index = href.indexOf("?");
-	    if (index != -1) { // strip off query params the rest should be the
-			       // public href.
-		result = href.substring(0, index);
-	    }
-	}
-	return result;
+        String result = href;
+        if (href != null) {
+            int index = href.indexOf("?");
+            if (index != -1) { // strip off query params the rest should be the
+                // public href.
+                result = href.substring(0, index);
+            }
+        }
+        return result;
     }
-
     /**
-     * Compares two descriptions by the their value as returned by
-     * {@link BaseDescription#getName()
+     * Compares two descriptions by the their value as returned by      {@link BaseDescription#getName()
      * }
      */
     public static final Comparator<? super BaseDescription> COMPARE_ON_NAME = new Comparator<BaseDescription>() {
-	@Override
-	public int compare(BaseDescription o1, BaseDescription o2) {
-	    int result = 0;
-	    if (o1.getName() != null && o2.getName() != null) {
-		result = o1.getName().compareToIgnoreCase(o2.getName());
-	    }
-	    if (o1.getId() != null && result == 0) {
-		result = o1.getId().compareTo(o2.getId());
-	    }
-	    return result;
-	}
+        @Override
+        public int compare(BaseDescription o1, BaseDescription o2) {
+            int result = 0;
+            if (o1.getName() != null && o2.getName() != null) {
+                result = o1.getName().compareToIgnoreCase(o2.getName());
+            }
+            if (o1.getId() != null && result == 0) {
+                result = o1.getId().compareTo(o2.getId());
+            }
+            return result;
+        }
     };
     /**
@@ -78,49 +76,68 @@
      */
     public static final Comparator<? super BaseDescription> COMPARE_ON_DATE = new Comparator<BaseDescription>() {
-	/**
-	 * @returns 1 if o11 is older than o2, returns -1 if o1 is younger than
-	 *          o2
-	 */
-	@Override
-	public int compare(BaseDescription o1, BaseDescription o2) {
-	    return o1.getRegistrationDate().compareTo(o2.getRegistrationDate());
-	}
+        /**
+         * @returns 1 if o11 is older than o2, returns -1 if o1 is younger than
+         * o2
+         */
+        @Override
+        public int compare(BaseDescription o1, BaseDescription o2) {
+            return o1.getRegistrationDate().compareTo(o2.getRegistrationDate());
+        }
     };
 
-    public static ProfileDescription toProfile(BaseDescription baseDescription) {
-	if (baseDescription == null)
-	    return null;
-	ProfileDescription copy = new ProfileDescription();
-	BeanUtils.copyProperties(baseDescription, copy);
-	return copy;
+    public static ProfileDescription toProfile(BaseDescription baseDescription) throws ComponentRegistryException {
+        if (baseDescription == null) {
+            return null;
+        }
+        if (baseDescription.getId().startsWith(ProfileDescription.PROFILE_PREFIX)) {
+            ProfileDescription copy = new ProfileDescription();
+            BeanUtils.copyProperties(baseDescription, copy);
+            return copy;
+        } else {
+            throw new ComponentRegistryException("The item is not a profile.");
+        }
     }
 
-    public static ComponentDescription toComponent(BaseDescription baseDescription) {
-	if (baseDescription == null)
-	    return null;
-	ComponentDescription copy = new ComponentDescription();
-	BeanUtils.copyProperties(baseDescription, copy);
-	return copy;
+    public static ComponentDescription toComponent(BaseDescription baseDescription) throws ComponentRegistryException {
+        if (baseDescription == null) {
+            return null;
+        }
+        if (baseDescription.getId().startsWith(ComponentDescription.COMPONENT_PREFIX)) {
+            ComponentDescription copy = new ComponentDescription();
+            BeanUtils.copyProperties(baseDescription, copy);
+            return copy;
+        } else {
+            throw new ComponentRegistryException("The item is not a component");
+        }
     }
 
     public static List<ProfileDescription> toProfiles(
-	    List<BaseDescription> baseDescription) {
-	if (baseDescription == null)
-	    return null;
-	List<ProfileDescription> list = new ArrayList<ProfileDescription>();
-	for (BaseDescription c : baseDescription)
-	    list.add(toProfile(c));
-	return list;
+            List<BaseDescription> baseDescription) {
+        if (baseDescription == null) {
+            return null;
+        }
+        List<ProfileDescription> list = new ArrayList<ProfileDescription>();
+        for (BaseDescription c : baseDescription) {
+            try {
+                list.add(toProfile(c));
+            } catch (ComponentRegistryException e) {
+            }
+        }
+        return list;
     }
 
     public static List<ComponentDescription> toComponents(
-	    List<BaseDescription> baseDescription) {
-	if (baseDescription == null)
-	    return null;
-	List<ComponentDescription> list = new ArrayList<ComponentDescription>();
-	for (BaseDescription c : baseDescription)
-	    list.add(toComponent(c));
-	return list;
+            List<BaseDescription> baseDescription) {
+        if (baseDescription == null) {
+            return null;
+        }
+        List<ComponentDescription> list = new ArrayList<ComponentDescription>();
+        for (BaseDescription c : baseDescription) {
+            try {
+                list.add(toComponent(c));
+            } catch (ComponentRegistryException e) {
+            }
+        }
+        return list;
     }
-
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java	(revision 5549)
@@ -14,8 +14,8 @@
 import clarin.cmdi.componentregistry.ComponentRegistryException;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.DeleteFailedException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
-import clarin.cmdi.componentregistry.OwnerUser;
+import clarin.cmdi.componentregistry.UserCredentials;
 import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
@@ -54,5 +54,10 @@
 
     public void submitFile(CMDItemInfo info, Principal userPrincipal)
-	    throws SubmitFailedException {
+	    throws SubmitFailedException, UserUnauthorizedException {
+        if (userPrincipal == null) {
+            LOG.info("Null user principal, nothings is submitted.");
+            return;
+        }
+        
 	try {
 	    BaseDescription originalDescription = info.getDataNode()
@@ -72,8 +77,6 @@
 		    IOUtils.toInputStream(info.getContent(), "UTF-8"), null);
 	    checkId(originalDescription.getId(), description.getId());
-
-	    int result = getRegistry(userPrincipal, originalDescription, info)
-		    .update(description, spec, userPrincipal,
-			    info.isForceUpdate());
+            ComponentRegistry cr = this.getRegistry(new UserCredentials(userPrincipal));
+	    int result = cr.update(description, spec, info.isForceUpdate());
 	    if (result < 0) {
 		throw new SubmitFailedException(
@@ -83,4 +86,6 @@
 	    throw new SubmitFailedException(e);
 	} catch (IOException e) {
+	    throw new SubmitFailedException(e);
+	} catch (ItemNotFoundException e) {
 	    throw new SubmitFailedException(e);
 	}
@@ -109,5 +114,5 @@
 	BaseDescription desc = info.getDataNode().getDescription();
 	try {
-	    deleteFromRegistry(userPrincipal, desc, info);
+	    this.deleteFromRegistry(userPrincipal, desc, info);
 	    LOG.info("Deleted item: " + id);
 	} catch (IOException e) {
@@ -119,4 +124,6 @@
 	} catch (ComponentRegistryException e) {
 	    throw new SubmitFailedException(e);
+	} catch (ItemNotFoundException e) {
+	    throw new SubmitFailedException(e);
 	}
 
@@ -125,30 +132,23 @@
     private void deleteFromRegistry(Principal userPrincipal,
 	    BaseDescription desc, CMDItemInfo info) throws IOException,
-	    UserUnauthorizedException, ComponentRegistryException {
-	ComponentRegistry registry = getRegistry(userPrincipal, desc, info);
+	    UserUnauthorizedException, ComponentRegistryException, ItemNotFoundException {
+        
+        if (userPrincipal == null) {
+           LOG.info("Bnull user principal, nothing is deleted"); 
+           return;
+        }
+        
+	ComponentRegistry registry = this.getRegistry(new UserCredentials(userPrincipal));
 	LOG.info("Deleting item: " + desc);
 	if (desc.isProfile()) {
-	    registry.deleteMDProfile(desc.getId(), userPrincipal);
+	    registry.deleteMDProfile(desc.getId());
 	} else {
-	    registry.deleteMDComponent(desc.getId(), userPrincipal,
-		    info.isForceUpdate());
+	    registry.deleteMDComponent(desc.getId(), info.isForceUpdate());
 	}
     }
 
-    private ComponentRegistry getRegistry(Principal userPrincipal,
-	    BaseDescription desc, CMDItemInfo info) {
-	ComponentRegistry registry = componentRegistryFactory
-		.getPublicRegistry();
-	// TODO: More generic check
-	if (info.getStatus() == ComponentStatus.PRIVATE /*
-							 * || info.getStatus()
-							 * == ComponentStatus.
-							 * DEVELOPMENT
-							 */) {
-	    registry = componentRegistryFactory.getOtherUserComponentRegistry(
-		    userPrincipal, info.getStatus(),
-		    new OwnerUser(Integer.parseInt(desc.getUserId())));
-	}
-	return registry;
-    }
+    private ComponentRegistry getRegistry(UserCredentials credentials) throws UserUnauthorizedException{
+        return componentRegistryFactory.getBaseRegistry(credentials);
+        }
+    
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java	(revision 5549)
@@ -4,12 +4,14 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.Configuration;
 import clarin.cmdi.componentregistry.DeleteFailedException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
 import clarin.cmdi.componentregistry.Owner;
 import clarin.cmdi.componentregistry.OwnerUser;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
+import clarin.cmdi.componentregistry.components.CMDComponentType;
 import clarin.cmdi.componentregistry.impl.ComponentRegistryImplBase;
 import clarin.cmdi.componentregistry.impl.ComponentUtils;
@@ -17,4 +19,5 @@
 import clarin.cmdi.componentregistry.model.Comment;
 import clarin.cmdi.componentregistry.model.ComponentDescription;
+import clarin.cmdi.componentregistry.model.Group;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
 import clarin.cmdi.componentregistry.model.RegistryUser;
@@ -30,5 +33,4 @@
 import java.io.UnsupportedEncodingException;
 import java.security.Principal;
-import java.text.ParseException;
 import java.util.ArrayList;
 import java.util.Calendar;
@@ -51,5 +53,5 @@
  * Implementation of ComponentRegistry that uses Database Acces Objects for
  * accessing the registry (ergo: a database implementation)
- * 
+ *
  * @author Twan Goosen <twan.goosen@mpi.nl>
  * @author George.Georgovassilis@mpi.nl
@@ -58,748 +60,913 @@
 public class ComponentRegistryDbImpl extends ComponentRegistryImplBase implements ComponentRegistry {
 
-	private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryDbImpl.class);
-	private Owner registryOwner;
-	private ComponentStatus registryStatus;
-	@Autowired
-	private Configuration configuration;
-	@Autowired
-	@Qualifier("componentsCache")
-	private CMDComponentSpecCache componentsCache;
-	@Autowired
-	@Qualifier("profilesCache")
-	private CMDComponentSpecCache profilesCache;
-	// DAO's
-	@Autowired
-	private ComponentDao componentDao;
-	@Autowired
-	private UserDao userDao;
-	@Autowired
-	private CommentsDao commentsDao;
-	@Autowired
-	private MDMarshaller marshaller;
-	@Autowired
-	private GroupService groupService;
-
-	/**
-	 * Default constructor, to use this as a (spring) bean. The public registry
-	 * by default. Use setStatus() and setOwner() to make it another kind of
-	 * registry.
-	 * 
-	 * @see setUser
-	 */
-	public ComponentRegistryDbImpl() throws TransformerException {
-		this.registryStatus = ComponentStatus.PUBLISHED;
-	}
-
-	/**
-	 * Creates a new ComponentRegistry (either public or not) for the provided
-	 * user. Only use for test and/or make sure to inject all dao's and other
-	 * services
-	 * 
-	 * @param userId
-	 *            User id of the user to create registry for. Pass null for
-	 *            public
-	 */
-	public ComponentRegistryDbImpl(ComponentStatus status, Owner owner) {
-		this.registryStatus = status;
-		this.registryOwner = owner;
-	}
-
-	@Override
-	public List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException {
-		try {
-			switch (registryStatus) {
-			// TODO: support other status types
-			case PRIVATE:
-				if (registryOwner == null) {
-					throw new ComponentRegistryException("Private workspace without owner!");
-				}
-				// TODO: Support group space
-				return ComponentUtils.toProfiles(componentDao.getUserspaceProfiles(registryOwner.getId()));
-			case PUBLISHED:
-				return ComponentUtils.toProfiles(componentDao.getPublicProfileDescriptions());
-			default:
-				throw new ComponentRegistryException("Unsupported status type" + registryStatus);
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
-		}
-	}
-
-	@Override
-	public ProfileDescription getProfileDescription(String id) throws ComponentRegistryException {
-		try {
-			return ComponentUtils.toProfile(componentDao.getByCmdId(id, getUserId()));
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
-		}
-	}
-
-	@Override
-	public List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException {
-		try {
-			if (isPublic()) {
-				return ComponentUtils.toComponents(componentDao.getPublicComponentDescriptions());
-			} else {
-				return ComponentUtils.toComponents(componentDao.getUserspaceComponents(getUserId()));
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get component descriptions", ex);
-		}
-	}
-
-	@Override
-	public ComponentDescription getComponentDescription(String id) throws ComponentRegistryException {
-		try {
-			return ComponentUtils.toComponent(componentDao.getByCmdId(id, getUserId()));
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get component description", ex);
-		}
-	}
-
-	@Override
-	public List<Comment> getCommentsInProfile(String profileId, Principal principal) throws ComponentRegistryException {
-		try {
-			if (componentDao.isInRegistry(profileId, getUserId())) {
-				final List<Comment> commentsFromProfile = commentsDao.getCommentsFromComponent(profileId);
-				setCanDeleteInComments(commentsFromProfile, principal);
-				return commentsFromProfile;
-			} else {
-				// Profile does not exist (at least not in this registry)
-				throw new ComponentRegistryException("Profile " + profileId + " does not exist in specified registry");
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException(
-					"Database access error while trying to get list of comments from profile", ex);
-		}
-	}
-
-	@Override
-	public Comment getSpecifiedCommentInProfile(String profileId, String commentId, Principal principal)
-			throws ComponentRegistryException {
-		try {
-			Comment comment = commentsDao.findOne(Long.parseLong(commentId));
-			if (comment != null && profileId.equals(comment.getComponentId())
-					&& componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
-				setCanDeleteInComments(Collections.singleton(comment), principal);
-				return comment;
-			} else {
-				// Comment exists in DB, but profile is not in this registry
-				throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get comment from profile", ex);
-		}
-	}
-
-	@Override
-	public List<Comment> getCommentsInComponent(String componentId, Principal principal)
-			throws ComponentRegistryException {
-		try {
-			if (componentDao.isInRegistry(componentId, getUserId())) {
-				final List<Comment> commentsFromComponent = commentsDao.getCommentsFromComponent(componentId);
-				setCanDeleteInComments(commentsFromComponent, principal);
-				return commentsFromComponent;
-			} else {
-				// Component does not exist (at least not in this registry)
-				throw new ComponentRegistryException("Component " + componentId
-						+ " does not exist in specified registry");
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException(
-					"Database access error while trying to get list of comments from component", ex);
-		}
-	}
-
-	@Override
-	public Comment getSpecifiedCommentInComponent(String componentId, String commentId, Principal principal)
-			throws ComponentRegistryException {
-		try {
-			Comment comment = commentsDao.findOne(Long.parseLong(commentId));
-			if (comment != null && componentId.equals(comment.getComponentId().toString())
-					&& componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
-				setCanDeleteInComments(Collections.singleton(comment), principal);
-				return comment;
-			} else {
-				// Comment does not exists in DB or component is not in this
-				// registry
-				throw new ComponentRegistryException("Comment " + commentId
-						+ " cannot be found in specified registry for specified component");
-			}
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get comment from component", ex);
-		}
-	}
-
-	/**
-	 * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all
-	 * comments in the provided collection for the perspective of the specified
-	 * principal. Comment owners (determined by {@link Comment#getUserId() }) and
-	 * admins can delete, others cannot.
-	 * 
-	 * @param comments
-	 *            comments to configure
-	 * @param principal
-	 *            user to configure for
-	 * @see Comment#isCanDelete()
-	 */
-	private void setCanDeleteInComments(Collection<Comment> comments, Principal principal) {
-		if (principal != null && principal.getName() != null) {
-			final RegistryUser registryUser = userDao.getByPrincipalName(principal.getName());
-			final long registryUserId = registryUser == null ? -1 : registryUser.getId();
-			final boolean isAdmin = registryUser != null && configuration.isAdminUser(principal);
-			for (Comment comment : comments) {
-				comment.setCanDelete(isAdmin || comment.getUserId() == registryUserId);
-			}
-		}
-	}
-
-	@Override
-	public CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException {
-		if (inWorkspace(id)||canCurrentUserAccessDescription(id)) {
-			CMDComponentSpec result = profilesCache.get(id);
-			if (result == null && !profilesCache.containsKey(id)) {
-				result = getUncachedMDProfile(id);
-				profilesCache.put(id, result);
-			}
-			return result;
-		} else {
-			// May exist, but not in this workspace
-			LOG.debug("Could not find profile '{}' in registry '{}'", new Object[] { id, this.toString() });
-			return null;
-		}
-	}
-
-	public CMDComponentSpec getUncachedMDProfile(String id) throws ComponentRegistryException {
-		try {
-			return getUncachedMDComponent(id, componentDao);
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get profile", ex);
-		}
-	}
-
-	@Override
-	public CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException {
-		if (inWorkspace(id)||canCurrentUserAccessDescription(id)) {
-			CMDComponentSpec result = componentsCache.get(id);
-			if (result == null && !componentsCache.containsKey(id)) {
-				result = getUncachedMDComponent(id);
-				componentsCache.put(id, result);
-			}
-			return result;
-		} else {
-			// May exist, but not in this workspace
-			LOG.info("Could not find component '{}' was in registry '{}'", new Object[] { id, this.toString() });
-			return null;
-		}
-	}
-
-	public CMDComponentSpec getUncachedMDComponent(String id) throws ComponentRegistryException {
-		try {
-			return getUncachedMDComponent(id, componentDao);
-		} catch (DataAccessException ex) {
-			throw new ComponentRegistryException("Database access error while trying to get component", ex);
-		}
-	}
-
-	@Override
-	public int register(BaseDescription description, CMDComponentSpec spec) {
-		enrichSpecHeader(spec, description);
-		try {
-			String xml = componentSpecToString(spec);
-			// Convert principal name to user record id
-			Number uid = convertUserInDescription(description);
-			componentDao.insertDescription(description, xml, isPublic(), uid);
-			invalidateCache(description);
-			return 0;
-		} catch (DataAccessException ex) {
-			LOG.error("Database error while registering component", ex);
-			return -1;
-		} catch (JAXBException ex) {
-			LOG.error("Error while registering component", ex);
-			return -2;
-		} catch (UnsupportedEncodingException ex) {
-			LOG.error("Error while registering component", ex);
-			return -3;
-		}
-	}
-
-	@Override
-	public int registerComment(Comment comment, String principalName) throws ComponentRegistryException {
-		try {
-			if (comment.getComponentId() != null && componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
-				// Convert principal name to user record id
-				Number uid = convertUserIdInComment(comment, principalName);
-				// Set date to current date
-				comment.setCommentDate(new Date());
-				comment.setUserId(uid.longValue());
-				commentsDao.saveAndFlush(comment);
-			} else {
-				throw new ComponentRegistryException(
-						"Cannot insert comment into this registry. Unknown profileId or componentId");
-			}
-			return 0;
-		} catch (DataAccessException ex) {
-			LOG.error("Database error while registering component", ex);
-			return -1;
-		}
-	}
-
-	/**
-	 * Calling service sets user id to principle. Our task is to convert this to
-	 * an id for later reference. If none is set and this is a user's workspace,
-	 * set from that user's id.
-	 * 
-	 * It also sets the name in the description according to the display name in
-	 * the database.
-	 * 
-	 * @param description
-	 *            Description containing principle name as userId
-	 * @return Id (from database)
-	 * @throws DataAccessException
-	 */
-	private Number convertUserInDescription(BaseDescription description) throws DataAccessException {
-		Number uid = null;
-		String name = null;
-		if (description.getUserId() != null) {
-			RegistryUser user = userDao.getByPrincipalName(description.getUserId());
-			if (user != null) {
-				uid = user.getId();
-				name = user.getName();
-			}
-		} else {
-			uid = getUserId(); // this can be null as well
-		}
-		if (uid != null) {
-			description.setUserId(uid.toString());
-		}
-		if (name != null) {
-			description.setCreatorName(name);
-		}
-		return uid;
-	}
-
-	/**
-	 * Calling service sets user id to principle. Our task is to convert this to
-	 * an id for later reference. If none is set and this is a user's workspace,
-	 * set from that user's id.
-	 * 
-	 * @param comment
-	 *            Comment containing principle name as userId
-	 * @return Id (from database)
-	 * @throws DataAccessException
-	 */
-	private Number convertUserIdInComment(Comment comment, String principalName) throws DataAccessException,
-			ComponentRegistryException {
-		if (principalName != null) {
-			RegistryUser user = userDao.getByPrincipalName(principalName);
-			if (user != null) {
-				Long id = user.getId();
-				if (id != null) {
-					// Set user id in comment for convenience of calling method
-					comment.setUserId(id);
-					// Set name to user's preferred display name
-					comment.setUserName(user.getName());
-					return id;
-				} else {
-					throw new ComponentRegistryException("Cannot find user with principal name: " + principalName);
-				}
-			}
-		}
-		return null;
-	}
-
-	@Override
-	public int update(BaseDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate) {
-		try {
-			checkAuthorisation(description, principal);
-			checkAge(description, principal);
-			// For public components, check if used in other components or
-			// profiles (unless forced)
-			if (!forceUpdate && this.isPublic() && !description.isProfile()) {
-				checkStillUsed(description.getId());
-			}
-			componentDao.updateDescription(getIdForDescription(description), description, componentSpecToString(spec));
-			invalidateCache(description);
-			return 0;
-		} catch (JAXBException ex) {
-			LOG.error("Error while updating component", ex);
-			return -1;
-		} catch (UnsupportedEncodingException ex) {
-			LOG.error("Error while updating component", ex);
-			return -1;
-		} catch (IllegalArgumentException ex) {
-			LOG.error("Error while updating component", ex);
-			return -1;
-		} catch (UserUnauthorizedException e) {
-			LOG.error("Error while updating component", e);
-			return -1;
-		} catch (DeleteFailedException e) {
-			LOG.error("Error while updating component", e);
-			return -1;
-		} catch (ComponentRegistryException e) {
-			LOG.error("Error while updating component", e);
-			return -1;
-		}
-	}
-
-	@Override
-	public int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal) {
-		int result = 0;
-		if (!isPublic()) { // if already in public workspace there is nothing
-			// todo
-			desc.setHref(ComponentUtils.createPublicHref(desc.getHref()));
-			Number id = getIdForDescription(desc);
-			try {
-				// Update description & content
-				componentDao.updateDescription(id, desc, componentSpecToString(spec));
-				// Set to public
-				componentDao.setPublished(id, true);
-			} catch (DataAccessException ex) {
-				LOG.error("Database error while updating component", ex);
-				return -1;
-			} catch (JAXBException ex) {
-				LOG.error("Error while updating component", ex);
-				return -2;
-			} catch (UnsupportedEncodingException ex) {
-				LOG.error("Error while updating component", ex);
-				return -3;
-			}
-		}
-		return result;
-	}
-
-	@Override
-	public void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException {
-		CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
-		writeXml(expandedSpec, output);
-	}
-
-	@Override
-	public void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException {
-		CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
-		writeXsd(expandedSpec, outputStream);
-	}
-
-	@Override
-	public void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException {
-		CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
-		writeXml(expandedSpec, output);
-	}
-
-	@Override
-	public void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException {
-		CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
-		writeXsd(expandedSpec, outputStream);
-	}
-
-	@Override
-	public void deleteMDProfile(String profileId, Principal principal) throws UserUnauthorizedException,
-			DeleteFailedException, ComponentRegistryException {
-		ProfileDescription desc = getProfileDescription(profileId);
-		if (desc != null) {
-			try {
-				checkAuthorisation(desc, principal);
-				checkAge(desc, principal);
-				componentDao.setDeleted(desc, true);
-				invalidateCache(desc);
-			} catch (DataAccessException ex) {
-				throw new DeleteFailedException("Database access error while trying to delete profile", ex);
-			}
-		}
-	}
-
-	@Override
-	public void deleteMDComponent(String componentId, Principal principal, boolean forceDelete)
-			throws UserUnauthorizedException, DeleteFailedException, ComponentRegistryException {
-		BaseDescription desc = componentDao.getByCmdId(componentId);
-		if (desc != null) {
-			try {
-				checkAuthorisation(desc, principal);
-				checkAge(desc, principal);
-
-				if (!forceDelete) {
-					checkStillUsed(componentId);
-				}
-				componentDao.setDeleted(desc, true);
-				invalidateCache(desc);
-			} catch (DataAccessException ex) {
-				throw new DeleteFailedException("Database access error while trying to delete component", ex);
-			}
-		}
-	}
-
-	/**
-	 * 
-	 * @return whether this is the public registry
-	 * @deprecated use {@link #getStatus() } to check if this is the
-	 *             {@link ComponentStatus#PUBLISHED public registry}
-	 */
-	@Override
-	@Deprecated
-	public boolean isPublic() {
-		return registryStatus == ComponentStatus.PUBLISHED;
-	}
-
-	/**
-	 * @return The user id, or null if there is no owner or it is not a user.
-	 */
-	private Number getUserId() {
-		if (registryOwner instanceof OwnerUser) {
-			return registryOwner.getId();
-		} else {
-			return null;
-		}
-	}
-
-	@Override
-	public Owner getOwner() {
-		return registryOwner;
-	}
-
-	/**
-	 * Sets status and owner of this registry
-	 * 
-	 * @param status
-	 *            new status for registry
-	 * @param owner
-	 *            new owner for registry
-	 */
-	public void setStatus(ComponentStatus status, Owner owner) {
-		setStatus(status);
-		this.registryOwner = owner;
-	}
-
-	public void setStatus(ComponentStatus status) {
-		this.registryStatus = status;
-	}
-
-	@Override
-	public ComponentStatus getStatus() {
-		return registryStatus;
-	}
-
-	private void invalidateCache(BaseDescription description) {
-		if (description.isProfile()) {
-			profilesCache.remove(description.getId());
-		} else {
-			componentsCache.remove(description.getId());
-		}
-	}
-
-	/**
-	 * Looks up description on basis of CMD Id. This will also check if such a
-	 * record even exists.
-	 * 
-	 * @param description
-	 *            Description to look up
-	 * @return Database id for description
-	 * @throws IllegalArgumentException
-	 *             If description with non-existing id is passed
-	 */
-	private Number getIdForDescription(BaseDescription description) throws IllegalArgumentException {
-		Number dbId = null;
-		try {
-			dbId = componentDao.getDbId(description.getId());
-		} catch (DataAccessException ex) {
-			LOG.error("Error getting dbId for component with id " + description.getId(), ex);
-		}
-		if (dbId == null) {
-			throw new IllegalArgumentException("Could not get database Id for description");
-		} else {
-			return dbId;
-		}
-	}
-
-	private String componentSpecToString(CMDComponentSpec spec) throws UnsupportedEncodingException, JAXBException {
-		ByteArrayOutputStream os = new ByteArrayOutputStream();
-		getMarshaller().marshal(spec, os);
-		String xml = os.toString("UTF-8");
-		return xml;
-	}
-
-	private CMDComponentSpec getUncachedMDComponent(String id, ComponentDao dao) {
-		String xml = dao.getContent(false, id);
-		if (xml != null) {
-			try {
-				InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
-				return getMarshaller().unmarshal(CMDComponentSpec.class, is, null);
-
-			} catch (JAXBException ex) {
-				LOG.error("Error while unmarshalling", ex);
-			} catch (UnsupportedEncodingException ex) {
-				LOG.error("Exception while reading XML from database", ex);
-			}
-		}
-		return null;
-	}
-
-	private void checkAuthorisation(BaseDescription desc, Principal principal) throws UserUnauthorizedException {
-		if (!isOwnerOfDescription(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
-			throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
-					+ "' is not the creator (nor an administrator) of the "
-					+ (desc.isProfile() ? "profile" : "component") + "(" + desc + ").");
-		}
-	}
-
-	private void checkAuthorisationComment(Comment desc, Principal principal) throws UserUnauthorizedException {
-		if (!isOwnerOfComment(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
-			throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
-					+ "' is not the creator (nor an administrator) of the " + (desc.getId()) + "(" + desc + ").");
-		}
-	}
-
-	private boolean isOwnerOfDescription(BaseDescription desc, String principalName) {
-		String owner = componentDao.getOwnerPrincipalName(getIdForDescription(desc));
-		return owner != null // If owner is null, no one can be owner
-				&& principalName.equals(owner);
-	}
-
-	private boolean isOwnerOfComment(Comment com, String principalName) {
-		RegistryUser owner = commentsDao.getOwnerOfComment(Integer.parseInt(com.getId()));
-		return owner != null // If owner is null, no one can be owner
-				&& principalName.equals(owner.getPrincipalName());
-	}
-
-	private void checkAge(BaseDescription desc, Principal principal) throws DeleteFailedException {
-		if (isPublic() && !configuration.isAdminUser(principal)) {
-			Date regDate = desc.getRegistrationDate();
-			Calendar calendar = Calendar.getInstance();
-			calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
-			if (regDate.before(calendar.getTime())) { // More then month old
-				throw new DeleteFailedException(
-						"The "
-								+ (desc.isProfile() ? "Profile" : "Component")
-								+ " is more then a month old and cannot be deleted anymore. It might have been used to create metadata, deleting it would invalidate that metadata.");
-			}
-		}
-	}
-
-	private boolean inWorkspace(String cmdId) {
-		if (isPublic()) {
-			return componentDao.isPublic(cmdId);
-		} else {
-			return componentDao.isInUserSpace(cmdId, getUserId());
-		}
-	}
-
-	@Override
-	public String getName() {
-		if (isPublic()) {
-			return ComponentRegistry.PUBLIC_NAME;
-		} else {
-			RegistryUser u = userDao.findOne(getUserId().longValue());
-			return "Registry of " + u.getName();
-		}
-	}
-
-	private boolean canCurrentUserAccessDescription(String cmdId) {
-		if (cmdId == null)
-			return false;
-		Number userId = getUserId();
-		if (userId == null)
-			return false;
-		RegistryUser user = userDao.findOne(userId.longValue());
-		if (user == null)
-			return false;
-		BaseDescription description = componentDao.getByCmdId(cmdId);
-		if (description == null)
-			return false;
-		return groupService.canUserAccessComponentEitherOnHisOwnOrThroughGroupMembership(user, description);
-	}
-
-	@Override
-	public List<ProfileDescription> getDeletedProfileDescriptions() {
-		return ComponentUtils.toProfiles(componentDao.getDeletedDescriptions(getUserId()));
-	}
-
-	@Override
-	public List<ComponentDescription> getDeletedComponentDescriptions() {
-		return ComponentUtils.toComponents(componentDao.getDeletedDescriptions(getUserId()));
-	}
-
-	@Override
-	public void deleteComment(String commentId, Principal principal) throws IOException, ComponentRegistryException,
-			UserUnauthorizedException, DeleteFailedException {
-		try {
-			Comment comment = commentsDao.findOne(Long.parseLong(commentId));
-			if (comment != null
-					// Comment must have an existing (in this registry)
-					// componentId or profileId
-					&& comment.getComponentId() != null
-					&& componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
-				checkAuthorisationComment(comment, principal);
-				commentsDao.delete(comment);
-			} else {
-				// Comment exists in DB, but component is not in this registry
-				throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
-			}
-		} catch (DataAccessException ex) {
-			throw new DeleteFailedException("Database access error while trying to delete component", ex);
-		} catch (NumberFormatException ex) {
-			throw new DeleteFailedException("Illegal comment ID, cannot parse integer", ex);
-		}
-	}
-
-	@Override
-	public CMDComponentSpecExpander getExpander() {
-		return new CMDComponentSpecExpanderDbImpl(this);
-	}
-
-	@Override
-	protected MDMarshaller getMarshaller() {
-		return marshaller;
-	}
-
-	@Override
-	public String toString() {
-		return getName();
-	}
-
-	@Override
-	public List<ComponentDescription> getComponentDescriptionsInGroup(String principalName, String groupId)
-			throws ComponentRegistryException {
-		List<String> componentIds = groupService.getComponentIdsInGroup(Long.parseLong(groupId));
-		List<ComponentDescription> components = new ArrayList<ComponentDescription>();
-		for (String id : componentIds) {
-			BaseDescription description = componentDao.getByCmdId(id);
-			components.add(ComponentUtils.toComponent(description));
-		}
-		return components;
-	}
-
-	@Override
-	public List<ProfileDescription> getProfileDescriptionsForMetadaEditor(String groupId)
-			throws ComponentRegistryException {
-		List<String> componentIds = groupService.getProfileIdsInGroup(Long.parseLong(groupId));
-		List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
-		for (String id : componentIds) {
-			ProfileDescription profile = getProfileDescription(id);
-			if (profile != null)
-				profiles.add(profile);
-		}
-		return profiles;
-	}
-
-	@Override
-	public List<ProfileDescription> getProfileDescriptionsInGroup(String groupId) throws ComponentRegistryException {
-		List<String> componentIds = groupService.getProfileIdsInGroup(Long.parseLong(groupId));
-		List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
-		for (String id : componentIds) {
-			ProfileDescription profile = getProfileDescription(id);
-			if (profile != null)
-				profiles.add(profile);
-		}
-		return profiles;
-	}
-
-	@Override
-	public List<String> getAllNonDeletedProfileIds() {
-		return componentDao.getAllNonDeletedProfileIds();
-	}
-
-	@Override
-	public List<String> getAllNonDeletedComponentIds() {
-		return componentDao.getAllNonDeletedComponentIds();
-	}
+    private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryDbImpl.class);
+    private Owner registryOwner;
+    private RegistrySpace registrySpace;
+    private Number groupId;
+    @Autowired
+    private Configuration configuration;
+    @Autowired
+    @Qualifier("componentsCache")
+    private CMDComponentSpecCache componentsCache;
+    @Autowired
+    @Qualifier("profilesCache")
+    private CMDComponentSpecCache profilesCache;
+    // DAO's
+    @Autowired
+    private ComponentDao componentDao;
+    @Autowired
+    private UserDao userDao;
+    @Autowired
+    private CommentsDao commentsDao;
+    @Autowired
+    private MDMarshaller marshaller;
+    @Autowired
+    private GroupService groupService;
+
+    
+    // 
+    /**
+     * Default constructor, to use this as a (spring) bean. The public registry
+     * by default. Use setRegistryStatus(), setRegistryOwner(), setGroupId() to make it another kind of
+     * registry.
+     *
+     * 
+     */
+    public ComponentRegistryDbImpl() throws TransformerException {
+        this.registrySpace = RegistrySpace.PUBLISHED;
+    }
+
+
+    @Override
+    public Owner getRegistryOwner() {
+        return this.registryOwner;
+    }
+    
+    @Override
+    public void setRegistryOwner(Owner registryOwner) {
+        this.registryOwner = registryOwner;
+    }
+    
+    
+    @Override
+    public RegistrySpace getRegistrySpace() {
+        return this.registrySpace;
+    }
+
+    @Override
+    public void setRegistrySpace(RegistrySpace registrySpace) {
+        this.registrySpace = registrySpace;
+    }
+
+    @Override
+    public Number getGroupId() {
+        return this.groupId;
+    }
+    
+    @Override
+    public void setGroupId(Number groupId) {
+        this.groupId = groupId;
+    }
+    
+    @Override
+    public Number getBaseDescriptionOwnerId(String cmdId){
+        BaseDescription bd = componentDao.getByCmdId(cmdId);
+        return bd.getDbUserId();
+    }
+    
+    @Override
+    public  List<Number> getItemGroups(String cmdId){
+        List<Group> groups = groupService.getGroupsTheItemIsAMemberOf(cmdId);
+        List<Number> result = new ArrayList<Number>();
+        if (groups != null) {
+            for (Group group: groups) {
+                result.add(group.getId());
+            }
+        }
+        return result;
+    }
+    
+    /**
+     * @return The user id, or null if there is no owner or it is not a user.
+     */
+    private Number getUserId() {
+        if (registryOwner instanceof OwnerUser) {
+            return registryOwner.getId();
+        } else {
+            return null;
+        }
+    }
+    
+    @Override
+    public List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException, UserUnauthorizedException {
+        try {
+            switch (registrySpace) {
+                case PRIVATE:
+                    if (registryOwner == null) {
+                        throw new ComponentRegistryException("Private workspace without owner!");
+                    }
+                    return ComponentUtils.toProfiles(componentDao.getPrivateBaseDescriptions(registryOwner.getId(), ProfileDescription.PROFILE_PREFIX));
+                case GROUP:
+                    return this.getProfileDescriptionsInGroup(groupId);
+                case PUBLISHED:
+                    return ComponentUtils.toProfiles(componentDao.getPublicBaseDescriptions(ProfileDescription.PROFILE_PREFIX));
+                default:
+                    throw new ComponentRegistryException("Unsupported status type" + registrySpace);
+            }
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
+        }
+    }
+
+    @Override
+    public Boolean isItemPublic(String id) throws ItemNotFoundException{
+        BaseDescription desc = componentDao.getByCmdId(id);
+        if (desc == null) {
+            String idS = (id == null) ? "null" : id;
+            throw new ItemNotFoundException("The component with the id " + idS+ "is not found in the database.");
+        }
+        return desc.isPublic();
+    }
+
+    @Override
+    public ProfileDescription getProfileDescriptionAccessControlled(String id) throws ItemNotFoundException, UserUnauthorizedException, ComponentRegistryException {
+        boolean hasAccess = this.canCurrentUserAccessDescription(id);
+        if (hasAccess) {
+            try {
+                return ComponentUtils.toProfile(componentDao.getByCmdId(id));
+            } catch (DataAccessException ex) {
+                throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
+            }
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
+        }
+    }
+
+    private ProfileDescription getProfileDescription(String id) throws ComponentRegistryException {
+        try {
+            return ComponentUtils.toProfile(componentDao.getByCmdId(id));
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
+        }
+
+    }
+
+    @Override
+    public List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException, UserUnauthorizedException {
+        try {
+            switch (registrySpace) {
+                case PRIVATE:
+                    if (registryOwner == null) {
+                        throw new ComponentRegistryException("Private workspace without owner!");
+                    }
+                    return ComponentUtils.toComponents(componentDao.getPrivateBaseDescriptions(registryOwner.getId(), ComponentDescription.COMPONENT_PREFIX));
+                case GROUP:
+                    return this.getComponentDescriptionsInGroup(groupId);
+                case PUBLISHED:
+                    return ComponentUtils.toComponents(componentDao.getPublicBaseDescriptions(ComponentDescription.COMPONENT_PREFIX));
+                default:
+                    throw new ComponentRegistryException("Unsupported status type" + registrySpace);
+            }
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
+        }
+    }
+
+    @Override
+    public ComponentDescription getComponentDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        boolean hasAccess = this.canCurrentUserAccessDescription(id);
+        if (hasAccess) {
+            try {
+                return ComponentUtils.toComponent(componentDao.getByCmdId(id));
+            } catch (DataAccessException ex) {
+                throw new ComponentRegistryException("Database access error while trying to get component description", ex);
+            }
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
+        }
+    }
+
+    private ComponentDescription getComponentDescription(String id) throws ComponentRegistryException {
+        try {
+            return ComponentUtils.toComponent(componentDao.getByCmdId(id));
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get component description", ex);
+        }
+
+    }
+
+    @Override
+    public List<Comment> getCommentsInProfile(String profileId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        try {
+            //Olha was here
+            //if (componentDao.isInRegistry(profileId, getUserId())) {
+            if (this.canCurrentUserAccessDescription(profileId)) {
+                final List<Comment> commentsFromProfile = commentsDao.getCommentsFromItem(profileId);
+                this.setCanDeleteInComments(commentsFromProfile);
+                return commentsFromProfile;
+            } else {
+                throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
+            }
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException(
+                    "Database access error while trying to get list of comments from profile", ex);
+        }
+    }
+
+    @Override
+    public Comment getSpecifiedCommentInProfile(String profileId, String commentId)
+            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        if (this.canCurrentUserAccessDescription(profileId)) {
+            try {
+                Comment comment = commentsDao.findOne(Long.parseLong(commentId));
+                if (comment != null && profileId.equals(comment.getComponentId())) {
+                    this.setCanDeleteInComments(Collections.singleton(comment));
+                    return comment;
+                } else {
+                    // Comment exists in DB, but profile is not in this registry
+                    throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
+                }
+            } catch (DataAccessException ex) {
+                throw new ComponentRegistryException("Database access error while trying to get comment from profile", ex);
+            }
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
+        }
+    }
+
+    @Override
+    public List<Comment> getCommentsInComponent(String componentId)
+            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        if (this.canCurrentUserAccessDescription(componentId)) {
+            try {
+                final List<Comment> commentsFromComponent = commentsDao.getCommentsFromItem(componentId);
+                this.setCanDeleteInComments(commentsFromComponent);
+                return commentsFromComponent;
+
+            } catch (DataAccessException ex) {
+                throw new ComponentRegistryException(
+                        "Database access error while trying to get list of comments from component", ex);
+            }
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
+        }
+    }
+
+    @Override
+    public Comment getSpecifiedCommentInComponent(String componentId, String commentId)
+            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        if (this.canCurrentUserAccessDescription(componentId)) {
+            try {
+                Comment comment = commentsDao.findOne(Long.parseLong(commentId));
+                if (comment != null && componentId.equals(comment.getComponentId().toString())) {
+                    this.setCanDeleteInComments(Collections.singleton(comment));
+                    return comment;
+                } else {
+                    // Comment does not exists in DB or component is not in this
+                    // registry
+                    throw new ComponentRegistryException("Comment " + commentId
+                            + " cannot be found in specified registry for specified component");
+                }
+            } catch (DataAccessException ex) {
+                throw new ComponentRegistryException("Database access error while trying to get comment from component", ex);
+            }
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
+        }
+    }
+
+    /**
+     * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all
+     * comments in the provided collection for the perspective of the specified
+     * principal. Comment owners (determined by {@link Comment#getUserId() })
+     * and admins can delete, others cannot.
+     *
+     * @param comments comments to configure
+     * @param principal user to configure for
+     * @see Comment#isCanDelete()
+     */
+    private void setCanDeleteInComments(Collection<Comment> comments) {
+        String principalName = (userDao.getPrincipalNameById(registryOwner.getId())).getPrincipalName();
+        final boolean isAdmin = configuration.isAdminUser(principalName);
+        for (Comment comment : comments) {
+            comment.setCanDelete(isAdmin || comment.getUserId() == registryOwner.getId().longValue());
+        }
+
+    }
+
+    @Override
+    public CMDComponentSpec getMDProfileAccessControled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        if (this.canCurrentUserAccessDescription(id)) {
+            return this.getMDProfile(id);
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile or the profile is not found.");
+        }
+    }
+
+    private CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException {
+        if (id.startsWith(ProfileDescription.PROFILE_PREFIX)) {
+            CMDComponentSpec result = profilesCache.get(id);
+            if (result == null && !profilesCache.containsKey(id)) {
+                result = this.getUncachedMDProfile(id);
+                profilesCache.put(id, result);
+            }
+            return result;
+        } else {
+            throw new ComponentRegistryException("the id " + id + " is not a profile id.");
+        }
+    }
+
+    public CMDComponentSpec getUncachedMDProfile(String id) throws ComponentRegistryException {
+        try {
+            return this.getUncachedMDComponent(id, componentDao);
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get profile", ex);
+        }
+    }
+
+    @Override
+    public CMDComponentSpec getMDComponentAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        if (this.canCurrentUserAccessDescription(id)) {
+            return this.getMDComponent(id);
+        } else {
+            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component or the component is not found.");
+        }
+    }
+
+    @Override
+    public CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException {
+        if (id.startsWith(ComponentDescription.COMPONENT_PREFIX)) {
+            CMDComponentSpec result = componentsCache.get(id);
+            if (result == null && !componentsCache.containsKey(id)) {
+                result = getUncachedMDComponent(id);
+                componentsCache.put(id, result);
+            }
+            return result;
+        } else {
+            throw new ComponentRegistryException("The id " + id + " is not a component id");
+        }
+    }
+
+    public CMDComponentSpec getUncachedMDComponent(String id) throws ComponentRegistryException {
+        try {
+            return this.getUncachedMDComponent(id, componentDao);
+        } catch (DataAccessException ex) {
+            throw new ComponentRegistryException("Database access error while trying to get component", ex);
+        }
+    }
+
+    @Override
+    public int register(BaseDescription description, CMDComponentSpec spec) {
+        enrichSpecHeader(spec, description);
+        try {
+            String xml = componentSpecToString(spec);
+            // Convert principal name to user record id
+            Number uid = convertUserInDescription(description);
+            componentDao.insertDescription(description, xml, description.isPublic(), uid);
+            invalidateCache(description);
+            return 0;
+        } catch (DataAccessException ex) {
+            LOG.error("Database error while registering component", ex);
+            return -1;
+        } catch (JAXBException ex) {
+            LOG.error("Error while registering component", ex);
+            return -2;
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Error while registering component", ex);
+            return -3;
+        }
+    }
+
+    @Override
+    public int registerComment(Comment comment, String principalName) throws ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
+        try {
+            if (comment.getComponentId() != null)  {
+                if (this.canCurrentUserAccessDescription(comment.getComponentId()))
+                {
+                // Convert principal name to user record id
+                Number uid = convertUserIdInComment(comment, principalName);
+                // Set date to current date
+                comment.setCommentDate(new Date());
+                comment.setUserId(uid.longValue());
+                commentsDao.saveAndFlush(comment);
+            
+            } else {
+                throw new UserUnauthorizedException("The logged-in user cannot access the component/profile with id "+comment.getComponentId());
+            }
+            } else {
+                throw new ComponentRegistryException("The component/profile id for this comment is null.");            
+            }
+            return 0;
+        } catch (DataAccessException ex) {
+            LOG.error("Database error while registering component", ex);
+            return -1;
+        }
+    }
+
+    /**
+     * Calling service sets user id to principle. Our task is to convert this to
+     * an id for later reference. If none is set and this is a user's workspace,
+     * set from that user's id.
+     *
+     * It also sets the name in the description according to the display name in
+     * the database.
+     *
+     * @param description Description containing principle name as userId
+     * @return Id (from database)
+     * @throws DataAccessException
+     */
+    private Number convertUserInDescription(BaseDescription description) throws DataAccessException {
+        Number uid = null;
+        String name = null;
+        if (description.getUserId() != null) {
+            RegistryUser user = userDao.getByPrincipalName(description.getUserId());
+            if (user != null) {
+                uid = user.getId();
+                name = user.getName();
+            }
+        } else {
+            uid = getUserId(); // this can be null as well
+        }
+        if (uid != null) {
+            description.setUserId(uid.toString());
+        }
+        if (name != null) {
+            description.setCreatorName(name);
+        }
+        return uid;
+    }
+
+    /**
+     * Calling service sets user id to principle. Our task is to convert this to
+     * an id for later reference. If none is set and this is a user's workspace,
+     * set from that user's id.
+     *
+     * @param comment Comment containing principle name as userId
+     * @return Id (from database)
+     * @throws DataAccessException
+     */
+    private Number convertUserIdInComment(Comment comment, String principalName) throws DataAccessException,
+            ComponentRegistryException {
+        if (principalName != null) {
+            RegistryUser user = userDao.getByPrincipalName(principalName);
+            if (user != null) {
+                Long id = user.getId();
+                if (id != null) {
+                    // Set user id in comment for convenience of calling method
+                    comment.setUserId(id);
+                    // Set name to user's preferred display name
+                    comment.setUserName(user.getName());
+                    return id;
+                } else {
+                    throw new ComponentRegistryException("Cannot find user with principal name: " + principalName);
+                }
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public int update(BaseDescription description, CMDComponentSpec spec, boolean forceUpdate) throws UserUnauthorizedException, ItemNotFoundException {
+        try {
+            this.checkAuthorisation(description);
+            this.checkAge(description);
+            // For public components, check if used in other components or
+            // profiles (unless forced)
+            if (!forceUpdate && description.isPublic() && !description.isProfile()) {
+                this.checkStillUsed(description.getId());
+            }
+            componentDao.updateDescription(getIdForDescription(description), description, componentSpecToString(spec));
+            invalidateCache(description);
+            return 0;
+        } catch (JAXBException ex) {
+            LOG.error("Error while updating component", ex);
+            return -1;
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Error while updating component", ex);
+            return -1;
+        } catch (IllegalArgumentException ex) {
+            LOG.error("Error while updating component", ex);
+            return -1;
+        } catch (DeleteFailedException e) {
+            LOG.error("Error while updating component", e);
+            return -1;
+        } catch (ComponentRegistryException e) {
+            LOG.error("Error while updating component", e);
+            return -1;
+        }
+    }
+
+    @Override
+    public int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal) throws UserUnauthorizedException, ItemNotFoundException {
+        int result = 0;
+        this.checkAuthorisation(desc);
+        if (desc.isPublic()) { // if already in published
+            // todo
+            desc.setHref(ComponentUtils.createPublicHref(desc.getHref()));
+            Number id = getIdForDescription(desc);
+            try {
+                // Update description & content
+                componentDao.updateDescription(id, desc, componentSpecToString(spec));
+                // Set to public
+                componentDao.setPublished(id, true);
+            } catch (DataAccessException ex) {
+                LOG.error("Database error while updating component", ex);
+                return -1;
+            } catch (JAXBException ex) {
+                LOG.error("Error while updating component", ex);
+                return -2;
+            } catch (UnsupportedEncodingException ex) {
+                LOG.error("Error while updating component", ex);
+                return -3;
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException {
+        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
+        writeXml(expandedSpec, output);
+    }
+
+    @Override
+    public void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException {
+        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
+        writeXsd(expandedSpec, outputStream);
+    }
+
+    @Override
+    public void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException {
+        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
+        writeXml(expandedSpec, output);
+    }
+
+    @Override
+    public void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException {
+        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
+        writeXsd(expandedSpec, outputStream);
+    }
+
+    @Override
+    public void deleteMDProfile(String profileId) throws UserUnauthorizedException,
+            DeleteFailedException, ComponentRegistryException, ItemNotFoundException {
+        ProfileDescription desc = getProfileDescriptionAccessControlled(profileId);
+        if (desc != null) {
+            try {
+                this.checkAuthorisation(desc);
+                this.checkAge(desc);
+                componentDao.setDeleted(desc, true);
+                invalidateCache(desc);
+            } catch (DataAccessException ex) {
+                throw new DeleteFailedException("Database access error while trying to delete profile", ex);
+            }
+        }
+    }
+
+    @Override
+    public void deleteMDComponent(String componentId, boolean forceDelete)
+            throws UserUnauthorizedException, DeleteFailedException, ComponentRegistryException, ItemNotFoundException {
+        BaseDescription desc = componentDao.getByCmdId(componentId);
+        if (desc != null) {
+            try {
+                this.checkAuthorisation(desc);
+                this.checkAge(desc);
+
+                if (!forceDelete) {
+                    checkStillUsed(componentId);
+                }
+                componentDao.setDeleted(desc, true);
+                invalidateCache(desc);
+            } catch (DataAccessException ex) {
+                throw new DeleteFailedException("Database access error while trying to delete component", ex);
+            }
+        }
+    }
+
+    
+
+    private void invalidateCache(BaseDescription description) {
+        if (description.isProfile()) {
+            profilesCache.remove(description.getId());
+        } else {
+            componentsCache.remove(description.getId());
+        }
+    }
+
+    /**
+     * Looks up description on basis of CMD Id. This will also check if such a
+     * record even exists.
+     *
+     * @param description Description to look up
+     * @return Database id for description
+     * @throws IllegalArgumentException If description with non-existing id is
+     * passed
+     */
+    private Number getIdForDescription(BaseDescription description) throws IllegalArgumentException {
+        Number dbId = null;
+        try {
+            dbId = componentDao.getDbId(description.getId());
+        } catch (DataAccessException ex) {
+            LOG.error("Error getting dbId for component with id " + description.getId(), ex);
+        }
+        if (dbId == null) {
+            throw new IllegalArgumentException("Could not get database Id for description");
+        } else {
+            return dbId;
+        }
+    }
+
+    private String componentSpecToString(CMDComponentSpec spec) throws UnsupportedEncodingException, JAXBException {
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        getMarshaller().marshal(spec, os);
+        String xml = os.toString("UTF-8");
+        return xml;
+    }
+
+    private CMDComponentSpec getUncachedMDComponent(String id, ComponentDao dao) {
+        String xml = dao.getContent(false, id);
+        if (xml != null) {
+            try {
+                InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
+                CMDComponentSpec result = getMarshaller().unmarshal(CMDComponentSpec.class, is, null);
+                try {
+                    is.close();
+                    return result;
+                } catch (IOException ex) {
+                    LOG.error("Cannot close the stream", ex);
+                    return result;
+                }
+
+            } catch (JAXBException ex) {
+                LOG.error("Error while unmarshalling", ex);
+            } catch (UnsupportedEncodingException ex) {
+                LOG.error("Exception while reading XML from database", ex);
+            }
+        }
+        return null;
+    }
+
+    private void checkAuthorisation(BaseDescription desc) throws UserUnauthorizedException, ItemNotFoundException {
+        if (!this.canCurrentUserAccessDescription(desc.getId())) {            
+            String principalName = (registryOwner != null) ? userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName() : "null";
+            throw new UserUnauthorizedException("Unauthorized operation user '" + principalName
+                    + "' is not the creator (nor a member of the group, nor an administrator) of the "
+                    + (desc.isProfile() ? "profile" : "component") + "(" + desc + ").");
+        }
+    }
+
+    private void checkAuthorisationComment(Comment desc) throws UserUnauthorizedException {
+        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
+        if (!(this.isOwnerOfComment(desc, principalName) || configuration.isAdminUser(principalName))) {
+            throw new UserUnauthorizedException("Unauthorized operation user '" + principalName
+                    + "' is not the creator (nor a member of the group, nor an administrator) of the " + (desc.getId()) + "(" + desc + ").");
+        }
+    }
+
+//    private boolean isOwnerOfDescription(BaseDescription desc, String principalName) {
+//        String owner = componentDao.getOwnerPrincipalName(getIdForDescription(desc));
+//        return owner != null // If owner is null, no one can be owner
+//                && principalName.equals(owner);
+//    }
+    private boolean isOwnerOfComment(Comment com, String principalName) {
+        long id = Long.parseLong(com.getId());
+        RegistryUser owner = commentsDao.getOwnerOfComment(id);
+        return owner != null // If owner is null, no one can be owner
+                && principalName.equals(owner.getPrincipalName());
+    }
+
+    private void checkAge(BaseDescription desc) throws DeleteFailedException {
+        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
+        if (desc.isPublic() && !configuration.isAdminUser(principalName)) {
+            Date regDate = desc.getRegistrationDate();
+            Calendar calendar = Calendar.getInstance();
+            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
+            if (regDate.before(calendar.getTime())) { // More then month old
+                throw new DeleteFailedException(
+                        "The "
+                        + (desc.isProfile() ? "Profile" : "Component")
+                        + " is more then a month old and cannot be deleted anymore. It might have been used to create metadata, deleting it would invalidate that metadata.");
+            }
+        }
+    }
+
+    @Override
+    public String getName() {
+        if (this.getRegistrySpace() != null) {
+            if (this.getRegistrySpace().equals(RegistrySpace.PUBLISHED)) {
+                return ComponentRegistry.PUBLIC_NAME;
+            } else {
+                if (this.getRegistrySpace().equals(RegistrySpace.GROUP)) {
+                    if (groupId != null) {
+                        return "Registry of group" + groupId.toString();
+                    } else {
+                        return "Error: Registry of group null.";
+                    }
+                }
+            }
+        };
+        RegistryUser u = userDao.findOne(getUserId().longValue());
+        return "Registry of " + u.getName();
+    }
+
+    private boolean canCurrentUserAccessDescription(String cmdId) throws ItemNotFoundException{
+        if (cmdId == null) {
+            throw new ItemNotFoundException("Item with the null cmdIdentifier.");
+        }
+        
+        BaseDescription description = componentDao.getByCmdId(cmdId);
+        if (description == null) {
+            throw new ItemNotFoundException("Item with the id "+cmdId+" is not found.");
+        }
+        
+       
+        Number userId = getUserId();
+        if (userId == null) {
+            return false;
+        }
+        RegistryUser user = userDao.findOne(userId.longValue());
+        if (user == null) {
+            return false;
+        }
+       
+
+        if (configuration.isAdminUser(user.getPrincipalName())) {
+            return true;
+        }
+
+        return groupService.canUserAccessComponentEitherOnHisOwnOrThroughGroupMembership(user, description);
+    }
+
+    @Override
+    public List<ProfileDescription> getDeletedProfileDescriptions() throws ComponentRegistryException {
+        return ComponentUtils.toProfiles(componentDao.getDeletedDescriptions(getUserId()));
+    }
+
+    @Override
+    public List<ComponentDescription> getDeletedComponentDescriptions() throws ComponentRegistryException {
+        return ComponentUtils.toComponents(componentDao.getDeletedDescriptions(getUserId()));
+    }
+
+    @Override
+    public void deleteComment(String commentId) throws IOException, ComponentRegistryException, 
+            UserUnauthorizedException, DeleteFailedException, ItemNotFoundException {
+        try {
+            Comment comment = commentsDao.findOne(Long.parseLong(commentId));
+            if (comment != null
+                    // Comment must have an existing (in this registry)
+                    // componentId or profileId
+                    && comment.getComponentId() != null
+                    && this.canCurrentUserAccessDescription(comment.getComponentId())) {
+                this.checkAuthorisationComment(comment);
+                commentsDao.delete(comment);
+            } else {
+                // Comment exists in DB, but component is not in this registry
+                throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
+            }
+        } catch (DataAccessException ex) {
+            throw new DeleteFailedException("Database access error while trying to delete component", ex);
+        } catch (NumberFormatException ex) {
+            throw new DeleteFailedException("Illegal comment ID, cannot parse integer", ex);
+        }
+    }
+    
+  
+
+    @Override
+    public CMDComponentSpecExpander getExpander() {
+        return new CMDComponentSpecExpanderDbImpl(this);
+    }
+
+    @Override
+    protected MDMarshaller getMarshaller() {
+        return marshaller;
+    }
+
+    @Override
+    public String toString() {
+        return getName();
+    }
+
+    private List<ComponentDescription> getComponentDescriptionsInGroup(Number groupId)
+            throws ComponentRegistryException, UserUnauthorizedException {
+
+        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
+
+        if (!groupService.userGroupMember(principalName, groupId.toString())) {
+            throw new UserUnauthorizedException("The user \'" + principalName + "\' does not have access to components of the group " + groupId);
+        }
+
+        List<String> componentIds = componentDao.getAllItemIdsInGroup(ComponentDescription.COMPONENT_PREFIX, groupId.longValue());
+        List<ComponentDescription> components = new ArrayList<ComponentDescription>();
+        for (String id : componentIds) {
+            BaseDescription description = componentDao.getByCmdId(id);
+            components.add(ComponentUtils.toComponent(description));
+        }
+        return components;
+    }
+
+    private List<ProfileDescription> getProfileDescriptionsInGroup(Number groupId) throws ComponentRegistryException, UserUnauthorizedException {
+
+        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
+
+        if (!groupService.userGroupMember(principalName, groupId.toString())) {
+            throw new UserUnauthorizedException("The user \'" + principalName + "\' does not have access to profiles of the group " + groupId);
+        }
+
+        List<String> profileIds = componentDao.getAllItemIdsInGroup(ProfileDescription.PROFILE_PREFIX, groupId.longValue());
+        List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
+        for (String id : profileIds) {
+            BaseDescription description = componentDao.getByCmdId(id);
+            if (description != null) {
+                profiles.add(ComponentUtils.toProfile(description));
+            }
+        }
+        return profiles;
+    }
+
+    @Override
+    public List<ProfileDescription> getProfileDescriptionsForMetadaEditor(Number groupId) throws UserUnauthorizedException,
+            ComponentRegistryException {
+        return this.getProfileDescriptionsInGroup(groupId.longValue());
+    }
+
+    @Override
+    public List<String> getAllNonDeletedProfileIds() {
+        return componentDao.getAllNonDeletedProfileIds();
+    }
+
+    @Override
+    public List<String> getAllNonDeletedComponentIds() {
+        return componentDao.getAllNonDeletedComponentIds();
+    }
+
+    @Override
+    public List<ComponentDescription> getUsageInComponents(String componentId) throws ComponentRegistryException {
+        LOG.debug("Checking usage of component {} in components", componentId);
+        List<ComponentDescription> result = new ArrayList<ComponentDescription>();
+        List<String> ids = getAllNonDeletedComponentIds();
+        for (String id : ids) {
+            CMDComponentSpec spec = getMDComponent(id);
+            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
+                LOG.debug("Component {} used in component {}", componentId, spec.getHeader().getID());
+                result.add(getComponentDescription(id));
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException {
+        LOG.debug("Checking usage of component {} in profiles", componentId);
+        List<ProfileDescription> result = new ArrayList<ProfileDescription>();
+        for (String id : getAllNonDeletedProfileIds()) {
+            CMDComponentSpec profile = getMDProfile(id);
+            if (profile != null && hasComponentId(componentId, profile.getCMDComponent())) {
+                LOG.debug("Component {} used in profile {}", componentId, profile.getHeader().getID());
+                result.add(getProfileDescription(id));
+            }
+        }
+        return result;
+    }
+
+    protected static boolean findComponentId(String componentId, List<CMDComponentType> componentReferences) {
+        for (CMDComponentType cmdComponent : componentReferences) {
+            if (hasComponentId(componentId, cmdComponent)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean hasComponentId(String componentId, CMDComponentType cmdComponent) {
+        if (componentId.equals(cmdComponent.getComponentId())) {
+            return true;
+        } else if (findComponentId(componentId, cmdComponent.getCMDComponent())) {
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    protected void checkStillUsed(String componentId) throws DeleteFailedException, ComponentRegistryException {
+        for (String id : getAllNonDeletedProfileIds()) {
+            CMDComponentSpec spec = getMDProfile(id);
+            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
+                LOG.warn("Cannot delete component {}, still used in profile {} and possibly other profiles and/or components", componentId, spec.getHeader().getID());
+                // Profile match - throw
+                throw new DeleteFailedException("Component is still in use by other components or profiles. Request component usage for details.");
+            }
+        }
+
+        LOG.debug("Component {} is not used in any profiles", componentId);
+
+        for (String id : getAllNonDeletedComponentIds()) {
+            CMDComponentSpec spec = getMDComponent(id);
+            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
+                LOG.warn("Cannot delete component {}, still used in component {} and possibly other components", componentId, spec.getHeader().getID());
+                // Component match -> throw
+                throw new DeleteFailedException("Component is still in use by one or more other components. Request component usage for details.");
+            }
+        }
+    }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java	(revision 5549)
@@ -3,8 +3,8 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.Configuration;
 import clarin.cmdi.componentregistry.Owner;
 import clarin.cmdi.componentregistry.OwnerUser;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.UserCredentials;
 import clarin.cmdi.componentregistry.UserUnauthorizedException;
@@ -25,5 +25,5 @@
  * ComponentRegistryDbImpl implementation of ComponentRegistry for accessing the
  * registry
- * 
+ *
  * @author Twan Goosen <twan.goosen@mpi.nl>
  * @author George.Georgovassilis@mpi.nl
@@ -32,5 +32,5 @@
 
     private final static Logger LOG = LoggerFactory
-	    .getLogger(ComponentRegistryFactoryDbImpl.class);
+            .getLogger(ComponentRegistryFactoryDbImpl.class);
     @Autowired
     private Configuration configuration;
@@ -43,141 +43,169 @@
     @Override
     public List<ComponentRegistry> getAllUserRegistries() {
-	// TODO: this probably could use some caching
-	try {
-	    List<RegistryUser> users = userDao.getAllUsers();
-	    List<ComponentRegistry> registries = new ArrayList<ComponentRegistry>();
-	    for (RegistryUser user : users) {
-		registries.add(getNewComponentRegistryForUser(user.getId()));
-	    }
-	    return registries;
-	} catch (DataAccessException ex) {
-	    LOG.error("Could not retrieve users", ex);
-	    throw ex;
-	}
-    }
-
-    @Override
-    public ComponentRegistry getComponentRegistry(ComponentStatus status,
-	    Owner owner, UserCredentials credentials)
-	    throws UserUnauthorizedException {
-	switch (status) {
-	case PRIVATE:
-	    return getPrivateRegistry(owner, credentials);
-	case PUBLISHED:
-	    return getPublicRegistry();
-	default:
-	    // TODO: Add support for other status types
-	    throw new UnsupportedOperationException(
-		    "Unsupported component status" + status);
-	}
+        // TODO: this probably could use some caching
+        try {
+            List<RegistryUser> users = userDao.getAllUsers();
+            List<ComponentRegistry> registries = new ArrayList<ComponentRegistry>();
+            for (RegistryUser user : users) {
+                registries.add(getNewComponentRegistryForUser(user.getId()));
+            }
+            return registries;
+        } catch (DataAccessException ex) {
+            LOG.error("Could not retrieve users", ex);
+            throw ex;
+        }
+    }
+
+    @Override
+    public ComponentRegistry getComponentRegistry(RegistrySpace space,
+            Owner owner, UserCredentials credentials, Number groupId)
+            throws UserUnauthorizedException {
+
+        switch (space) {
+            case PRIVATE:
+                return this.getPrivateRegistry(owner, credentials);
+            case PUBLISHED:
+                return this.getPublicRegistry();
+            case GROUP:
+                return this.getGroupRegistry(groupId, owner, credentials);
+            default:
+                // TODO: Add support for "review" types
+                throw new UnsupportedOperationException(
+                        "Unsupported component space" + space);
+        }
+    }
+
+    private ComponentRegistry getGroupRegistry(Number groupId, Owner owner, UserCredentials credentials) {
+        if (owner == null || owner instanceof OwnerUser) {
+            RegistryUser user = this.getOrCreateUser(credentials);
+            owner = new OwnerUser(user.getId());
+        }
+        ComponentRegistryDbImpl cr = componentRegistryBeanFactory.getNewComponentRegistry();// default public registry
+        cr.setRegistrySpace(RegistrySpace.PRIVATE);
+        cr.setRegistryOwner(owner);
+        cr.setGroupId(groupId);
+        return cr;
     }
 
     private ComponentRegistry getPrivateRegistry(Owner owner,
-	    UserCredentials credentials) throws IllegalArgumentException,
-	    DataAccessException, UserUnauthorizedException {
-	if (owner == null || owner instanceof OwnerUser) {
-	    RegistryUser user = getOrCreateUser(credentials);
-	    if (user != null) {
-		if (owner != null && !user.getId().equals(owner.getId())) {
-		    throw new UserUnauthorizedException(
-			    "User cannot access other user's private registry");
-		}
-
-		try {
-		    return getNewComponentRegistryForUser(user.getId());
-		} catch (DataAccessException ex) {
-		    LOG.error("Could not retrieve or create user", ex);
-		    throw ex;
-		}
-	    } else {
-		throw new UserUnauthorizedException(
-			"No user credentials available cannot load userspace.");
-	    }
-	} else {
-	    // TODO: Support group owners
-	    throw new UnsupportedOperationException(
-		    "Group owners not supported");
-	}
+            UserCredentials credentials) throws IllegalArgumentException,
+            DataAccessException, UserUnauthorizedException {
+        if (owner == null || owner instanceof OwnerUser) {
+            RegistryUser user = getOrCreateUser(credentials);
+            if (user != null) {
+                if (owner != null && !user.getId().equals(owner.getId())) {
+                    throw new UserUnauthorizedException(
+                            "User cannot access other user's private registry");
+                }
+
+                try {
+                    return this.getNewComponentRegistryForUser(user.getId());
+                } catch (DataAccessException ex) {
+                    LOG.error("Could not retrieve or create user", ex);
+                    throw ex;
+                }
+            } else {
+                throw new UserUnauthorizedException(
+                        "No user credentials available cannot load userspace.");
+            }
+        } else {
+            // TODO: Support group owners
+            throw new UnsupportedOperationException(
+                    "Group owners not supported");
+        }
     }
 
     @Override
     public ComponentRegistry getOtherUserComponentRegistry(
-	    Principal adminPrincipal, ComponentStatus status, Owner owner) {
-	try {
-	    RegistryUser user;
-	    if (owner instanceof OwnerUser) {
-		user = userDao.findOne(owner.getId().longValue());
-	    } else {
-		// TODO: Implement for groups
-		throw new UnsupportedOperationException(
-			"Groups not implemented yet");
-	    }
-	    ComponentRegistry result = null;
-	    if (user != null) {
-		if (configuration.isAdminUser(adminPrincipal)) {
-		    result = getNewComponentRegistryForUser(user.getId());
-		} else {
-		    LOG.info("{} not found in list of {}",
-			    adminPrincipal.getName(),
-			    configuration.getAdminUsersArray().length);
-		    throw new IllegalArgumentException("User "
-			    + adminPrincipal.getName()
-			    + " is not admin user cannot load userspace.");
-		}
-	    }
-	    return result;
-	} catch (DataAccessException ex) {
-	    LOG.error("Could not retrieve user by id", ex);
-	    throw ex;
-	}
+            Principal adminPrincipal, Owner owner) {
+        try {
+            RegistryUser user;
+            if (owner instanceof OwnerUser) {
+                user = userDao.findOne(owner.getId().longValue());
+            } else {
+                // TODO: Implement for groups ??? Twan
+                throw new UnsupportedOperationException(
+                        "Groups not implemented yet");
+            }
+            ComponentRegistry result = null;
+            if (user != null) {
+                if (configuration.isAdminUser(adminPrincipal)) {
+                    result = this.getNewComponentRegistryForUser(user.getId());
+                } else {
+                    LOG.info("{} not found in list of {}",
+                            adminPrincipal.getName(),
+                            configuration.getAdminUsersArray().length);
+                    throw new IllegalArgumentException("User "
+                            + adminPrincipal.getName()
+                            + " is not admin user cannot load userspace.");
+                }
+            }
+            return result;
+        } catch (DataAccessException ex) {
+            LOG.error("Could not retrieve user by id", ex);
+            throw ex;
+        }
     }
 
     @Override
     public ComponentRegistry getPublicRegistry() {
-	if (publicComponentRegistry == null) {
-	    publicComponentRegistry = getNewComponentRegistryForUser(null);
-	}
-	return publicComponentRegistry;
+        if (publicComponentRegistry == null) {
+            publicComponentRegistry = this.getNewComponentRegistryForUser(null);
+        }
+        return publicComponentRegistry;
     }
 
     private ComponentRegistry getNewComponentRegistryForUser(Number userId) {
-	ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory
-		.getNewComponentRegistry();
-	if (userId != null) {
-	    // Null means public registry
-	    // TODO: Make this more explicit
-	    componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(
-		    userId));
-	}
-	return componentRegistry;
+        ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
+        if (userId != null) {
+            OwnerUser ou = new OwnerUser(userId);
+            componentRegistry.setRegistrySpace(RegistrySpace.PRIVATE);
+            componentRegistry.setRegistryOwner(ou);
+            componentRegistry.setGroupId(null);
+        }
+        return componentRegistry;
+    }
+
+    @Override
+    public ComponentRegistryDbImpl getBaseRegistry(UserCredentials credentials) {
+        RegistryUser user = this.getOrCreateUser(credentials);
+        ComponentRegistryDbImpl componentRegistryDbImpl = componentRegistryBeanFactory.getNewComponentRegistry();// default public registry
+        if (user != null) {
+            Number userId = user.getId();
+            Owner owner = new OwnerUser(userId);
+            componentRegistryDbImpl.setRegistrySpace(null);
+            componentRegistryDbImpl.setRegistryOwner(owner);
+            componentRegistryDbImpl.setGroupId(null);
+        }
+        return componentRegistryDbImpl;
     }
 
     @Override
     public RegistryUser getOrCreateUser(UserCredentials credentials) {
-	if (credentials != null
-		&& !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
-	    String principalName = credentials.getPrincipalName();
-	    return getOrCreateUser(principalName, credentials.getDisplayName());
-	}
-	return null;
+        if (credentials != null
+                && !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
+            String principalName = credentials.getPrincipalName();
+            return this.getOrCreateUser(principalName, credentials.getDisplayName());
+        }
+        return null;
     }
 
     private synchronized RegistryUser getOrCreateUser(String principalName,
-	    String displayName) {
-	// Try getting it from db
-	RegistryUser user = userDao.getByPrincipalName(principalName);
-	if (user == null) {
-	    LOG.info(
-		    "Request to create user with principal name {} and display name {}",
-		    new Object[] { principalName, displayName });
-	    // Create the new user
-	    user = new RegistryUser();
-	    user.setPrincipalName(principalName);
-	    user.setName(displayName);
-	    userDao.saveAndFlush(user);
-	    // Retrieve from db
-	    user = userDao.getByPrincipalName(principalName);
-	}
-	return user;
+            String displayName) {
+        // Try getting it from db
+        RegistryUser user = userDao.getByPrincipalName(principalName);
+        if (user == null) {
+            LOG.info(
+                    "Request to create user with principal name {} and display name {}",
+                    new Object[]{principalName, displayName});
+            // Create the new user
+            user = new RegistryUser();
+            user.setPrincipalName(principalName);
+            user.setName(displayName);
+            userDao.saveAndFlush(user);
+            // Retrieve from db
+            user = userDao.getByPrincipalName(principalName);
+        }
+        return user;
     }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupService.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupService.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupService.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.impl.database;
 
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import java.util.List;
 
@@ -95,5 +96,5 @@
      * @param componentId
      */
-    void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId);
+    void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId) throws UserUnauthorizedException;
 
     /**
@@ -103,5 +104,5 @@
      * @param componentId
      */
-    void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId);
+    void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException;
 
     /**
@@ -126,4 +127,6 @@
      */
     List<String> getProfileIdsInGroup(long groupId);
-
+    
+    boolean userGroupMember(String principalName, String groupId);
+   
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImpl.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImpl.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImpl.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.impl.database;
 
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -235,6 +236,7 @@
 		ownerships.addAll(ownershipDao.findOwnershipByComponentId(itemId));
 		Set<Group> groups = new HashSet<Group>();
-		for (Ownership ownership : ownerships)
+		for (Ownership ownership : ownerships) {
 			groups.add(groupDao.findOne(ownership.getGroupId()));
+                }
 		List<Group> groupList = new ArrayList<Group>(groups);
 		Collections.sort(groupList, new Comparator<Group>() {
@@ -247,4 +249,6 @@
 		return groupList;
 	}
+        
+        
 
 	@ManagedOperation(description = "Make a component owned by a group instead of a user")
@@ -254,13 +258,27 @@
 			@ManagedOperationParameter(name = "componentId", description = "Id of component") })
 	@Override
-	public void transferItemOwnershipFromUserToGroup(String principal, String groupName, String itemId) {
-
+	public void transferItemOwnershipFromUserToGroup(String principal, String groupName, String itemId) throws UserUnauthorizedException{
+                
+                           
 		BaseDescription item = null;
 		item = componentDao.getByCmdId(itemId);
-		if (item == null)
+		if (item == null) {
 			throw new ValidationException("No profile or component found with ID " + itemId);
+                }
 		Group group = groupDao.findGroupByName(groupName);
-		if (group == null)
+		if (group == null) {
 			throw new ValidationException("No group found with name " + groupName);
+                }
+                
+                if (!this.userGroupMember(principal, String.valueOf(group.getId()))) {
+                   throw new UserUnauthorizedException("User " + principal+ " is not a member of group "+groupName); 
+                }
+                
+                String creatorName = item.getCreatorName();
+                if (!creatorName.equals(principal)) {
+                   throw new UserUnauthorizedException("User " + principal+ " is not creator of the item  "+item.getName()); 
+                }
+                
+                
 		Ownership ownership = null;
 		List<Ownership> oldOwnerships = ownershipDao.findOwnershipByComponentId(itemId);
@@ -273,10 +291,17 @@
 
 	@Override
-	public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) {
+	public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException{
 		Group group = groupDao.findOne(groupId);
-		if (group == null)
+		if (group == null) {
 			throw new ValidationException("No group found with id " + groupId);
-		transferItemOwnershipFromUserToGroup(principal, group.getName(), componentId);
-	}
-
+                }
+		this.transferItemOwnershipFromUserToGroup(principal, group.getName(), componentId);
+	}
+
+        @Override
+        public boolean userGroupMember(String principalName, String groupId) {
+            RegistryUser user = userDao.getByPrincipalName(principalName);
+            GroupMembership gm = groupMembershipDao.findMembership(user.getId(), Long.parseLong(groupId));
+            return gm != null;
+        }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/ComponentDao.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/ComponentDao.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/ComponentDao.java	(revision 5549)
@@ -16,11 +16,5 @@
 public interface ComponentDao {
 
-    /**
-     * Get all public components
-     * 
-     * @return
-     */
-    List<BaseDescription> getPublicComponentDescriptions();
-
+    
     /**
      * Get all public profiles
@@ -28,5 +22,5 @@
      * @return
      */
-    List<BaseDescription> getPublicProfileDescriptions();
+    List<BaseDescription> getPublicBaseDescriptions(String prefix);
 
     /**
@@ -57,5 +51,5 @@
      *         public)
      */
-    boolean isInRegistry(String cmdId, Number userId);
+    //boolean isAccessible(String cmdId, Number userId);
 
     /**
@@ -117,6 +111,7 @@
      * @return The description, if it exists; null otherwise
      */
-    BaseDescription getByCmdId(String id, Number userId)
-	    throws DataAccessException;
+//    BaseDescription getByCmdId(String id, Number userId)
+//	    throws DataAccessException;
+ 
 
     /**
@@ -146,15 +141,7 @@
      *         not part of any group
      */
-    List<BaseDescription> getUserspaceComponents(Number userId)
+    List<BaseDescription> getPrivateBaseDescriptions(Number userId, String prefix)
 	    throws DataAccessException;
-
-    /**
-     * 
-     * @return All the user's profiles not in the public space and are also
-     *         not part of any group
-     */
-    List<BaseDescription> getUserspaceProfiles(Number userId)
-	    throws DataAccessException;
-
+  
     void setDeleted(BaseDescription desc, boolean isDeleted)
 	    throws DataAccessException;
@@ -182,4 +169,8 @@
     List<String> getAllNonDeletedComponentIds();
 
+    public List<BaseDescription> getAllNonDeletedDescriptions();
+            
+    // Olha was here
+    public List<String> getAllItemIdsInGroup(String prefix, Long groupId);
 
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java	(revision 5549)
@@ -110,6 +110,7 @@
      */
     private List<BaseDescription> augment(List<BaseDescription> baseDescription) {
-	if (baseDescription.isEmpty())
+	if (baseDescription.isEmpty()) {
 	    return baseDescription;
+        }
 	Map<String, BaseDescription> map = new HashMap<String, BaseDescription>();
 	List<String> idlist = new ArrayList<String>();
@@ -165,12 +166,12 @@
      *         public)
      */
-    @Override
-    public boolean isInRegistry(String cmdId, Number userId) {
-	if (userId == null) {
-	    return isPublic(cmdId);
-	} else {
-	    return isInUserSpace(cmdId, userId);
-	}
-    }
+//    @Override
+//    public boolean isAccessible(String cmdId, Number userId) {
+//	if (userId == null) {
+//	    return this.isPublic(cmdId);
+//	} else {
+//	    return this.isInUserSpace(cmdId, userId);
+//	}
+//    }
 
     /**
@@ -207,4 +208,5 @@
 	copy.setPublic(isPublic);
 	copy.setUserId(toString(userId));
+        copy.setCreatorName(description.getCreatorName());
 	copy = jpaComponentDao.saveAndFlush(copy);
 	jpaComponentDao.updateContent(copy.getId(), content);
@@ -278,30 +280,5 @@
     }
 
-    /**
-     * Get by ComponentId / ProfileId
-     * 
-     * @param id
-     *            Full component id
-     * @param userId
-     *            Db id of user for workspace; null for public space
-     * @return The description, if it exists; null otherwise
-     */
-    @Override
-    public BaseDescription getByCmdId(String id, Number userId) {
-	BaseDescription baseDescription = getByCmdId(id);
-	if (baseDescription != null) {
-	    augment(baseDescription);
-	    if (userId == null) {
-		if (!baseDescription.isPublic())
-		    baseDescription = null;
-	    } else {
-		if (baseDescription.isPublic()
-			|| !compare(baseDescription.getUserId(), userId))
-		    baseDescription = null;
-	    }
-	}
-	return baseDescription;
-    }
-
+  
     /**
      * 
@@ -352,16 +329,10 @@
      */
     @Override
-    public List<BaseDescription> getUserspaceComponents(Number userId) {
-	return augment(jpaComponentDao
-		.findItemsForUserThatAreNotInGroups(userId.longValue(),
-			ComponentDescription.COMPONENT_PREFIX + "%"));
-    }
-
-    @Override
-    public List<BaseDescription> getUserspaceProfiles(Number userId) {
-	return augment(jpaComponentDao.findItemsForUserThatAreNotInGroups(
-		userId.longValue(), ProfileDescription.PROFILE_PREFIX + "%"));
-    }
-
+    public List<BaseDescription> getPrivateBaseDescriptions(Number userId, String prefix) {
+        return augment(jpaComponentDao.findItemsForUserThatAreNotInGroups(userId.longValue(),prefix + "%"));
+	//return augment(jpaComponentDao.findNotPublishedUserItems(userId.longValue(),prefix + "%"));
+    }
+
+   
     @Override
     public void setDeleted(BaseDescription desc, boolean isDeleted) {
@@ -399,15 +370,9 @@
 
     @Override
-    public List<BaseDescription> getPublicComponentDescriptions() {
-	return augment(jpaComponentDao
-		.findPublicItems(ComponentDescription.COMPONENT_PREFIX + "%"));
-    }
-
-    @Override
-    public List<BaseDescription> getPublicProfileDescriptions() {
-	return augment(jpaComponentDao
-		.findPublicItems(ProfileDescription.PROFILE_PREFIX + "%"));
-    }
-
+    public List<BaseDescription> getPublicBaseDescriptions(String prefix) {
+	return augment(jpaComponentDao.findPublishedItems(prefix + "%"));
+    }
+
+   
     @Override
     public List<String> getAllNonDeletedProfileIds() {
@@ -419,4 +384,17 @@
 	return jpaComponentDao.findNonDeletedItemIds(ComponentDescription.COMPONENT_PREFIX+"%");
     }
-
+    
+    @Override
+    public List<BaseDescription> getAllNonDeletedDescriptions() {
+	return jpaComponentDao.findNonDeletedDescriptions();
+    }
+    
+    // Olha was here
+    @Override
+    public List<String> getAllItemIdsInGroup(String prefix, Long groupId) {
+        // we are ineterested only in non-published components in the group
+	return jpaComponentDao.findAllItemIdsInGroup(false, prefix + "%", groupId);
+    }
+    
+   
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/CommentsDao.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/CommentsDao.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/CommentsDao.java	(revision 5549)
@@ -35,5 +35,5 @@
 	 */
     	@Query("select c from Comment c where c.componentId = ?1 order by c.commentDate, c.id")
-	List<Comment> getCommentsFromComponent(String componentId)
+	List<Comment> getCommentsFromItem(String componentId)
 			throws DataAccessException;
 
@@ -44,5 +44,6 @@
 	 * @return Principal name of description's owner, if any. Otherwise, null.
 	 */
-    	@Query("select user from RegistryUser user, Comment comment, BaseDescription component where comment.id = ?1 and comment.componentId = component.componentId and component.dbUserId = user.id")
+    	//@Query("select user from RegistryUser user, Comment comment, BaseDescription component where comment.id = ?1 and comment.componentId = component.componentId and component.dbUserId = user.id")
+	@Query("select user from RegistryUser user, Comment comment where comment.id = ?1 and user.id=comment.userId")
 	RegistryUser getOwnerOfComment(long id);
 
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/JpaComponentDao.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/JpaComponentDao.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/JpaComponentDao.java	(revision 5549)
@@ -25,5 +25,5 @@
 
     @Query("select c from BaseDescription c where c.ispublic = true and c.deleted = false and c.componentId like ?1 order by upper(c.name) asc")
-    List<BaseDescription> findPublicItems(String idPrefix);
+    List<BaseDescription> findPublishedItems(String idPrefix);
 
     @Query("select c from BaseDescription c where c.ispublic = false and c.deleted = true and c.dbUserId = ?1 order by upper(c.name), c.id")
@@ -33,4 +33,5 @@
     List<BaseDescription> findPublicDeletedItems();
     
+    //compare @Query("select c from BaseDescription c where c.dbUserId = ?1 AND c.deleted = false AND c.ispublic = false AND c.componentId like ?2 order by upper(c.name), c.id")
     @Query("select c from BaseDescription c where c.dbUserId = ?1 AND c.deleted = false AND c.ispublic = false AND c.componentId like ?2 AND not exists (select 1 from Ownership o where o.componentId = c.componentId) order by upper(c.name), c.id")
     List<BaseDescription> findItemsForUserThatAreNotInGroups(Long userId, String idPrefix);
@@ -48,4 +49,12 @@
     @Query("select c.componentId from BaseDescription c where c.deleted = false and c.componentId like ?1 order by c.id asc")
     List<String> findNonDeletedItemIds(String componentIdPrefix);
+    
+    @Query("select c from BaseDescription c where c.deleted = false order by c.id asc")
+    List<BaseDescription> findNonDeletedDescriptions();
 
+    @Query("select c from BaseDescription c where c.dbUserId = ?1 AND c.deleted = false AND c.ispublic = false AND c.componentId like ?2 order by upper(c.name), c.id")
+    List<BaseDescription> findNotPublishedUserItems(Long userId, String idPrefix);    
+    
+    @Query("select c.componentId from BaseDescription c where c.ispublic = ?1 AND c.componentId like ?2 AND exists (select o from Ownership o where o.componentId = c.componentId AND o.groupId = ?3)")
+    List<String> findAllItemIdsInGroup(boolean isPublished, String idPrefix, long groupId);
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/UserDao.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/UserDao.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/UserDao.java	(revision 5549)
@@ -28,4 +28,7 @@
 	RegistryUser getByPrincipalName(String principalName)
 			throws DataAccessException;
+        
+        @Query("select u from RegistryUser u where u.id = ?1")
+	RegistryUser getPrincipalNameById(Number id) throws DataAccessException;
 
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentClosure.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentClosure.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentClosure.java	(revision 5549)
@@ -3,4 +3,6 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.model.ComponentDescription;
 
@@ -8,6 +10,6 @@
 
     @Override
-    public ComponentDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException {
-        return registry.getComponentDescription(id);
+    public ComponentDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        return registry.getComponentDescriptionAccessControlled(id);
     }
 
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java	(revision 5549)
@@ -2,11 +2,12 @@
 
 import clarin.cmdi.componentregistry.AllowedAttributetypesXML;
+import clarin.cmdi.componentregistry.AuthenticationFailException;
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.DeleteFailedException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
-import clarin.cmdi.componentregistry.Owner;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.UserCredentials;
 import clarin.cmdi.componentregistry.UserUnauthorizedException;
@@ -45,4 +46,5 @@
 import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
@@ -72,5 +74,7 @@
 
 /**
- * Handles CRUD operations on {@link ComponentDescription}, {@link ProfileDescription} and {@link Comment}s
+ * Handles CRUD operations on
+ * {@link ComponentDescription}, {@link ProfileDescription} and {@link Comment}s
+ *
  * @author twago@mpi.nl
  * @author olsha@mpi.nl
@@ -80,1526 +84,1685 @@
 @Path("/registry")
 @Service
-@Transactional(rollbackFor= {Exception.class, ValidationException.class})
+@Transactional(rollbackFor = {Exception.class, ValidationException.class})
 public class ComponentRegistryRestService implements
-		IComponentRegistryRestService {
-
-	private final static Logger LOG = LoggerFactory
-			.getLogger(IComponentRegistryRestService.class);
-	@Context
-	private UriInfo uriInfo;
-	@Context
-	private SecurityContext security;
-	@Context
-	private HttpServletRequest request;
-	@Context
-	private ServletContext servletContext;
-	@InjectParam(value = "componentRegistryFactory")
-	private ComponentRegistryFactory componentRegistryFactory;
-	@InjectParam(value = "mdMarshaller")
-	private MDMarshaller marshaller;
-	
-	@Autowired
-	private GroupService groupService;
-
-	/**
-	 * Converts userspace boolean to component status. Temporary solution!!!
-	 * 
-	 * TODO: Replace all calls to getRegistry that use this by calls using
-	 * ComponentStatus
-	 * 
-	 * 
-	 * 
-	 * @param userSpace
-	 * @return
-	 * @deprecated All calls should go directly to
-	 *             {@link #getRegistry(clarin.cmdi.componentregistry.ComponentStatus)}
-	 */
-	@Deprecated
-	private static ComponentStatus getStatus(boolean userSpace) {
-		if (userSpace) {
-			return ComponentStatus.PRIVATE;
-		} else {
-			return ComponentStatus.PUBLISHED;
-		}
-	}
-
-	private ComponentRegistry getRegistry(ComponentStatus status) {
-		Principal userPrincipal = security.getUserPrincipal();
-		UserCredentials userCredentials = getUserCredentials(userPrincipal);
-		return getRegistry(status, null, userCredentials);
-	}
-
-	private ComponentRegistry getRegistry(ComponentStatus status, Owner owner,
-			UserCredentials userCredentials) {
-		try {
-			return componentRegistryFactory.getComponentRegistry(status, owner,
-					userCredentials);
-		} catch (UserUnauthorizedException uuEx) {
-			LOG.warn("Unauthorized access to {} registry by user {}", status,
-					userCredentials);
-			LOG.debug("Details for unauthorized access", uuEx);
-			throw new WebApplicationException(uuEx, Status.UNAUTHORIZED);
-		}
-	}
-
-	/**
-	 * 
-	 * @return Principal of current request
-	 * @throws IllegalArgumentException
-	 *             If no user principal found
-	 */
-	private Principal checkAndGetUserPrincipal()
-			throws UserUnauthorizedException {
-		Principal principal = security.getUserPrincipal();
-		if (principal == null) {
-			throw new UserUnauthorizedException("no user principal found.");
-		}
-		return principal;
-	}
-
-	private UserCredentials getUserCredentials(Principal userPrincipal) {
-		UserCredentials userCredentials = null;
-		if (userPrincipal != null) {
-			userCredentials = new UserCredentials(userPrincipal);
-		}
-		return userCredentials;
-	}
-	
-	@Override
-	@GET
-	@Path("/components")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<ComponentDescription> getRegisteredComponents(
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(GROUPID_PARAM) String groupId)
-			throws ComponentRegistryException {
-		long start = System.currentTimeMillis();
-		
-		List<ComponentDescription> components = null;
-		ComponentRegistry cr = getRegistry(getStatus(userspace));
-		if (groupId == null||groupId.isEmpty())
-		    components = cr.getComponentDescriptions();
-		else {
-		    Principal principal = security.getUserPrincipal();
-		    UserCredentials credentials = getUserCredentials(principal);
- 		    components = cr.getComponentDescriptionsInGroup(principal.getName(), groupId);
-
-		}
-		LOG.debug(
-				"Releasing {} registered components into the world ({} millisecs)",
-				components.size(), (System.currentTimeMillis() - start));
-		return components;
-	}
-
-	@Override
-	@GET
-	@Path("/profiles")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<ProfileDescription> getRegisteredProfiles(
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor,
-			@QueryParam(GROUPID_PARAM) String groupId
-			)
-			throws ComponentRegistryException {
-		long start = System.currentTimeMillis();
-
-		List<ProfileDescription> profiles;
-		ComponentRegistry cr = getRegistry(getStatus(userspace));
-		if (metadataEditor) {
-		    if (groupId == null || groupId.isEmpty())
-			profiles = cr.getProfileDescriptionsForMetadaEditor();
-		    else
-			profiles = cr.getProfileDescriptionsForMetadaEditor(groupId);
-		} else {
-		    if (groupId == null || groupId.isEmpty())
-			profiles = cr.getProfileDescriptions();
-		    else
-			profiles = cr.getProfileDescriptionsInGroup(groupId);
-		}
-
-		LOG.debug(
-				"Releasing {} registered profiles into the world ({} millisecs)",
-				profiles.size(), (System.currentTimeMillis() - start));
-		return profiles;
-	}
-
-	@Override
-	@GET
-	@Path("/components/{componentId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Response getRegisteredComponent(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace
-			)
-			throws ComponentRegistryException {
-		LOG.debug("Component with id: {} is requested.", componentId);
-		CMDComponentSpec mdComponent = getRegistry(getStatus(userspace))
-				.getMDComponent(componentId);
-		if (mdComponent == null) {
-			return Response.status(Status.NOT_FOUND).build();
-		} else {
-			return Response.ok(mdComponent).build();
-		}
-	}
-
-	@Override
-	@GET
-	@Path("/components/{componentId}/{rawType}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
-	public Response getRegisteredComponentRawType(
-			@PathParam("componentId") final String componentId,
-			@PathParam("rawType") String rawType) {
-		LOG.debug("Component with id: {} and rawType: {} is requested.",
-				componentId, rawType);
-		StreamingOutput result = null;
-		try {
-			final ComponentRegistry registry = findRegistry(componentId,
-					new ComponentClosure());
-			if (registry == null) {
-				return Response
-						.status(Status.NOT_FOUND)
-						.entity("Id: " + componentId
-								+ " is not registered, cannot create data.")
-						.build();
-			}
-			ComponentDescription desc = registry
-					.getComponentDescription(componentId);
-			checkAndThrowDescription(desc, componentId);
-			String fileName = desc.getName() + "." + rawType;
-			if ("xml".equalsIgnoreCase(rawType)) {
-				result = new StreamingOutput() {
-					@Override
-					public void write(OutputStream output) throws IOException,
-							WebApplicationException {
-						try {
-							registry.getMDComponentAsXml(componentId, output);
-						} catch (ComponentRegistryException e) {
-							LOG.warn("Could not retrieve component {}",
-									componentId);
-							LOG.debug("Details", e);
-							throw new WebApplicationException(e, Response
-									.serverError()
-									.status(Status.INTERNAL_SERVER_ERROR)
-									.build());
-						}
-					}
-				};
-			} else if ("xsd".equalsIgnoreCase(rawType)) {
-				result = new StreamingOutput() {
-					@Override
-					public void write(OutputStream output) throws IOException,
-							WebApplicationException {
-						try {
-							registry.getMDComponentAsXsd(componentId, output);
-						} catch (ComponentRegistryException e) {
-							LOG.warn("Could not retrieve component {}",
-									componentId);
-							LOG.debug("Details", e);
-							throw new WebApplicationException(e, Response
-									.serverError()
-									.status(Status.INTERNAL_SERVER_ERROR)
-									.build());
-						}
-
-					}
-				};
-			} else {
-				throw new WebApplicationException(Response
-						.serverError()
-						.entity("unsupported rawType: " + rawType
-								+ " (only xml or xsd are supported)").build());
-			}
-			return createDownloadResponse(result, fileName);
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve component {}", componentId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		}
-	}
-
-	@Override
-	public ComponentRegistry findRegistry(String id,
-			RegistryClosure<? extends BaseDescription> clos)
-			throws ComponentRegistryException {
-		BaseDescription desc = null;
-		ComponentRegistry result = getRegistry(getStatus(false));
-		desc = clos.getDescription(result, id);
-		if (desc == null) {
-			List<ComponentRegistry> userRegs = componentRegistryFactory
-					.getAllUserRegistries();
-			for (ComponentRegistry reg : userRegs) {
-				desc = clos.getDescription(reg, id);
-				if (desc != null) {
-					result = reg;
-					break;
-				}
-			}
-		}
-		return result;
-	}
-
-	@Override
-	@GET
-	@Path("/profiles/{profileId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Response getRegisteredProfile(
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		LOG.debug("Profile with id {} is requested.", profileId);
-		CMDComponentSpec mdProfile = getRegistry(getStatus(userspace))
-				.getMDProfile(profileId);
-		if (mdProfile == null) {
-			return Response.status(Status.NOT_FOUND).build();
-		} else {
-			return Response.ok(mdProfile).build();
-		}
-	}
-
-	@Override
-	@GET
-	@Path("/components/usage/{componentId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<BaseDescription> getComponentUsage(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		try {
-			final long start = System.currentTimeMillis();
-			ComponentRegistry registry = getRegistry(getStatus(userspace));
-			List<ComponentDescription> components = registry
-					.getUsageInComponents(componentId);
-			List<ProfileDescription> profiles = registry
-					.getUsageInProfiles(componentId);
-
-			LOG.debug(
-					"Found {} components and {} profiles that use component {} ({} millisecs)",
-					components.size(), profiles.size(), componentId,
-					(System.currentTimeMillis() - start));
-
-			List<BaseDescription> usages = new ArrayList<BaseDescription>(
-					components.size() + profiles.size());
-			usages.addAll(components);
-			usages.addAll(profiles);
-
-			return usages;
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve profile usage {}", componentId);
-			LOG.debug("Details", e);
-			throw e;
-		}
-	}
-
-	@Override
-	@GET
-	@Path("/profiles/{profileId}/comments")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<Comment> getCommentsFromProfile(
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		long start = System.currentTimeMillis();
-		final Principal principal = security.getUserPrincipal();
-		List<Comment> comments = getRegistry(getStatus(userspace))
-				.getCommentsInProfile(profileId, principal);
-		LOG.debug(
-				"Releasing {} registered comments in profile into the world ({} millisecs)",
-				comments.size(), (System.currentTimeMillis() - start));
-		return comments;
-	}
-
-	@Override
-	@GET
-	@Path("/components/{componentId}/comments")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<Comment> getCommentsFromComponent(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		long start = System.currentTimeMillis();
-		final Principal principal = security.getUserPrincipal();
-		List<Comment> comments = getRegistry(getStatus(userspace))
-				.getCommentsInComponent(componentId, principal);
-		LOG.debug(
-				"Releasing {} registered comments in Component into the world ({} millisecs)",
-				comments.size(), (System.currentTimeMillis() - start));
-		return comments;
-	}
-
-	@Override
-	@GET
-	@Path("/profiles/{profileId}/comments/{commentId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Comment getSpecifiedCommentFromProfile(
-			@PathParam("profileId") String profileId,
-			@PathParam("commentId") String commentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		LOG.debug("Comments of profile with id {} are requested.", commentId);
-		final Principal principal = security.getUserPrincipal();
-		return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(
-				profileId, commentId, principal);
-	}
-
-	@Override
-	@GET
-	@Path("/components/{componentId}/comments/{commentId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Comment getSpecifiedCommentFromComponent(
-			@PathParam("componentId") String componentId,
-			@PathParam("commentId") String commentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		LOG.debug("Comments of component with id {} are requested.", commentId);
-		final Principal principal = security.getUserPrincipal();
-		return getRegistry(getStatus(userspace))
-				.getSpecifiedCommentInComponent(componentId, commentId,
-						principal);
-	}
-
-	/**
-	 * 
-	 * Purely helper method for my front-end (FLEX) which only does post/get
-	 * requests. The query param is checked and the "proper" method is called.
-	 * 
-	 * @param profileId
-	 * @param method
-	 * @return
-	 */
-	@Override
-	@POST
-	@Path("/profiles/{profileId}")
-	public Response manipulateRegisteredProfile(
-			@PathParam("profileId") String profileId,
-			@FormParam("method") String method,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		if ("delete".equalsIgnoreCase(method)) {
-			return deleteRegisteredProfile(profileId, userspace);
-		} else {
-			return Response.ok().build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/profiles/{profileId}/comments/{commentId}")
-	public Response manipulateCommentFromProfile(
-			@PathParam("profileId") String profileId,
-			@PathParam("commentId") String commentId,
-			@FormParam("method") String method,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		if ("delete".equalsIgnoreCase(method)) {
-			return deleteCommentFromProfile(profileId, commentId, userspace);
-		} else {
-			return Response.ok().build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/components/{componentId}/comments/{commentId}")
-	public Response manipulateCommentFromComponent(
-			@PathParam("componentId") String componentId,
-			@PathParam("commentId") String commentId,
-			@FormParam("method") String method,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		if ("delete".equalsIgnoreCase(method)) {
-			return deleteCommentFromComponent(componentId, commentId, userspace);
-		} else {
-			return Response.ok().build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/profiles/{profileId}/publish")
-	@Consumes("multipart/form-data")
-	public Response publishRegisteredProfile(
-			@PathParam("profileId") String profileId,
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			ProfileDescription desc = getRegistry(getStatus(true))
-					.getProfileDescription(profileId);
-			if (desc != null) {
-				updateDescription(desc, name, description, domainName, group);
-				return register(input, desc, getUserCredentials(principal),
-						true, new PublishAction(principal));
-			} else {
-				LOG.error("Update of nonexistent profile {} failed.", profileId);
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot update nonexistent profile")
-						.build();
-			}
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve profile {}", profileId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/profiles/{profileId}/update")
-	@Consumes("multipart/form-data")
-	public Response updateRegisteredProfile(
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			UserCredentials userCredentials = getUserCredentials(principal);
-			ProfileDescription desc = getRegistry(getStatus(userspace))
-					.getProfileDescription(profileId);
-			if (desc != null) {
-				updateDescription(desc, name, description, domainName, group);
-				return register(input, desc, userCredentials, userspace,
-						new UpdateAction(principal));
-			} else {
-				LOG.error("Update of nonexistent id (" + profileId
-						+ ") failed.");
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot update nonexistent profile")
-						.build();
-			}
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve profile {}", profileId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-
-	}
-
-	/**
-	 * 
-	 * Purely helper method for my front-end (FLEX) which van only do post/get
-	 * requests. The query param is checked and the "proper" method is called.
-	 * 
-	 * @param componentId
-	 * @param method
-	 * @return
-	 */
-	@Override
-	@POST
-	@Path("/components/{componentId}")
-	public Response manipulateRegisteredComponent(
-			@PathParam("componentId") String componentId,
-			@FormParam("method") String method,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		if ("delete".equalsIgnoreCase(method)) {
-			return deleteRegisteredComponent(componentId, userspace);
-		} else {
-			return Response.ok().build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/components/{componentId}/publish")
-	@Consumes("multipart/form-data")
-	public Response publishRegisteredComponent(
-			@PathParam("componentId") String componentId,
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			// TODO: Get status from parameter
-			ComponentDescription desc = getRegistry(getStatus(true))
-					.getComponentDescription(componentId);
-			if (desc != null) {
-				updateDescription(desc, name, description, domainName, group);
-				return register(input, desc, getUserCredentials(principal),
-						true, new PublishAction(principal));
-			} else {
-				LOG.error("Update of nonexistent id (" + componentId
-						+ ") failed.");
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot update nonexistent profile")
-						.build();
-			}
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve component {}", componentId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/components/{componentId}/update")
-	@Consumes("multipart/form-data")
-	public Response updateRegisteredComponent(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			ComponentDescription desc = getRegistry(getStatus(userspace))
-					.getComponentDescription(componentId);
-			if (desc != null) {
-				updateDescription(desc, name, description, domainName, group);
-				return register(input, desc, getUserCredentials(principal),
-						userspace, new UpdateAction(principal));
-			} else {
-				LOG.error("Update of nonexistent id (" + componentId
-						+ ") failed.");
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot update nonexistent component")
-						.build();
-			}
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve component {}", componentId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	private void updateDescription(BaseDescription desc, String name,
-			String description, String domainName, String group) {
-		desc.setName(name);
-		desc.setDescription(description);
-		desc.setDomainName(domainName);
-		desc.setGroupName(group);
-		desc.setRegistrationDate(new Date());
-	}
-
-	@Override
-	@DELETE
-	@Path("/components/{componentId}")
-	public Response deleteRegisteredComponent(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			ComponentRegistry registry = getRegistry(getStatus(userspace));
-			LOG.debug("Component with id {} set for deletion.", componentId);
-			registry.deleteMDComponent(componentId, principal, false);
-		} catch (DeleteFailedException e) {
-			LOG.info("Component with id {} deletion failed. Reason: {}",
-					componentId, e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.status(Status.FORBIDDEN)
-					.entity("" + e.getMessage()).build();
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Component with id " + componentId + " deletion failed.",
-					e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (IOException e) {
-			LOG.error("Component with id " + componentId + " deletion failed.",
-					e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException e) {
-			LOG.info("Component with id {} deletion failed: {}", componentId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.UNAUTHORIZED)
-					.entity("" + e.getMessage()).build();
-		}
-		LOG.info("Component with id: {} deleted.", componentId);
-		return Response.ok().build();
-	}
-
-	@Override
-	@DELETE
-	@Path("/profiles/{profileId}")
-	public Response deleteRegisteredProfile(
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			LOG.debug("Profile with id: {} set for deletion.", profileId);
-			getRegistry(getStatus(userspace)).deleteMDProfile(profileId,
-					principal);
-		} catch (DeleteFailedException e) {
-			LOG.info("Profile with id: {} deletion failed: {}", profileId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.FORBIDDEN)
-					.entity("" + e.getMessage()).build();
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve component", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (IOException e) {
-			LOG.error("Profile with id: " + profileId + " deletion failed.", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException e) {
-			LOG.info("Profile with id: {} deletion failed: {}", profileId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.UNAUTHORIZED)
-					.entity("" + e.getMessage()).build();
-		}
-		LOG.info("Profile with id: {} deleted.", profileId);
-		return Response.ok().build();
-	}
-
-	@Override
-	@DELETE
-	@Path("/profiles/{profileId}/comments/{commentId}")
-	public Response deleteCommentFromProfile(
-			@PathParam("profileId") String profileId,
-			@PathParam("commentId") String commentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			final Principal principal = checkAndGetUserPrincipal();
-			final ComponentRegistry registry = getRegistry(getStatus(userspace));
-			final Comment comment = registry.getSpecifiedCommentInProfile(
-					profileId, commentId, principal);
-			if (comment != null
-					&& profileId.equals(comment.getComponentId())) {
-				LOG.debug("Comment with id: {} set for deletion.", commentId);
-				registry.deleteComment(commentId, principal);
-			} else {
-				throw new ComponentRegistryException(
-						"Comment not found for specified profile");
-			}
-		} catch (DeleteFailedException e) {
-			LOG.info("Comment with id: {} deletion failed: {}", commentId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.FORBIDDEN)
-					.entity("" + e.getMessage()).build();
-		} catch (ComponentRegistryException e) {
-			LOG.info("Could not retrieve component", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (IOException e) {
-			LOG.error("Comment with id: " + commentId + " deletion failed.", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException e) {
-			LOG.info("Comment with id: {} deletion failed: {}", commentId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.UNAUTHORIZED)
-					.entity("" + e.getMessage()).build();
-		}
-		LOG.info("Comment with id: {} deleted.", commentId);
-		return Response.ok().build();
-	}
-
-	@Override
-	@DELETE
-	@Path("/components/{componentId}/comments/{commentId}")
-	public Response deleteCommentFromComponent(
-			@PathParam("componentId") String componentId,
-			@PathParam("commentId") String commentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			final Principal principal = checkAndGetUserPrincipal();
-			final ComponentRegistry registry = getRegistry(getStatus(userspace));
-			final Comment comment = registry.getSpecifiedCommentInComponent(
-					componentId, commentId, principal);
-			if (comment != null
-					&& componentId.equals(comment.getComponentId())) {
-				LOG.debug("Comment with id: {} set for deletion.", commentId);
-				registry.deleteComment(commentId, principal);
-			} else {
-				throw new ComponentRegistryException(
-						"Comment not found for specified component");
-			}
-		} catch (DeleteFailedException e) {
-			LOG.info("Comment with id: {} deletion failed: {}", commentId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.FORBIDDEN)
-					.entity("" + e.getMessage()).build();
-		} catch (ComponentRegistryException e) {
-			LOG.info("Could not retrieve component", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (IOException e) {
-			LOG.error("Comment with id: " + commentId + " deletion failed.", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		} catch (UserUnauthorizedException e) {
-			LOG.info("Comment with id: {} deletion failed: {}", commentId,
-					e.getMessage());
-			LOG.debug("Deletion failure details:", e);
-			return Response.serverError().status(Status.UNAUTHORIZED)
-					.entity("" + e.getMessage()).build();
-		}
-		LOG.info("Comment with id: {} deleted.", commentId);
-		return Response.ok().build();
-	}
-
-	@Override
-	@GET
-	@Path("/profiles/{profileId}/{rawType}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
-	public Response getRegisteredProfileRawType(
-			@PathParam("profileId") final String profileId,
-			@PathParam("rawType") String rawType) {
-		LOG.debug("Profile with id {} and rawType {} is requested.", profileId,
-				rawType);
-		StreamingOutput result = null;
-		try {
-			final ComponentRegistry registry = findRegistry(profileId,
-					new ProfileClosure());
-			if (registry == null) {
-				return Response
-						.status(Status.NOT_FOUND)
-						.entity("Id: " + profileId
-								+ " is not registered, cannot create data.")
-						.build();
-			}
-			ProfileDescription desc = registry.getProfileDescription(profileId);
-			checkAndThrowDescription(desc, profileId);
-			String fileName = desc.getName() + "." + rawType;
-
-			if ("xml".equalsIgnoreCase(rawType)) {
-				result = new StreamingOutput() {
-					@Override
-					public void write(OutputStream output) throws IOException,
-							WebApplicationException {
-						try {
-							registry.getMDProfileAsXml(profileId, output);
-						} catch (ComponentRegistryException e) {
-							LOG.warn("Could not retrieve component {}",
-									profileId);
-							LOG.debug("Details", e);
-							throw new WebApplicationException(e, Response
-									.serverError()
-									.status(Status.INTERNAL_SERVER_ERROR)
-									.build());
-						}
-					}
-				};
-			} else if ("xsd".equalsIgnoreCase(rawType)) {
-				result = new StreamingOutput() {
-					@Override
-					public void write(OutputStream output) throws IOException,
-							WebApplicationException {
-						try {
-							registry.getMDProfileAsXsd(profileId, output);
-						} catch (ComponentRegistryException e) {
-							LOG.warn("Could not retrieve component {}",
-									profileId);
-							LOG.debug("Details", e);
-							throw new WebApplicationException(e, Response
-									.serverError()
-									.status(Status.INTERNAL_SERVER_ERROR)
-									.build());
-						}
-					}
-				};
-			} else {
-				throw new WebApplicationException(Response
-						.serverError()
-						.entity("unsupported rawType: " + rawType
-								+ " (only xml or xsd are supported)").build());
-			}
-			return createDownloadResponse(result, fileName);
-		} catch (ComponentRegistryException e) {
-			LOG.warn("Could not retrieve component {}", profileId);
-			LOG.debug("Details", e);
-			return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
-					.build();
-		}
-	}
-
-	private void checkAndThrowDescription(BaseDescription desc, String id) {
-		if (desc == null) {
-			throw new WebApplicationException(Response.serverError()
-					.entity("Incorrect id:" + id + "cannot handle request")
-					.build());
-		}
-	}
-
-	private Response createDownloadResponse(StreamingOutput result,
-			String fileName) {
-		// Making response so it triggers browsers native save as dialog.
-		Response response = Response
-				.ok()
-				.type("application/x-download")
-				.header("Content-Disposition",
-						"attachment; filename=\"" + fileName + "\"")
-				.entity(result).build();
-		return response;
-
-	}
-
-	@Override
-	@POST
-	@Path("/profiles")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	@Consumes("multipart/form-data")
-	public Response registerProfile(
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			UserCredentials userCredentials = getUserCredentials(principal);
-			ProfileDescription desc = createNewProfileDescription();
-			desc.setCreatorName(userCredentials.getDisplayName());
-			desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
-																// be created
-																// here, now Id
-																// is
-																// constructed
-																// by impl
-			desc.setName(name);
-			desc.setDescription(description);
-			desc.setGroupName(group);
-			desc.setDomainName(domainName);
-			LOG.debug("Trying to register Profile: {}", desc);
-			return register(input, desc, userCredentials, userspace,
-					new NewAction());
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/components")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	@Consumes("multipart/form-data")
-	public Response registerComponent(
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@FormDataParam(NAME_FORM_FIELD) String name,
-			@FormDataParam(DESCRIPTION_FORM_FIELD) String description,
-			@FormDataParam(GROUP_FORM_FIELD) String group,
-			@FormDataParam(DOMAIN_FORM_FIELD) String domainName,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			UserCredentials userCredentials = getUserCredentials(principal);
-			ComponentDescription desc = createNewComponentDescription();
-			desc.setCreatorName(userCredentials.getDisplayName());
-			desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
-																// be created
-																// here, now Id
-																// is
-																// constructed
-																// by impl
-			desc.setName(name);
-			desc.setDescription(description);
-			desc.setGroupName(group);
-			desc.setDomainName(domainName);
-			LOG.debug("Trying to register Component: {}", desc);
-			return register(input, desc, userCredentials, userspace,
-					new NewAction());
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/components/{componentId}/comments")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	@Consumes("multipart/form-data")
-	public Response registerCommentInComponent(
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			UserCredentials userCredentials = getUserCredentials(principal);
-			if (null == componentRegistryFactory
-					.getOrCreateUser(userCredentials)) {
-				throw new UserUnauthorizedException(
-						"Cannot materialize authenticated user");
-			}
-			// TODO: Add user/group param
-			ComponentRegistry registry = getRegistry(getStatus(userspace),
-					null, userCredentials);
-			ComponentDescription description = registry
-					.getComponentDescription(componentId);
-			if (description != null) {
-				LOG.debug("Trying to register comment to {}", componentId);
-				return registerComment(input, registry, userspace, description,
-						principal, userCredentials);
-			} else {
-				LOG.warn(
-						"Attempt to post comment on nonexistent component id {} failed.",
-						componentId);
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot comment on nonexistent component")
-						.build();
-			}
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@POST
-	@Path("/profiles/{profileId}/comments")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	@Consumes("multipart/form-data")
-	public Response registerCommentInProfile(
-			@FormDataParam(DATA_FORM_FIELD) InputStream input,
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
-			throws ComponentRegistryException {
-		try {
-			Principal principal = checkAndGetUserPrincipal();
-			UserCredentials userCredentials = getUserCredentials(principal);
-			if (null == componentRegistryFactory
-					.getOrCreateUser(userCredentials)) {
-				throw new UserUnauthorizedException(
-						"Cannot materialize authenticated user");
-			}
-			// TODO: Add user/group param
-			ComponentRegistry registry = getRegistry(getStatus(userspace),
-					null, userCredentials);
-			ProfileDescription description = registry
-					.getProfileDescription(profileId);
-			if (description != null) {
-				LOG.debug("Trying to register comment to {}", profileId);
-				return registerComment(input, registry, userspace, description,
-						principal, userCredentials);
-			} else {
-				LOG.warn(
-						"Attempt to post comment on nonexistent profile id {} failed.",
-						profileId);
-				return Response
-						.serverError()
-						.entity("Invalid id, cannot comment on nonexistent profile")
-						.build();
-			}
-		} catch (UserUnauthorizedException ex) {
-			return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
-					.build();
-		}
-	}
-
-	@Override
-	@GET
-	@Path("/pingSession")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Response pingSession() {
-		boolean stillActive = false;
-		Principal userPrincipal = security.getUserPrincipal();
-		if (LOG.isInfoEnabled()) {
-			LOG.debug("ping by <{}>",
-					(userPrincipal == null ? "unauthorized user"
-							: userPrincipal.getName()));
-		}
-		if (request != null) {
-			if (userPrincipal != null
-					&& !ComponentRegistryFactory.ANONYMOUS_USER
-							.equals(userPrincipal.getName())) {
-				stillActive = !((HttpServletRequest) request).getSession()
-						.isNew();
-			}
-		}
-		return Response
-				.ok()
-				.entity(String.format("<session stillActive=\"%s\"/>",
-						stillActive)).build();
-	}
-
-	private Response register(InputStream input, BaseDescription desc,
-			UserCredentials userCredentials, boolean userspace,
-			RegisterAction action) {
-		try {
-			// TODO: Add user/group param
-			ComponentRegistry registry = getRegistry(getStatus(userspace),
-					null, userCredentials);
-			DescriptionValidator descriptionValidator = new DescriptionValidator(
-					desc);
-			MDValidator validator = new MDValidator(input, desc, registry,
-					getRegistry(getStatus(true)),
-					componentRegistryFactory.getPublicRegistry(), marshaller);
-			RegisterResponse response = new RegisterResponse();
-			response.setIsInUserSpace(userspace);
-			validate(response, descriptionValidator, validator);
-			if (response.getErrors().isEmpty()) {
-
-				CMDComponentSpec spec = validator.getCMDComponentSpec();
-
-				// removing filename from spec before it gets extended.
-				// recursion over all the components
-				setFileNamesFromListToNull(Collections.singletonList(spec.getCMDComponent()));
-
-				try {
-					checkForRecursion(validator, registry, desc);
-
-					// Add profile
-					int returnCode = action.execute(desc, spec, response,
-							registry);
-					if (returnCode == 0) {
-						response.setRegistered(true);
-						response.setDescription(desc);
-					} else {
-						response.setRegistered(false);
-						response.addError("Unable to register at this moment. Internal server error.");
-					}
-				} catch (ComponentRegistryException ex) {
-					// Recursion detected
-					response.setRegistered(false);
-					response.addError("Error while expanding specification. "
-							+ ex.getMessage());
-				}
-			} else {
-				LOG.warn("Registration failed with validation errors: {}",
-						Arrays.toString(response.getErrors().toArray()));
-				response.setRegistered(false);
-			}
-			LOG.info("Registered new {} {}", desc.isProfile() ? "profile"
-					: "component", desc);
-			response.setIsProfile(desc.isProfile());
-			return Response.ok(response).build();
-		} finally {
-			try {
-				input.close();// either we read the input or there was an
-								// exception, we need to close it.
-			} catch (IOException e) {
-				LOG.error("Error when closing inputstream: ", e);
-			}
-		}
-	}
-
-	/**
-	 * 
-	 * @param validator
-	 * @param registry
-	 * @param desc
-	 * @throws ComponentRegistryException
-	 *             if recursion is detected or something goes wrong while trying
-	 *             to detect recursion
-	 */
-	private void checkForRecursion(MDValidator validator,
-			ComponentRegistry registry, BaseDescription desc)
-			throws ComponentRegistryException {
-		try {
-			// Expand to check for recursion. Operate on copy so that original
-			// does not get expanded.
-			final CMDComponentSpec specCopy = validator
-					.getCopyOfCMDComponentSpec();
-			// In case of recursion, the following will throw a
-			// ComponentRegistryException
-			registry.getExpander().expandNestedComponent(
-					Lists.newArrayList(specCopy.getCMDComponent()), desc.getId());
-		} catch (JAXBException ex) {
-			throw new ComponentRegistryException(
-					"Unmarshalling failed while preparing recursion detection",
-					ex);
-		}
-	}
-
-	private Response registerComment(InputStream input,
-			ComponentRegistry registry, boolean userspace,
-			BaseDescription description, Principal principal,
-			UserCredentials userCredentials) {
-		try {
-			CommentValidator validator = new CommentValidator(input,
-					description, marshaller);
-			CommentResponse response = new CommentResponse();
-			response.setIsInUserSpace(userspace);
-			validateComment(response, validator);
-			if (response.getErrors().isEmpty()) {
-				Comment com = validator.getCommentSpec();
-				// int returnCode = action.executeComment(com, response,
-				// registry, principal.getName());
-
-				// If user name is left empty, fill it using the user's display
-				// name
-				if (null == com.getUserName() || "".equals(com.getUserName())) {
-					if (userCredentials != null) {
-						com.setUserName(userCredentials.getDisplayName());
-					} else {
-						com.setUserName(principal.getName());
-					}
-				}
-
-				int returnCode = registry.registerComment(com,
-						principal.getName());
-				if (returnCode == 0) {
-					response.setRegistered(true);
-					response.setComment(com);
-				} else {
-					response.setRegistered(false);
-					response.addError("Unable to post at this moment. Internal server error.");
-				}
-				if (com.getComponentId() != null) {
-					LOG.info("Posted new comment on component {}",
-							com.getComponentId());
-				} else {
-					LOG.info("Posted new comment on profile {}",
-							com.getComponentId());
-				}
-			} else {
-				LOG.warn(
-						"Posting of comment failed with validation errors: {}",
-						Arrays.toString(response.getErrors().toArray()));
-				response.setRegistered(false);
-			}
-			return Response.ok(response).build();
-		} catch (ComponentRegistryException ex) {
-			LOG.error("Error while inserting comment: ", ex);
-			return Response.serverError().entity(ex.getMessage()).build();
-		} finally {
-			try {
-				input.close();// either we read the input or there was an
-								// exception, we need to close it.
-			} catch (IOException e) {
-				LOG.error("Error when closing inputstream: ", e);
-				return Response.serverError().build();
-			}
-		}
-	}
-
-	private ComponentDescription createNewComponentDescription() {
-		ComponentDescription desc = ComponentDescription.createNewDescription();
-		desc.setHref(createXlink(desc.getId()));
-		return desc;
-	}
-
-	private ProfileDescription createNewProfileDescription() {
-		ProfileDescription desc = ProfileDescription.createNewDescription();
-		desc.setHref(createXlink(desc.getId()));
-		return desc;
-	}
-
-	private String createXlink(String id) {
-		URI uri = uriInfo.getRequestUriBuilder().path(id).build();
-		return uri.toString();
-	}
-
-	/**
-	 * 
-	 * @return The application's base URI as configured in the
-	 *         {@link #APPLICATION_BASE_URL_PARAM} context parameter. If
-	 *         correctly configured, it should look something like
-	 *         "http://catalog.clarin.eu/ds/ComponentRegistry".
-	 *         <em>Be aware that this
-	 * can also be null if configured incorrectly!</em>
-	 * 
-	 * @see #APPLICATION_BASE_URL_PARAM
-	 */
-	private String getApplicationBaseURI() {
-		return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
-	}
-
-	private void validate(RegisterResponse response, Validator... validators) {
-		for (Validator validator : validators) {
-			if (!validator.validate()) {
-				for (String error : validator.getErrorMessages()) {
-					response.addError(error);
-				}
-			}
-		}
-	}
-
-	private void validateComment(CommentResponse response,
-			Validator... validators) {
-		for (Validator validator : validators) {
-			if (!validator.validate()) {
-				for (String error : validator.getErrorMessages()) {
-					response.addError(error);
-				}
-			}
-		}
-	}
-
-	/**
-	 * @param componentRegistryFactory
-	 *            the componentRegistryFactory to set
-	 */
-	@Override
-	public void setComponentRegistryFactory(
-			ComponentRegistryFactory componentRegistryFactory) {
-		this.componentRegistryFactory = componentRegistryFactory;
-	}
-
-	/**
-	 * 
-	 * @param listofcomponents
-	 *            a list of components whose file-names and whose childrens'
-	 *            filenames are to be set to null
-	 */
-	@Override
-	public void setFileNamesFromListToNull(
-			List<CMDComponentType> listofcomponents) {
-
-		for (CMDComponentType currentcomponent : listofcomponents) {
-			setFileNamesToNullCurrent(currentcomponent);
-		}
-
-	}
-
-	/**
-	 * 
-	 * @param currentcomponent
-	 *            a component whose file-name and whose children filenames are
-	 *            to be set to null
-	 */
-	protected void setFileNamesToNullCurrent(CMDComponentType currentcomponent) {
-		currentcomponent.setFilename(null);
-		setFileNamesFromListToNull(currentcomponent.getCMDComponent());
-	}
-
-	/**
-	 * 
-	 * @param userspace
-	 *            if "true" then profiles and components from the user's
-	 *            workspace, otherwise -- public
-	 * @param limit
-	 *            the number of items to be displayed
-	 * @return rss for the components in the database to which we are currently
-	 *         connected
-	 * @throws ComponentRegistryException
-	 * @throws ParseException
-	 */
-	@Override
-	@GET
-	@Path("/components/rss")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Rss getRssComponent(
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
-			throws ComponentRegistryException, ParseException {
-		final List<ComponentDescription> components = getRegistry(
-				getStatus(userspace)).getComponentDescriptions();
-		final RssCreatorDescriptions instance = new RssCreatorDescriptions(
-				userspace, getApplicationBaseURI(), "components",
-				Integer.parseInt(limit), components,
-				ComponentUtils.COMPARE_ON_DATE);
-		final Rss rss = instance.getRss();
-		LOG.debug("Releasing RSS of {} most recently registered components",
-				limit);
-		return rss;
-	}
-
-	/**
-	 * 
-	 * @param userspace
-	 *            if "true" then profiles and components from the user's
-	 *            workspace, otherwise -- public
-	 * @param limit
-	 *            the number of items to be displayed
-	 * @return rss for the profiles in the database to which we are currently
-	 *         connected
-	 * @throws ComponentRegistryException
-	 * @throws ParseException
-	 */
-	@Override
-	@GET
-	@Path("/profiles/rss")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Rss getRssProfile(
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
-			throws ComponentRegistryException, ParseException {
-		final List<ProfileDescription> profiles = getRegistry(
-				getStatus(userspace)).getProfileDescriptions();
-		final RssCreatorDescriptions instance = new RssCreatorDescriptions(
-				userspace, getApplicationBaseURI(), "profiles",
-				Integer.parseInt(limit), profiles,
-				ComponentUtils.COMPARE_ON_DATE);
-		final Rss rss = instance.getRss();
-		LOG.debug("Releasing RSS of {} most recently registered profiles",
-				limit);
-		return rss;
-	}
-
-	/**
-	 * 
-	 * @param profileId
-	 *            the Id of a profile whose comments are to be rss-ed
-	 * @param userspace
-	 *            if "true" then profiles and components from the user's
-	 *            workspace, otherwise -- public
-	 * @param limit
-	 *            the number of items to be displayed
-	 * @return rss of the comments for a chosen profile
-	 * @throws ComponentRegistryException
-	 * @throws IOException
-	 * @throws JAXBException
-	 * @throws ParseException
-	 */
-	@Override
-	@GET
-	@Path("/profiles/{profileId}/comments/rss")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Rss getRssOfCommentsFromProfile(
-			@PathParam("profileId") String profileId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
-			throws ComponentRegistryException, IOException, JAXBException,
-			ParseException {
-		final Principal principal = security.getUserPrincipal();
-		final List<Comment> comments = getRegistry(getStatus(userspace))
-				.getCommentsInProfile(profileId, principal);
-		final String profileName = getRegistry(getStatus(userspace))
-				.getProfileDescription(profileId).getName();
-		final RssCreatorComments instance = new RssCreatorComments(userspace,
-				getApplicationBaseURI(), Integer.parseInt(limit), profileId,
-				profileName, "profile", comments, Comment.COMPARE_ON_DATE);
-		final Rss rss = instance.getRss();
-		LOG.debug("Releasing RSS of {} most recent post on profile {}", limit,
-				profileId);
-		return rss;
-	}
-
-	/**
-	 * 
-	 * @param componentId
-	 *            the Id of a component whose comments are to be rss-ed
-	 * @param userspace
-	 *            if "true" then profiles and components from the user's
-	 *            workspace, otherwise -- public
-	 * @param limit
-	 *            the number of items to be displayed
-	 * @return rss of the comments for a chosen component
-	 * @throws ComponentRegistryException
-	 * @throws IOException
-	 * @throws JAXBException
-	 * @throws ParseException
-	 */
-	@Override
-	@GET
-	@Path("/components/{componentId}/comments/rss")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public Rss getRssOfCommentsFromComponent(
-			@PathParam("componentId") String componentId,
-			@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
-			@QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
-			throws ComponentRegistryException, IOException, JAXBException,
-			ParseException {
-		final Principal principal = security.getUserPrincipal();
-		final List<Comment> comments = getRegistry(getStatus(userspace))
-				.getCommentsInComponent(componentId, principal);
-		final String componentName = getRegistry(getStatus(userspace))
-				.getComponentDescription(componentId).getName();
-		final RssCreatorComments instance = new RssCreatorComments(userspace,
-				getApplicationBaseURI(), Integer.parseInt(limit), componentId,
-				componentName, "component", comments, Comment.COMPARE_ON_DATE);
-		final Rss rss = instance.getRss();
-		LOG.debug("Releasing RSS of {} most recent post on component {}",
-				limit, componentId);
-		return rss;
-	}
-
-	@Override
-	@GET
-	@Path("/AllowedTypes")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public AllowedAttributetypesXML getAllowedAttributeTypes()
-			throws ComponentRegistryException, IOException, JAXBException,
-			ParseException {
-		return (new AllowedAttributetypesXML());
-	}
-
-	@Override
-	@GET
-	@Path("/groups/usermembership")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<Group> getGroupsTheCurrentUserIsAMemberOf() {
-	    Principal principal = security.getUserPrincipal();
-	    if (principal == null)
-		return new ArrayList<Group>();
-	    List<Group> groups = groupService.getGroupsOfWhichUserIsAMember(principal.getName());
-	    return groups;
-	}
-
-	@Override
-	@GET
-	@Path("/items/{itemId}/groups")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public List<Group> getGroupsTheItemIsAMemberOf(@PathParam("itemId") String itemId) {
-	    return groupService.getGroupsTheItemIsAMemberOf(itemId);
-	}
-	
-	@Override
-	@POST
-	@Path("/items/{itemId}/transferownership")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public void transferItemOwnershipToGroup(@PathParam("itemId") String itemId, @QueryParam("groupId") long groupId) {
-	    Principal principal = security.getUserPrincipal();
-	    groupService.transferItemOwnershipFromUserToGroupId(principal.getName(), groupId, itemId);
-	}
-
-	@Override
-	@GET
-	@Path("/items/{itemId}")
-	@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
-			MediaType.APPLICATION_JSON })
-	public BaseDescription getComponentDescription(@PathParam("itemId") String itemId) throws ComponentRegistryException{
-			LOG.debug("Item with id: {} is requested.", itemId);
-			BaseDescription description = getRegistry(getStatus(false)).getComponentDescription(itemId);
-			if (description == null)
-				description = getRegistry(getStatus(true)).getComponentDescription(itemId);
-			if (description == null)
-				description = getRegistry(getStatus(false)).getProfileDescription(itemId);
-			if (description == null)
-				description = getRegistry(getStatus(true)).getProfileDescription(itemId);
-			return description;
-	}
-
+        IComponentRegistryRestService {
+
+    private final static Logger LOG = LoggerFactory
+            .getLogger(IComponentRegistryRestService.class);
+    @Context
+    private UriInfo uriInfo;
+    @Context
+    private SecurityContext security;
+    @Context
+    private HttpServletRequest request;
+    @Context
+    private HttpServletResponse response;
+    @Context
+    private ServletContext servletContext;
+    @InjectParam(value = "componentRegistryFactory")
+    private ComponentRegistryFactory componentRegistryFactory;
+    @InjectParam(value = "mdMarshaller")
+    private MDMarshaller marshaller;
+    @Autowired
+    private GroupService groupService;
+
+    private ComponentRegistry getBaseRegistry() throws AuthenticationFailException {
+        Principal userPrincipal = this.checkAndGetUserPrincipal();
+        UserCredentials userCredentials = this.getUserCredentials(userPrincipal);
+        return componentRegistryFactory.getBaseRegistry(userCredentials);
+    }
+
+    private ComponentRegistry getRegistry(RegistrySpace space, Number groupId) {
+        Principal userPrincipal = security.getUserPrincipal();
+        UserCredentials userCredentials = this.getUserCredentials(userPrincipal);
+        try {
+            return componentRegistryFactory.getComponentRegistry(space, null, userCredentials, groupId);
+        } catch (UserUnauthorizedException uuEx) {
+            LOG.warn("Unauthorized access to {} registry by user {}", space,
+                    userCredentials);
+            LOG.debug("Details for unauthorized access", uuEx);
+            throw new WebApplicationException(uuEx, Status.FORBIDDEN);
+        }
+    }
+
+    /**
+     *
+     * @return Principal of current request
+     * @throws IllegalArgumentException If no user principal found
+     */
+    private Principal checkAndGetUserPrincipal()
+            throws AuthenticationFailException {
+        Principal principal = security.getUserPrincipal();
+        if (principal == null) {
+            throw new AuthenticationFailException("No user principal found.");
+        }
+        return principal;
+    }
+
+    private UserCredentials getUserCredentials(Principal userPrincipal) {
+        UserCredentials userCredentials = null;
+        if (userPrincipal != null) {
+            userCredentials = new UserCredentials(userPrincipal);
+        }
+        return userCredentials;
+    }
+
+    private ComponentRegistry initialiseRegistry(String space, String groupId) throws AuthenticationFailException {
+        //checking credentials 
+        RegistrySpace regSpace = RegistrySpace.valueOf(space.toUpperCase());
+        UserCredentials user = this.getUserCredentials(this.checkAndGetUserPrincipal());
+        // initializing the registry
+        Number groupIdNumber = null;
+        if (groupId != null && !groupId.isEmpty()) {
+            groupIdNumber = Integer.parseInt(groupId);
+        }
+
+        return this.getRegistry(regSpace, groupIdNumber);
+    }
+
+    @Override
+    @GET
+    @Path("/components")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<ComponentDescription> getRegisteredComponents(
+            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
+            @QueryParam(GROUPID_PARAM) String groupId)
+            throws ComponentRegistryException, IOException {
+        long start = System.currentTimeMillis();
+
+        try {
+            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
+            List<ComponentDescription> result = cr.getComponentDescriptions();
+            LOG.debug(
+                    "Releasing {} registered components into the world ({} millisecs)",
+                    result.size(), (System.currentTimeMillis() - start));
+            return result;
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new ArrayList<ComponentDescription>();
+
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
+            return new ArrayList<ComponentDescription>();
+
+        }
+
+    }
+
+    @Override
+    @GET
+    @Path("/profiles")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<ProfileDescription> getRegisteredProfiles(
+            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
+            @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor,
+            @QueryParam(GROUPID_PARAM) String groupId)
+            throws ComponentRegistryException, IOException {
+
+        long start = System.currentTimeMillis();
+        try {
+            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
+            List<ProfileDescription> result = (metadataEditor) ? cr.getProfileDescriptionsForMetadaEditor() : cr.getProfileDescriptions();
+            LOG.debug(
+                    "Releasing {} registered components into the world ({} millisecs)",
+                    result.size(), (System.currentTimeMillis() - start));
+            return result;
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new ArrayList<ProfileDescription>();
+
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
+            return new ArrayList<ProfileDescription>();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/components/{componentId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Response getRegisteredComponent(
+            @PathParam("componentId") String componentId) throws IOException {
+        LOG.debug("Component with id: {} is requested.", componentId);
+        try {
+            CMDComponentSpec mdComponent = this.getBaseRegistry().getMDComponentAccessControlled(componentId);
+            return Response.ok(mdComponent).build();
+        } catch (ItemNotFoundException e) {
+            return Response.status(Status.NOT_FOUND).build();
+        } catch (ComponentRegistryException e1) {
+            return Response.serverError().status(Status.CONFLICT).build();
+        } catch (AuthenticationFailException e) {
+            return Response.serverError().status(Status.UNAUTHORIZED).build();
+        } catch (UserUnauthorizedException e) {
+            return Response.serverError().status(Status.FORBIDDEN).build();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/profiles/{profileId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Response getRegisteredProfile(
+            @PathParam("profileId") String profileId) throws IOException {
+        LOG.debug("Profile with id {} is requested.", profileId);
+        try {
+            CMDComponentSpec mdProfile = this.getBaseRegistry().getMDProfileAccessControled(profileId);
+            return Response.ok(mdProfile).build();
+        } catch (ItemNotFoundException e) {
+            return Response.status(Status.NOT_FOUND).build();
+        } catch (ComponentRegistryException e1) {
+            return Response.serverError().status(Status.CONFLICT).build();
+        } catch (UserUnauthorizedException e) {
+            return Response.serverError().status(Status.FORBIDDEN).build();
+        } catch (AuthenticationFailException e) {
+            return Response.serverError().status(Status.UNAUTHORIZED).build();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/components/{componentId}/{rawType}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
+    public Response getRegisteredComponentRawType(
+            @PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) throws ComponentRegistryException {
+
+        LOG.debug("Component with id: {} and rawType: {} is requested.", componentId, rawType);
+        try {
+            final ComponentRegistry registry = this.getBaseRegistry();
+            try {
+                ComponentDescription desc = registry.getComponentDescriptionAccessControlled(componentId);
+                StreamingOutput result = null;
+                String fileName = desc.getName() + "." + rawType;
+                if ("xml".equalsIgnoreCase(rawType)) {
+                    result = new StreamingOutput() {
+                        @Override
+                        public void write(OutputStream output) throws IOException,
+                                WebApplicationException {
+                            try {
+                                try {
+                                    try {
+                                        registry.getMDComponentAsXml(componentId, output);
+                                    } catch (ItemNotFoundException e1) {
+                                        LOG.warn("Could not retrieve component {}",
+                                                componentId);
+                                        LOG.debug("Details", e1);
+                                        throw new WebApplicationException(e1, Response
+                                                .serverError()
+                                                .status(Status.INTERNAL_SERVER_ERROR)
+                                                .build());
+                                    }
+                                } catch (ComponentRegistryException e) {
+                                    LOG.warn("Could not retrieve component {}",
+                                            componentId);
+                                    LOG.debug("Details", e);
+                                    throw new WebApplicationException(e, Response
+                                            .serverError()
+                                            .status(Status.INTERNAL_SERVER_ERROR)
+                                            .build());
+                                }
+
+                            } catch (UserUnauthorizedException e2) {
+                                LOG.error(e2.toString());
+                            }
+                        }
+                    };
+                } else if ("xsd".equalsIgnoreCase(rawType)) {
+                    result = new StreamingOutput() {
+                        @Override
+                        public void write(OutputStream output) throws IOException,
+                                WebApplicationException {
+                            try {
+                                try {
+                                    try {
+                                        registry.getMDComponentAsXsd(componentId, output);
+                                    } catch (ItemNotFoundException e1) {
+                                        LOG.warn("Could not retrieve component {}",
+                                                componentId);
+                                        LOG.debug("Details", e1);
+                                        throw new WebApplicationException(e1, Response
+                                                .serverError()
+                                                .status(Status.INTERNAL_SERVER_ERROR)
+                                                .build());
+                                    }
+                                } catch (ComponentRegistryException e) {
+                                    LOG.warn("Could not retrieve component {}",
+                                            componentId);
+                                    LOG.debug("Details", e);
+                                    throw new WebApplicationException(e, Response
+                                            .serverError()
+                                            .status(Status.INTERNAL_SERVER_ERROR)
+                                            .build());
+                                }
+                            } catch (UserUnauthorizedException e2) {
+                                LOG.error(e2.toString());
+                            }
+
+                        }
+                    };
+                } else {
+                    throw new WebApplicationException(Response
+                            .serverError()
+                            .entity("unsupported rawType: " + rawType
+                            + " (only xml or xsd are supported)").build());
+                }
+                return createDownloadResponse(result, fileName);
+
+            } catch (UserUnauthorizedException e2) {
+                return Response.status(Status.FORBIDDEN).build();
+            }
+        } catch (ItemNotFoundException e3) {
+            return Response.status(Status.NOT_FOUND).build();
+        } catch (AuthenticationFailException e) {
+            return Response.serverError().status(Status.UNAUTHORIZED).build();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/components/usage/{componentId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<BaseDescription> getComponentUsage(
+            @PathParam("componentId") String componentId) throws ComponentRegistryException, IOException {
+
+        final long start = System.currentTimeMillis();
+        try {
+            ComponentRegistry registry = this.getBaseRegistry();
+            List<ComponentDescription> components = registry.getUsageInComponents(componentId);
+            List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
+
+            LOG.debug(
+                    "Found {} components and {} profiles that use component {} ({} millisecs)",
+                    components.size(), profiles.size(), componentId,
+                    (System.currentTimeMillis() - start));
+
+            List<BaseDescription> usages = new ArrayList<BaseDescription>(components.size() + profiles.size());
+            usages.addAll(components);
+            usages.addAll(profiles);
+
+            return usages;
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve profile usage {}", componentId);
+            LOG.debug("Details", e);
+            return new ArrayList<BaseDescription>();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new ArrayList<BaseDescription>();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/profiles/{profileId}/comments")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<Comment> getCommentsFromProfile(
+            @PathParam("profileId") String profileId)
+            throws ComponentRegistryException, IOException {
+        long start = System.currentTimeMillis();
+        try {
+            List<Comment> comments = this.getBaseRegistry().getCommentsInProfile(profileId);
+            LOG.debug(
+                    "Releasing {} registered comments in profile into the world ({} millisecs)",
+                    comments.size(), (System.currentTimeMillis() - start));
+            return comments;
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new ArrayList<Comment>();
+
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new ArrayList<Comment>();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new ArrayList<Comment>();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/components/{componentId}/comments")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<Comment> getCommentsFromComponent(
+            @PathParam("componentId") String componentId)
+            throws ComponentRegistryException, IOException {
+        long start = System.currentTimeMillis();
+        try {
+            List<Comment> comments = this.getBaseRegistry().getCommentsInComponent(componentId);
+            LOG.debug(
+                    "Releasing {} registered comments in Component into the world ({} millisecs)",
+                    comments.size(), (System.currentTimeMillis() - start));
+            return comments;
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new ArrayList<Comment>();
+        } catch (UserUnauthorizedException e1) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new ArrayList<Comment>();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new ArrayList<Comment>();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/profiles/{profileId}/comments/{commentId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Comment getSpecifiedCommentFromProfile(
+            @PathParam("profileId") String profileId,
+            @PathParam("commentId") String commentId)
+            throws ComponentRegistryException, IOException {
+
+        LOG.debug("Comments of profile with id {} are requested.", commentId);
+        try {
+
+            return this.getBaseRegistry().getSpecifiedCommentInProfile(profileId, commentId);
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new Comment();
+        } catch (UserUnauthorizedException e1) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new Comment();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new Comment();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/components/{componentId}/comments/{commentId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Comment getSpecifiedCommentFromComponent(
+            @PathParam("componentId") String componentId,
+            @PathParam("commentId") String commentId)
+            throws ComponentRegistryException, IOException {
+        LOG.debug("Comments of component with id {} are requested.", commentId);
+        try {
+
+            return this.getBaseRegistry().getSpecifiedCommentInComponent(componentId, commentId);
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new Comment();
+        } catch (UserUnauthorizedException e1) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new Comment();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new Comment();
+        }
+    }
+
+    /**
+     *
+     * Purely helper method for my front-end (FLEX) which only does post/get
+     * requests. The query param is checked and the "proper" method is called.
+     *
+     * @param profileId
+     * @param method
+     * @return
+     */
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/profiles/{profileId}")
+    public Response manipulateRegisteredProfile(
+            @PathParam("profileId") String profileId,
+            @FormParam("method") String method) {
+        if ("delete".equalsIgnoreCase(method)) {
+            return this.deleteRegisteredProfile(profileId);
+        } else {
+            return Response.ok().build();
+        }
+    }
+
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/profiles/{profileId}/comments/{commentId}")
+    public Response manipulateCommentFromProfile(
+            @PathParam("profileId") String profileId,
+            @PathParam("commentId") String commentId,
+            @FormParam("method") String method) {
+        if ("delete".equalsIgnoreCase(method)) {
+            return this.deleteCommentFromProfile(profileId, commentId);
+        } else {
+            return Response.ok().build();
+        }
+    }
+
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/components/{componentId}/comments/{commentId}")
+    public Response manipulateCommentFromComponent(
+            @PathParam("componentId") String componentId,
+            @PathParam("commentId") String commentId,
+            @FormParam("method") String method) {
+        if ("delete".equalsIgnoreCase(method)) {
+            return this.deleteCommentFromComponent(componentId, commentId);
+        } else {
+            return Response.ok().build();
+        }
+    }
+
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/profiles/{profileId}/publish")
+    @Consumes("multipart/form-data")
+    public Response publishRegisteredProfile(
+            @PathParam("profileId") String profileId,
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+
+        try {
+            Principal principal = checkAndGetUserPrincipal();
+            ComponentRegistry registry = this.getBaseRegistry();
+            ProfileDescription desc = registry.getProfileDescriptionAccessControlled(profileId);
+            if (desc != null) {
+                if (desc.isPublic()) {
+                    return Response.status(Status.CONFLICT).entity("Cannot publish already published profile.")
+                            .build();
+                }
+                desc.setPublic(true);
+                this.updateDescription(desc, name, description, domainName, group);
+                return this.register(input, desc, new PublishAction(principal), registry);
+            } else {
+                LOG.error("Update of nonexistent profile {} failed.", profileId);
+                return Response
+                        .serverError()
+                        .entity("Invalid id, cannot update nonexistent profile")
+                        .build();
+            }
+
+        } catch (AuthenticationFailException e) {
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (ItemNotFoundException e1) {
+            return Response.status(Status.NOT_FOUND).entity(e1.getMessage()).build();
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve profile {}", profileId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+        }
+    }
+
+    @Override
+    @POST
+    @Path("/profiles/{profileId}/update")
+    @Consumes("multipart/form-data")
+    public Response updateRegisteredProfile(
+            @PathParam("profileId") String profileId,
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+        try {
+            ComponentRegistry br = this.getBaseRegistry();
+            ProfileDescription desc = br.getProfileDescriptionAccessControlled(profileId);
+            if (desc != null) {
+                if (desc.isPublic()) {
+                    return Response.status(Status.CONFLICT).entity("Cannot update already published profile.")
+                            .build();
+
+                }
+                Number groupId;
+                RegistrySpace space;
+                List<Number> groupIds = br.getItemGroups(profileId);
+                if (groupIds == null || groupIds.isEmpty()) {
+                    groupId = null;
+                    space = RegistrySpace.PRIVATE;
+                } else {
+                    groupId = groupIds.get(0);
+                    space = RegistrySpace.GROUP;
+                }
+
+                updateDescription(desc, name, description, domainName, group);
+                ComponentRegistry cr = this.getRegistry(space, groupId);
+                return register(input, desc, new UpdateAction(), cr);
+            } else {
+                LOG.error("Update of nonexistent id (" + profileId
+                        + ") failed.");
+                return Response
+                        .serverError()
+                        .entity("Invalid id, cannot update nonexistent profile")
+                        .build();
+            }
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve profile {}", profileId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+
+        } catch (ItemNotFoundException ex2) {
+            return Response.status(Status.NOT_FOUND).entity(ex2.getMessage())
+                    .build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+    }
+
+    /**
+     *
+     * Purely helper method for my front-end (FLEX) which van only do post/get
+     * requests. The query param is checked and the "proper" method is called.
+     *
+     * @param componentId
+     * @param method
+     * @return
+     */
+    // twan: why do we need it?
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/components/{componentId}")
+    public Response manipulateRegisteredComponent(
+            @PathParam("componentId") String componentId,
+            @FormParam("method") String method) {
+        if ("delete".equalsIgnoreCase(method)) {
+            return this.deleteRegisteredComponent(componentId);
+        } else {
+            return Response.ok("Nothing to do, not 'delete' method").build();
+        }
+    }
+
+    // TODO: test via POSTMAN
+    @Override
+    @POST
+    @Path("/components/{componentId}/publish")
+    @Consumes("multipart/form-data")
+    public Response publishRegisteredComponent(
+            @PathParam("componentId") String componentId,
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+
+        try {
+            Principal principal = checkAndGetUserPrincipal();
+            ComponentRegistry registry = this.getBaseRegistry();
+            ComponentDescription desc = registry.getComponentDescriptionAccessControlled(componentId);
+            if (desc != null) {
+                if (desc.isPublic()) {
+                    return Response.status(Status.CONFLICT).entity("Cannot publish already published omponent.")
+                            .build();
+                }
+                desc.setPublic(true);
+                this.updateDescription(desc, name, description, domainName, group);
+                return this.register(input, desc, new PublishAction(principal), registry);
+            } else {
+                LOG.error("Update of nonexistent id (" + componentId
+                        + ") failed.");
+                return Response
+                        .serverError()
+                        .entity("Invalid id, cannot update nonexistent profile")
+                        .build();
+            }
+        } catch (AuthenticationFailException e) {
+            LOG.warn("Could not retrieve component {}", componentId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve component {}", componentId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (ItemNotFoundException e) {
+            LOG.warn("Could not retrieve component {}", componentId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+        }
+    }
+
+    @Override
+    @POST
+    @Path("/components/{componentId}/update")
+    @Consumes("multipart/form-data")
+    public Response updateRegisteredComponent(
+            @PathParam("componentId") String componentId,
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+        try {
+            ComponentRegistry br = this.getBaseRegistry();
+            ComponentDescription desc =br.getComponentDescriptionAccessControlled(componentId);
+            if (desc != null) {
+                if (desc.isPublic()) {
+                    return Response.status(Status.CONFLICT).entity("Cannot update already published component.")
+                            .build();
+                }
+                Number groupId;
+                RegistrySpace space;
+                List<Number> groupIds = br.getItemGroups(componentId);
+                if (groupIds == null || groupIds.isEmpty()) {
+                    groupId = null;
+                    space = RegistrySpace.PRIVATE;
+                } else {
+                    groupId = groupIds.get(0);
+                    space = RegistrySpace.GROUP;
+                }
+
+                this.updateDescription(desc, name, description, domainName, group);
+                ComponentRegistry cr = this.getRegistry(space, groupId);
+                return this.register(input, desc, new UpdateAction(), cr);
+            } else {
+                LOG.error("Update of nonexistent id (" + componentId
+                        + ") failed.");
+                return Response
+                        .serverError()
+                        .entity("Invalid id, cannot update nonexistent component")
+                        .build();
+            }
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve component {}", componentId);
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+        } catch (ItemNotFoundException ex2) {
+            return Response.status(Status.FORBIDDEN).entity(ex2.getMessage())
+                    .build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+    }
+
+    private void updateDescription(BaseDescription desc, String name,
+            String description, String domainName, String group) {
+        desc.setName(name);
+        desc.setDescription(description);
+        desc.setDomainName(domainName);
+        desc.setGroupName(group);
+        desc.setRegistrationDate(new Date());
+    }
+
+    @Override
+    @DELETE
+    @Path("/components/{componentId}")
+    public Response deleteRegisteredComponent(
+            @PathParam("componentId") String componentId) {
+        try {
+            ComponentRegistry registry = this.getBaseRegistry();
+            LOG.debug("Component with id {} set for deletion.", componentId);
+            registry.deleteMDComponent(componentId, false);
+        } catch (DeleteFailedException e) {
+            LOG.info("Component with id {} deletion failed. Reason: {}",
+                    componentId, e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Component with id " + componentId + " deletion failed.",
+                    e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (ItemNotFoundException e) {
+            LOG.warn("Component with id " + componentId + " is not found.",
+                    e);
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .build();
+        } catch (IOException e) {
+            LOG.error("Component with id " + componentId + " deletion failed.",
+                    e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException e) {
+            LOG.info("Component with id {} deletion failed: {}", componentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+        LOG.info("Component with id: {} deleted.", componentId);
+        return Response.ok().build();
+    }
+
+    @Override
+    @DELETE
+    @Path("/profiles/{profileId}")
+    public Response deleteRegisteredProfile(
+            @PathParam("profileId") String profileId) {
+        try {
+            LOG.debug("Profile with id: {} set for deletion.", profileId);
+            this.getBaseRegistry().deleteMDProfile(profileId);
+        } catch (DeleteFailedException e) {
+            LOG.info("Profile with id: {} deletion failed: {}", profileId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (ComponentRegistryException e) {
+            LOG.warn("Could not retrieve component", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (ItemNotFoundException e) {
+            LOG.warn("Profile with id " + profileId + " is not found.",
+                    e);
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .build();
+        } catch (IOException e) {
+            LOG.error("Profile with id: " + profileId + " deletion failed.", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException e) {
+            LOG.info("Profile with id: {} deletion failed: {}", profileId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+        LOG.info("Profile with id: {} deleted.", profileId);
+        return Response.ok().build();
+    }
+
+    @Override
+    @DELETE
+    @Path("/profiles/{profileId}/comments/{commentId}")
+    public Response deleteCommentFromProfile(
+            @PathParam("profileId") String profileId,
+            @PathParam("commentId") String commentId) {
+        try {
+            final ComponentRegistry registry = this.getBaseRegistry();
+            try {
+                final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId);
+                if (comment != null
+                        && profileId.equals(comment.getComponentId())) {
+                    LOG.debug("Comment with id: {} set for deletion.", commentId);
+                    registry.deleteComment(commentId);
+                } else {
+                    throw new ComponentRegistryException(
+                            "Comment not found for specified profile");
+                }
+            } catch (ItemNotFoundException e1) {
+                LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                        e1.getMessage());
+                LOG.debug("Deletion failure details:", e1);
+                return Response.serverError().status(Status.NOT_FOUND)
+                        .entity("" + e1.getMessage()).build();
+            }
+
+        } catch (DeleteFailedException e) {
+            LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (ComponentRegistryException e) {
+            LOG.info("Could not retrieve component", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (IOException e) {
+            LOG.error("Comment with id: " + commentId + " deletion failed.", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException e) {
+            LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+        LOG.info("Comment with id: {} deleted.", commentId);
+        return Response.ok("Comment with id " + commentId + " deleted.").build();
+    }
+
+    @Override
+    @DELETE
+    @Path("/components/{componentId}/comments/{commentId}")
+    public Response deleteCommentFromComponent(
+            @PathParam("componentId") String componentId,
+            @PathParam("commentId") String commentId) {
+        try {
+            final ComponentRegistry registry = this.getBaseRegistry();
+            final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId);
+            if (comment != null
+                    && componentId.equals(comment.getComponentId())) {
+                LOG.debug("Comment with id: {} set for deletion.", commentId);
+                registry.deleteComment(commentId);
+            } else {
+                throw new ComponentRegistryException(
+                        "Comment not found for specified component");
+            }
+        } catch (ItemNotFoundException e) {
+            LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .entity("" + e.getMessage()).build();
+        } catch (DeleteFailedException e) {
+            LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (ComponentRegistryException e) {
+            LOG.info("Could not retrieve component", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (IOException e) {
+            LOG.error("Comment with id: " + commentId + " deletion failed.", e);
+            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
+                    .build();
+        } catch (UserUnauthorizedException e) {
+            LOG.info("Comment with id: {} deletion failed: {}", commentId,
+                    e.getMessage());
+            LOG.debug("Deletion failure details:", e);
+            return Response.serverError().status(Status.FORBIDDEN)
+                    .entity("" + e.getMessage()).build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+        LOG.info("Comment with id: {} deleted.", commentId);
+        return Response.ok("Comment with id " + commentId + " deleted.").build();
+    }
+
+    @Override
+    @GET
+    @Path("/profiles/{profileId}/{rawType}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
+    public Response getRegisteredProfileRawType(
+            @PathParam("profileId") final String profileId,
+            @PathParam("rawType") String rawType) throws ComponentRegistryException {
+
+
+        LOG.debug("Profile with id {} and rawType {} is requested.", profileId,
+                rawType);
+        try {
+            final ComponentRegistry registry = this.getBaseRegistry();
+
+            ProfileDescription desc = registry.getProfileDescriptionAccessControlled(profileId);
+            if (desc == null) {
+                return Response.status(Status.NOT_FOUND).build();
+            }
+
+            StreamingOutput result = null;
+            String fileName = desc.getName() + "." + rawType;
+            if ("xml".equalsIgnoreCase(rawType)) {
+                result = new StreamingOutput() {
+                    @Override
+                    public void write(OutputStream output) throws IOException,
+                            WebApplicationException {
+                        try {
+                            registry.getMDProfileAsXml(profileId, output);
+                        } catch (Exception e) {
+                            LOG.warn("Could not retrieve component {}",
+                                    profileId);
+                            LOG.debug("Details", e);
+                            throw new WebApplicationException(e, Response
+                                    .serverError()
+                                    .status(Status.INTERNAL_SERVER_ERROR)
+                                    .build());
+                        }
+                    }
+                };
+            } else if ("xsd".equalsIgnoreCase(rawType)) {
+                result = new StreamingOutput() {
+                    @Override
+                    public void write(OutputStream output) throws IOException,
+                            WebApplicationException {
+                        try {
+                            registry.getMDProfileAsXsd(profileId, output);
+                        } catch (Exception e) {
+                            LOG.warn("Could not retrieve component {}",
+                                    profileId);
+                            LOG.debug("Details", e);
+                            throw new WebApplicationException(e, Response
+                                    .serverError()
+                                    .status(Status.INTERNAL_SERVER_ERROR)
+                                    .build());
+                        }
+                    }
+                };
+            } else {
+                throw new WebApplicationException(Response
+                        .serverError()
+                        .entity("unsupported rawType: " + rawType
+                        + " (only xml or xsd are supported)").build());
+            }
+            return createDownloadResponse(result, fileName);
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).build();
+        } catch (ItemNotFoundException e) {
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .entity("" + e.getMessage()).build();
+        } catch (AuthenticationFailException e1) {
+            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
+                    .build();
+        }
+
+    }
+
+    private Response createDownloadResponse(StreamingOutput result,
+            String fileName) {
+        // Making response so it triggers browsers native save as dialog.
+        Response response = Response
+                .ok()
+                .type("application/x-download")
+                .header("Content-Disposition",
+                "attachment; filename=\"" + fileName + "\"")
+                .entity(result).build();
+        return response;
+
+    }
+
+    @Override
+    @POST
+    @Path("/profiles")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    @Consumes("multipart/form-data")
+    public Response registerProfile(
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+        try {
+            Principal principal = checkAndGetUserPrincipal();
+            UserCredentials userCredentials = getUserCredentials(principal);
+            ProfileDescription desc = this.createNewProfileDescription();
+            desc.setCreatorName(userCredentials.getDisplayName());
+            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
+            // be created
+            // here, now Id
+            // is
+            // constructed
+            // by impl
+            desc.setName(name);
+            desc.setDescription(description);
+            desc.setGroupName(group);
+            desc.setDomainName(domainName);
+            desc.setPublic(false);
+            LOG.debug("Trying to register Profile: {}", desc);
+            ComponentRegistry cr = this.getRegistry(RegistrySpace.PRIVATE, null);
+            return this.register(input, desc, new NewAction(), cr);
+        } catch (AuthenticationFailException e) {
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+        }
+    }
+
+    @Override
+    @POST
+    @Path("/components")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    @Consumes("multipart/form-data")
+    public Response registerComponent(
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @FormDataParam(NAME_FORM_FIELD) String name,
+            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
+            @FormDataParam(GROUP_FORM_FIELD) String group,
+            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
+        try {
+            Principal principal = checkAndGetUserPrincipal();
+            UserCredentials userCredentials = getUserCredentials(principal);
+            ComponentDescription desc = createNewComponentDescription();
+            desc.setCreatorName(userCredentials.getDisplayName());
+            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
+            // be created
+            // here, now Id
+            // is
+            // constructed
+            // by impl
+            desc.setName(name);
+            desc.setDescription(description);
+            desc.setGroupName(group);
+            desc.setDomainName(domainName);
+            desc.setPublic(false);
+            LOG.debug("Trying to register Component: {}", desc);
+            ComponentRegistry cr = this.getRegistry(RegistrySpace.PRIVATE, null);
+            return this.register(input, desc, new NewAction(), cr);
+        } catch (AuthenticationFailException e) {
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
+                    .build();
+        }
+    }
+
+    @Override
+    @POST
+    @Path("/components/{componentId}/comments")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    @Consumes("multipart/form-data")
+    public Response registerCommentInComponent(
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @PathParam("componentId") String componentId) throws ComponentRegistryException {
+        try {
+            ComponentRegistry registry = this.getBaseRegistry();
+            ComponentDescription description = registry.getComponentDescriptionAccessControlled(componentId);
+
+            LOG.debug("Trying to register comment to {}", componentId);
+
+            return this.registerComment(input, description, registry);
+        } catch (AuthenticationFailException e) {
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN)
+                    .build();
+        } catch (ItemNotFoundException e) {
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .entity("" + e.getMessage()).build();
+        }
+    }
+
+    // TODO test with the POSTMAN
+    @Override
+    @POST
+    @Path("/profiles/{profileId}/comments")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    @Consumes("multipart/form-data")
+    public Response registerCommentInProfile(
+            @FormDataParam(DATA_FORM_FIELD) InputStream input,
+            @PathParam("profileId") String profileId)
+            throws ComponentRegistryException {
+        try {
+            ComponentRegistry registry = this.getBaseRegistry();
+            ProfileDescription description = registry
+                    .getProfileDescriptionAccessControlled(profileId);
+
+            LOG.debug("Trying to register comment to {}", profileId);
+
+            return this.registerComment(input, description, registry);
+        } catch (AuthenticationFailException e) {
+            LOG.debug("Details", e);
+            return Response.serverError().status(Status.UNAUTHORIZED)
+                    .build();
+        } catch (UserUnauthorizedException ex) {
+            return Response.status(Status.FORBIDDEN)
+                    .build();
+        } catch (ItemNotFoundException e1) {
+            return Response.serverError().status(Status.NOT_FOUND)
+                    .entity("" + e1.getMessage()).build();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/pingSession")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Response pingSession() {
+        boolean stillActive = false;
+        Principal userPrincipal = security.getUserPrincipal();
+        if (LOG.isInfoEnabled()) {
+            LOG.debug("ping by <{}>",
+                    (userPrincipal == null ? "unauthorized user"
+                    : userPrincipal.getName()));
+        }
+        if (request != null) {
+            if (userPrincipal != null
+                    && !ComponentRegistryFactory.ANONYMOUS_USER
+                    .equals(userPrincipal.getName())) {
+                stillActive = !((HttpServletRequest) request).getSession()
+                        .isNew();
+            }
+        }
+        return Response
+                .ok()
+                .entity(String.format("<session stillActive=\"%s\"/>",
+                stillActive)).build();
+    }
+
+    private Response register(InputStream input, BaseDescription desc, RegisterAction action, ComponentRegistry registry) throws UserUnauthorizedException {
+        try {
+
+
+            DescriptionValidator descriptionValidator = new DescriptionValidator(
+                    desc);
+            MDValidator validator = new MDValidator(input, desc, registry, marshaller);
+            RegisterResponse response = new RegisterResponse();
+            //obsolete. Make it setstatus
+            response.setIsInUserSpace(!desc.isPublic());
+            this.validate(response, descriptionValidator, validator);
+            if (response.getErrors().isEmpty()) {
+
+                CMDComponentSpec spec = validator.getCMDComponentSpec();
+
+                // removing filename from spec before it gets extended.
+                // recursion over all the components
+                setFileNamesFromListToNull(Collections.singletonList(spec.getCMDComponent()));
+
+                try {
+                    checkForRecursion(validator, registry, desc);
+
+                    // Add profile
+                    int returnCode = action.execute(desc, spec, response,
+                            registry);
+                    if (returnCode == 0) {
+                        response.setRegistered(true);
+                        response.setDescription(desc);
+                    } else {
+                        response.setRegistered(false);
+                        response.addError("Unable to register at this moment. Internal server error.");
+                    }
+                } catch (ComponentRegistryException ex) {
+                    // Recursion detected
+                    response.setRegistered(false);
+                    response.addError("Error while expanding specification. "
+                            + ex.getMessage());
+                } catch (ItemNotFoundException ex) {
+                    // Recursion detected
+                    response.setRegistered(false);
+                    response.addError("Error while expanding specification. "
+                            + ex.getMessage());
+                }
+            } else {
+                LOG.warn("Registration failed with validation errors: {}",
+                        Arrays.toString(response.getErrors().toArray()));
+                response.setRegistered(false);
+            }
+            LOG.info("Registered new {} {}", desc.isProfile() ? "profile"
+                    : "component", desc);
+            response.setIsProfile(desc.isProfile());
+            return Response.ok(response).build();
+        } finally {
+            try {
+                input.close();// either we read the input or there was an
+                // exception, we need to close it.
+            } catch (IOException e) {
+                LOG.error("Error when closing inputstream: ", e);
+            }
+        }
+    }
+
+    /**
+     *
+     * @param validator
+     * @param registry
+     * @param desc
+     * @throws ComponentRegistryException if recursion is detected or something
+     * goes wrong while trying to detect recursion
+     */
+    private void checkForRecursion(MDValidator validator,
+            ComponentRegistry registry, BaseDescription desc)
+            throws ComponentRegistryException {
+        try {
+            // Expand to check for recursion. Operate on copy so that original
+            // does not get expanded.
+            final CMDComponentSpec specCopy = validator
+                    .getCopyOfCMDComponentSpec();
+            // In case of recursion, the following will throw a
+            // ComponentRegistryException
+            registry.getExpander().expandNestedComponent(
+                    Lists.newArrayList(specCopy.getCMDComponent()), desc.getId());
+        } catch (JAXBException ex) {
+            throw new ComponentRegistryException(
+                    "Unmarshalling failed while preparing recursion detection",
+                    ex);
+        }
+    }
+
+    private Response registerComment(InputStream input, BaseDescription description, ComponentRegistry registry) throws UserUnauthorizedException, AuthenticationFailException {
+        try {
+            CommentValidator validator = new CommentValidator(input, description, marshaller);
+            CommentResponse responseLocal = new CommentResponse();
+
+            responseLocal.setIsInUserSpace(!description.isPublic());
+            this.validateComment(responseLocal, validator);
+            if (responseLocal.getErrors().isEmpty()) {
+                Comment com = validator.getCommentSpec();
+                // int returnCode = action.executeComment(com, response,
+                // registry, principal.getName());
+
+                // If user name is left empty, fill it using the user's display
+                // name
+
+                Principal principal = this.checkAndGetUserPrincipal();
+                UserCredentials userCredentials = this.getUserCredentials(principal);
+                if (null == com.getUserName() || "".equals(com.getUserName())) {
+                    if (userCredentials != null) {
+                        com.setUserName(userCredentials.getDisplayName());
+                    } else {
+                        com.setUserName(principal.getName());
+                    }
+                }
+                try {
+                    int returnCode = registry.registerComment(com,
+                            principal.getName());
+                    if (returnCode == 0) {
+                        responseLocal.setRegistered(true);
+                        responseLocal.setComment(com);
+                    } else {
+                        responseLocal.setRegistered(false);
+                        responseLocal.addError("Unable to post at this moment. Internal server error.");
+                    }
+                    if (com.getComponentId() != null) {
+                        LOG.info("Posted new comment on component {}",
+                                com.getComponentId());
+                    } else {
+                        LOG.info("Posted new comment on profile {}",
+                                com.getComponentId());
+                    }
+                } catch (ItemNotFoundException e) {
+                    return Response.serverError().status(Status.NOT_FOUND)
+                            .entity("" + e.getMessage()).build();
+                }
+            } else {
+                LOG.warn(
+                        "Posting of comment failed with validation errors: {}",
+                        Arrays.toString(responseLocal.getErrors().toArray()));
+                responseLocal.setRegistered(false);
+            }
+            return Response.ok(responseLocal).build();
+        } catch (ComponentRegistryException ex) {
+            LOG.error("Error while inserting comment: ", ex);
+            return Response.serverError().entity(ex.getMessage()).build();
+        } finally {
+            try {
+                input.close();// either we read the input or there was an
+                // exception, we need to close it.
+            } catch (IOException e) {
+                LOG.error("Error when closing inputstream: ", e);
+                return Response.serverError().build();
+            }
+        }
+    }
+
+    private ComponentDescription createNewComponentDescription() {
+        ComponentDescription desc = ComponentDescription.createNewDescription();
+        desc.setHref(createXlink(desc.getId()));
+        return desc;
+    }
+
+    private ProfileDescription createNewProfileDescription() {
+        ProfileDescription desc = ProfileDescription.createNewDescription();
+        desc.setHref(createXlink(desc.getId()));
+        return desc;
+    }
+
+    private String createXlink(String id) {
+        URI uri = uriInfo.getRequestUriBuilder().path(id).build();
+        return uri.toString();
+    }
+
+    /**
+     *
+     * @return The application's base URI as configured in the
+     * {@link #APPLICATION_BASE_URL_PARAM} context parameter. If correctly
+     * configured, it should look something like
+     * "http://catalog.clarin.eu/ds/ComponentRegistry". <em>Be aware that this
+     * can also be null if configured incorrectly!</em>
+     *
+     * @see #APPLICATION_BASE_URL_PARAM
+     */
+    private String getApplicationBaseURI() {
+        return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
+    }
+
+    private void validate(RegisterResponse response, Validator... validators) throws UserUnauthorizedException {
+        for (Validator validator : validators) {
+            if (!validator.validate()) {
+                for (String error : validator.getErrorMessages()) {
+                    response.addError(error);
+                }
+            }
+        }
+    }
+
+    private void validateComment(CommentResponse response,
+            Validator... validators) throws UserUnauthorizedException {
+        for (Validator validator : validators) {
+            if (!validator.validate()) {
+                for (String error : validator.getErrorMessages()) {
+                    response.addError(error);
+                }
+            }
+        }
+    }
+
+    /**
+     * @param componentRegistryFactory the componentRegistryFactory to set
+     */
+    @Override
+    public void setComponentRegistryFactory(
+            ComponentRegistryFactory componentRegistryFactory) {
+        this.componentRegistryFactory = componentRegistryFactory;
+    }
+
+    /**
+     *
+     * @param listofcomponents a list of components whose file-names and whose
+     * childrens' filenames are to be set to null
+     */
+    @Override
+    public void setFileNamesFromListToNull(
+            List<CMDComponentType> listofcomponents) {
+
+        for (CMDComponentType currentcomponent : listofcomponents) {
+            setFileNamesToNullCurrent(currentcomponent);
+        }
+
+    }
+
+    /**
+     *
+     * @param currentcomponent a component whose file-name and whose children
+     * filenames are to be set to null
+     */
+    protected void setFileNamesToNullCurrent(CMDComponentType currentcomponent) {
+        currentcomponent.setFilename(null);
+        setFileNamesFromListToNull(currentcomponent.getCMDComponent());
+    }
+
+    /**
+     *
+     * @param isPublished if "true" then profiles and components from the user's
+     * workspace, otherwise -- public
+     * @param limit the number of items to be displayed
+     * @return rss for the components in the database to which we are currently
+     * connected
+     * @throws ComponentRegistryException
+     * @throws ParseException
+     */
+    @Override
+    @GET
+    @Path("/components/rss")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Rss getRssComponent(@QueryParam(GROUPID_PARAM) String groupId,
+            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
+            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
+            throws ComponentRegistryException, ParseException, IOException {
+        List<ComponentDescription> components = null;
+        try {
+            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
+            components = cr.getComponentDescriptions();
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new Rss();
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
+            return new Rss();
+        }
+        // obsolete, add group Id
+        final RssCreatorDescriptions instance = new RssCreatorDescriptions(!registrySpace.equalsIgnoreCase("published"), getApplicationBaseURI(), "components",
+                Integer.parseInt(limit), components,
+                ComponentUtils.COMPARE_ON_DATE);
+        final Rss rss = instance.getRss();
+        LOG.debug("Releasing RSS of {} most recently registered components",
+                limit);
+        return rss;
+    }
+
+    /**
+     *
+     * @param isPublished if "true" then profiles and components from the user's
+     * workspace, otherwise -- public
+     * @param limit the number of items to be displayed
+     * @return rss for the profiles in the database to which we are currently
+     * connected
+     * @throws ComponentRegistryException
+     * @throws ParseException
+     */
+    @Override
+    @GET
+    @Path("/profiles/rss")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Rss getRssProfile(@QueryParam(GROUPID_PARAM) String groupId,
+            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
+            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
+            throws ComponentRegistryException, ParseException, IOException {
+        List<ProfileDescription> profiles = null;
+        try {
+            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
+            profiles = cr.getProfileDescriptions();
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new Rss();
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
+            return new Rss();
+        }
+        final RssCreatorDescriptions instance = new RssCreatorDescriptions(
+                !registrySpace.equalsIgnoreCase("published"), getApplicationBaseURI(), "profiles",
+                Integer.parseInt(limit), profiles,
+                ComponentUtils.COMPARE_ON_DATE);
+        final Rss rss = instance.getRss();
+        LOG.debug("Releasing RSS of {} most recently registered profiles",
+                limit);
+        return rss;
+    }
+
+    /**
+     *
+     * @param profileId the Id of a profile whose comments are to be rss-ed
+     * @param isPublished if "true" then profiles and components from the user's
+     * workspace, otherwise -- public
+     * @param limit the number of items to be displayed
+     * @return rss of the comments for a chosen profile
+     * @throws ComponentRegistryException
+     * @throws IOException
+     * @throws JAXBException
+     * @throws ParseException
+     */
+    @Override
+    @GET
+    @Path("/profiles/{profileId}/comments/rss")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Rss getRssOfCommentsFromProfile(
+            @PathParam("profileId") String profileId,
+            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
+            throws ComponentRegistryException, IOException, JAXBException,
+            ParseException {
+        try {
+
+            ComponentRegistry cr = this.getBaseRegistry();
+
+            final List<Comment> comments = cr.getCommentsInProfile(profileId);
+            final ProfileDescription pd = cr.getProfileDescriptionAccessControlled(profileId);
+            final String profileName = pd.getName();
+            boolean profileIsPrivate = !pd.isPublic();
+            // obsolete, status must be involved, not boolean profileIsPrivate
+            final RssCreatorComments instance = new RssCreatorComments(profileIsPrivate,
+                    getApplicationBaseURI(), Integer.parseInt(limit), profileId,
+                    profileName, "profile", comments, Comment.COMPARE_ON_DATE);
+            final Rss rss = instance.getRss();
+            LOG.debug("Releasing RSS of {} most recent post on profile {}", limit,
+                    profileId);
+            return rss;
+        } catch (UserUnauthorizedException ex) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new Rss();
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new Rss();
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new Rss();
+        }
+    }
+
+    /**
+     *
+     * @param componentId the Id of a component whose comments are to be rss-ed
+     * @param isPublished if "true" then profiles and components from the user's
+     * workspace, otherwise -- public
+     * @param limit the number of items to be displayed
+     * @return rss of the comments for a chosen component
+     * @throws ComponentRegistryException
+     * @throws IOException
+     * @throws JAXBException
+     * @throws ParseException
+     */
+    @Override
+    @GET
+    @Path("/components/{componentId}/comments/rss")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public Rss getRssOfCommentsFromComponent(
+            @PathParam("componentId") String componentId,
+            @QueryParam(NUMBER_OF_RSSITEMS)
+            @DefaultValue("20") String limit)
+            throws ComponentRegistryException, IOException, JAXBException,
+            ParseException {
+        try {
+            ComponentRegistry cr = this.getBaseRegistry();
+            final List<Comment> comments = cr.getCommentsInComponent(componentId);
+            final ComponentDescription cd = cr.getComponentDescriptionAccessControlled(componentId);
+            final String componentName = cd.getName();
+            final boolean isPrivate = !cd.isPublic();
+            //oboslete. status must be involved, not boolean isPrivate
+            final RssCreatorComments instance = new RssCreatorComments(isPrivate,
+                    getApplicationBaseURI(), Integer.parseInt(limit), componentId,
+                    componentName, "component", comments, Comment.COMPARE_ON_DATE);
+            final Rss rss = instance.getRss();
+            LOG.debug("Releasing RSS of {} most recent post on component {}",
+                    limit, componentId);
+            return rss;
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode());
+            return new Rss();
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new Rss();
+        } catch (AuthenticationFailException e1) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode());
+            return new Rss();
+        }
+
+    }
+
+    @Override
+    @GET
+    @Path("/AllowedTypes")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public AllowedAttributetypesXML getAllowedAttributeTypes()
+            throws ComponentRegistryException, IOException, JAXBException,
+            ParseException {
+        return (new AllowedAttributetypesXML());
+    }
+
+    @Override
+    @GET
+    @Path("/groups/usermembership")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<Group> getGroupsTheCurrentUserIsAMemberOf() {
+        Principal principal = security.getUserPrincipal();
+        if (principal == null) {
+            return new ArrayList<Group>();
+        }
+        List<Group> groups = groupService.getGroupsOfWhichUserIsAMember(principal.getName());
+        return groups;
+    }
+
+    @Override
+    @GET
+    @Path("/items/{itemId}/groups")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public List<Group> getGroupsTheItemIsAMemberOf(@PathParam("itemId") String itemId) {
+        return groupService.getGroupsTheItemIsAMemberOf(itemId);
+    }
+
+    @Override
+    @POST
+    @Path("/items/{itemId}/transferownership")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public String transferItemOwnershipToGroup(@PathParam("itemId") String itemId,
+            @QueryParam("groupId") long groupId) throws IOException {
+        Principal principal = security.getUserPrincipal();
+        try {
+            groupService.transferItemOwnershipFromUserToGroupId(principal.getName(), groupId, itemId);
+            return "No exceptions happen, the item shoul be transferred";
+        } catch (UserUnauthorizedException e) {
+            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
+            return e.toString();
+        }
+    }
+
+    @Override
+    @GET
+    @Path("/items/{itemId}")
+    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
+        MediaType.APPLICATION_JSON})
+    public BaseDescription getBaseDescription(@PathParam("itemId") String itemId) throws ComponentRegistryException, IOException {
+        LOG.debug("Item with id: {} is requested.", itemId);
+        try {
+            ComponentRegistry cr = this.getBaseRegistry();
+            try {
+                BaseDescription description = cr.getComponentDescriptionAccessControlled(itemId);
+                return description;
+            } catch (UserUnauthorizedException ex1) {
+                try {
+                    BaseDescription description = cr.getProfileDescriptionAccessControlled(itemId);
+                    return description;
+                } catch (UserUnauthorizedException ex2) {
+                    response.sendError(Status.FORBIDDEN.getStatusCode(), "User \'" + security.getUserPrincipal().getName() + "\' does not have access to the item with the given id or the item with the given id does not exist.");
+                    return new BaseDescription();
+                }
+            }
+        } catch (ItemNotFoundException e) {
+            response.sendError(Status.NOT_FOUND.getStatusCode());
+            return new BaseDescription();
+        } catch (AuthenticationFailException e) {
+            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
+            return new BaseDescription();
+        }
+    }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/IComponentRegistryRestService.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/IComponentRegistryRestService.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/IComponentRegistryRestService.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.rest;
 
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -13,5 +14,4 @@
 
 import clarin.cmdi.componentregistry.AllowedAttributetypesXML;
-import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
@@ -44,42 +44,36 @@
 	public static final String GROUP_FORM_FIELD = "group";
 	public static final String DOMAIN_FORM_FIELD = "domainName";
-	public static final String USERSPACE_PARAM = "userspace";
+	public static final String REGISTRY_SPACE_PARAM = "registrySpace";
 	public static final String GROUPID_PARAM = "groupid";
 	public static final String METADATA_EDITOR_PARAM = "mdEditor";
 	public static final String NUMBER_OF_RSSITEMS = "limit";
 
-	List<ComponentDescription> getRegisteredComponents(boolean userspace, String groupId)
-			throws ComponentRegistryException;
-
-	List<ProfileDescription> getRegisteredProfiles(boolean userspace,
-			boolean metadataEditor, String groupId) throws ComponentRegistryException;
-
-	Response getRegisteredComponent(String componentId, boolean userspace)
-			throws ComponentRegistryException;
-
-	Response getRegisteredComponentRawType(String componentId, String rawType);
-
-	ComponentRegistry findRegistry(String id,
-			RegistryClosure<? extends BaseDescription> clos)
-			throws ComponentRegistryException;
-
-	Response getRegisteredProfile(String profileId, boolean userspace)
-			throws ComponentRegistryException;
-
-	List<BaseDescription> getComponentUsage(String componentId,
-			boolean userspace) throws ComponentRegistryException;
-
-	List<Comment> getCommentsFromProfile(String profileId, boolean userspace)
-			throws ComponentRegistryException;
-
-	List<Comment> getCommentsFromComponent(String componentId, boolean userspace)
-			throws ComponentRegistryException;
-
-	Comment getSpecifiedCommentFromProfile(String profileId, String commentId,
-			boolean userspace) throws ComponentRegistryException;
-
-	Comment getSpecifiedCommentFromComponent(String componentId,
-			String commentId, boolean userspace)
-			throws ComponentRegistryException;
+	List<ComponentDescription> getRegisteredComponents(String registrySpace, String groupId)
+			throws ComponentRegistryException, IOException, UserUnauthorizedException;
+
+	List<ProfileDescription> getRegisteredProfiles(String registrySpace, boolean metadataEditor, String groupId) throws ComponentRegistryException, IOException, UserUnauthorizedException;
+
+	Response getRegisteredComponent(String componentId) throws IOException;
+
+	Response getRegisteredProfile(String profileId) throws IOException;
+        
+        Response getRegisteredComponentRawType(String componentId, String rawType) throws ComponentRegistryException;
+
+        
+//	ComponentRegistry findRegistry(String id,
+//			RegistryClosure<? extends BaseDescription> clos)
+//			throws ComponentRegistryException;
+//
+//	
+
+	List<BaseDescription> getComponentUsage(String componentId) throws ComponentRegistryException, IOException;
+
+	List<Comment> getCommentsFromProfile(String profileId) throws ComponentRegistryException, IOException;
+
+	List<Comment> getCommentsFromComponent(String componentId) throws ComponentRegistryException, IOException;
+
+	Comment getSpecifiedCommentFromProfile(String profileId, String commentId) throws ComponentRegistryException, IOException ;
+
+	Comment getSpecifiedCommentFromComponent(String componentId, String commentId) throws ComponentRegistryException, IOException ;
 
 	/**
@@ -92,18 +86,17 @@
 	 * @return
 	 */
-	Response manipulateRegisteredProfile(String profileId, String method,
-			boolean userspace);
+	Response manipulateRegisteredProfile(String profileId, String method);
 
 	Response manipulateCommentFromProfile(String profileId, String commentId,
-			String method, boolean userspace);
+			String method);
 
 	Response manipulateCommentFromComponent(String componentId,
-			String commentId, String method, boolean userspace);
+			String commentId, String method);
 
 	Response publishRegisteredProfile(String profileId, InputStream input,
 			String name, String description, String group, String domainName);
 
-	Response updateRegisteredProfile(String profileId, boolean userspace,
-			InputStream input, String name, String description, String group,
+	Response updateRegisteredProfile(String profileId, 
+			InputStream input, String name, String description, String groupId,
 			String domainName);
 
@@ -117,39 +110,32 @@
 	 * @return
 	 */
-	Response manipulateRegisteredComponent(String componentId, String method,
-			boolean userspace);
+	Response manipulateRegisteredComponent(String componentId, String method);
 
 	Response publishRegisteredComponent(String componentId, InputStream input,
-			String name, String description, String group, String domainName);
-
-	Response updateRegisteredComponent(String componentId, boolean userspace,
-			InputStream input, String name, String description, String group,
+			String name, String description, String groupId, String domainName);
+
+	Response updateRegisteredComponent(String componentId,
+			InputStream input, String name, String description, String groupId,
 			String domainName);
 
-	Response deleteRegisteredComponent(String componentId, boolean userspace);
-
-	Response deleteRegisteredProfile(String profileId, boolean userspace);
-
-	Response deleteCommentFromProfile(String profileId, String commentId,
-			boolean userspace);
-
-	Response deleteCommentFromComponent(String componentId, String commentId,
-			boolean userspace);
-
-	Response getRegisteredProfileRawType(String profileId, String rawType);
+	Response deleteRegisteredComponent(String componentId);
+
+	Response deleteRegisteredProfile(String profileId);
+
+	Response deleteCommentFromProfile(String profileId, String commentId);
+
+	Response deleteCommentFromComponent(String componentId, String commentId);
+
+	Response getRegisteredProfileRawType(String profileId, String rawType) throws ComponentRegistryException;
 
 	Response registerProfile(InputStream input, String name,
-			String description, String group, String domainName,
-			boolean userspace);
+			String description, String groupId, String domainName);
 
 	Response registerComponent(InputStream input, String name,
-			String description, String group, String domainName,
-			boolean userspace);
-
-	Response registerCommentInComponent(InputStream input, String componentId,
-			boolean userspace) throws ComponentRegistryException;
-
-	Response registerCommentInProfile(InputStream input, String profileId,
-			boolean userspace) throws ComponentRegistryException;
+			String description, String groupId, String domainName);
+
+	Response registerCommentInComponent(InputStream input, String componentId) throws ComponentRegistryException;
+
+	Response registerCommentInProfile(InputStream input, String profileId) throws ComponentRegistryException;
 
 	Response pingSession();
@@ -158,6 +144,5 @@
 	 * @param componentRegistryFactory the componentRegistryFactory to set
 	 */
-	void setComponentRegistryFactory(
-			ComponentRegistryFactory componentRegistryFactory);
+	void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory);
 
 	/**
@@ -169,6 +154,6 @@
 	 * @throws ParseException
 	 */
-	Rss getRssComponent(boolean userspace, String limit)
-			throws ComponentRegistryException, ParseException;
+	Rss getRssComponent(String groupId, String registrySpace, String limit)
+			throws ComponentRegistryException, ParseException, IOException;
 
 	/**
@@ -180,6 +165,6 @@
 	 * @throws ParseException
 	 */
-	Rss getRssProfile(boolean userspace, String limit)
-			throws ComponentRegistryException, ParseException;
+	Rss getRssProfile(String groupId, String registrySpace, String limit)
+			throws ComponentRegistryException, ParseException, IOException;
 
 	/**
@@ -194,7 +179,6 @@
 	 * @throws ParseException
 	 */
-	Rss getRssOfCommentsFromProfile(String profileId, boolean userspace,
-			String limit) throws ComponentRegistryException, IOException,
-			JAXBException, ParseException;
+	Rss getRssOfCommentsFromProfile(String profileId, String limit) throws ComponentRegistryException, 
+			JAXBException, ParseException, IOException;
 
 	/**
@@ -209,5 +193,5 @@
 	 * @throws ParseException
 	 */
-	Rss getRssOfCommentsFromComponent(String componentId, boolean userspace,
+	Rss getRssOfCommentsFromComponent(String componentId,
 			String limit) throws ComponentRegistryException, IOException,
 			JAXBException, ParseException;
@@ -237,5 +221,5 @@
 	 * @param groupId
 	 */
-	void transferItemOwnershipToGroup(String itemId, long groupId);
+	String transferItemOwnershipToGroup(String itemId, long groupId) throws IOException;
 	
 	/**
@@ -244,5 +228,5 @@
 	 * @return
 	 */
-	BaseDescription getComponentDescription(String componentId) throws ComponentRegistryException;
+	BaseDescription getBaseDescription(String componentId) throws ComponentRegistryException, IOException;
 
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/MDValidator.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/MDValidator.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/MDValidator.java	(revision 5549)
@@ -5,9 +5,12 @@
 import clarin.cmdi.componentregistry.ComponentRegistryResourceResolver;
 import clarin.cmdi.componentregistry.Configuration;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.NullIdException;
+import clarin.cmdi.componentregistry.RegistrySpace;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.components.CMDComponentType;
 import clarin.cmdi.componentregistry.model.BaseDescription;
-import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.schema.cmd.Validator.Message;
 import clarin.cmdi.schema.cmd.ValidatorException;
@@ -29,5 +32,5 @@
 
 public class MDValidator implements Validator {
-    
+
     private final static Logger LOG = LoggerFactory.getLogger(MDValidator.class);
     static final String MISMATCH_ERROR = "Cannot register component as a profile or vica versa.";
@@ -36,5 +39,5 @@
     static final String SCHEMA_ERROR = "Error in reading general component schema: ";
     static final String IO_ERROR = "Error while reading specification or general component schema: ";
-    static final String COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR = "referenced component cannot be found in the published components: ";
+    static final String COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR = "referenced component cannot be found in the appropriate registry components: ";
     static final String COMPONENT_REGISTRY_EXCEPTION_ERROR = "An exception occurred while accessing the component registry: ";
     static final String ILLEGAL_ATTRIBUTE_NAME_ERROR = "Illegal attribute name: ";
@@ -47,6 +50,4 @@
     private final BaseDescription description;
     private final ComponentRegistry registry;
-    private final ComponentRegistry userRegistry;
-    private final ComponentRegistry publicRegistry;
     private final MDMarshaller marshaller;
 
@@ -61,20 +62,18 @@
      * @param registry
      */
-    public MDValidator(InputStream input, BaseDescription description, ComponentRegistry registry, ComponentRegistry userRegistry, ComponentRegistry publicRegistry, MDMarshaller marshaller) {
+    public MDValidator(InputStream input, BaseDescription description, ComponentRegistry registry, MDMarshaller marshaller) {
         this.input = input;
         this.description = description;
         this.registry = registry;
-        this.userRegistry = userRegistry;
-        this.publicRegistry = publicRegistry;
         this.marshaller = marshaller;
     }
-    
+
     @Override
     public List<String> getErrorMessages() {
         return errorMessages;
     }
-    
+
     @Override
-    public boolean validate() {
+    public boolean validate() throws UserUnauthorizedException {
         try {
             clarin.cmdi.schema.cmd.Validator validator = new clarin.cmdi.schema.cmd.Validator(new URL(Configuration.getInstance().getGeneralComponentSchema()));
@@ -116,65 +115,88 @@
             } catch (ComponentRegistryException e) {
                 errorMessages.add(COMPONENT_REGISTRY_EXCEPTION_ERROR + e);
+            } catch (ItemNotFoundException e2) {
+                errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + e2);
+            } catch (NullIdException e3) {
+                errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + e3);
             }
         }
         return errorMessages.isEmpty();
     }
-    
+
     private byte[] getBytesFromInputStream() throws IOException {
         int len;
         byte[] b = new byte[4096];
         final ByteArrayOutputStream bOS = new ByteArrayOutputStream();
-        
+
         while ((len = input.read(b)) > 0) {
             bOS.write(b, 0, len);
         }
-        
+
         return bOS.toByteArray();
     }
 
-    private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException {
+    private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
         validateComponents(Collections.singletonList(componentSpec.getCMDComponent()));
     }
-    
-    private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException {
+
+    private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
         for (CMDComponentType cmdComponentType : cmdComponents) {
-            validateDescribedComponents(cmdComponentType);
-            validateComponents(cmdComponentType.getCMDComponent());//Recursion
-        }
-    }
-    
-    private void validateDescribedComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException {
-        checkPublicComponents(cmdComponentType);
-    }
-    
-    private void checkPublicComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException {
+            this.validateDescribedComponents(cmdComponentType);
+            this.validateComponents(cmdComponentType.getCMDComponent());//Recursion
+        }
+    }
+
+    private void validateDescribedComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
+        this.checkComponentInSpace(cmdComponentType);
+    }
+
+    private void checkComponentInSpace(CMDComponentType cmdComponentType) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
         if (isDefinedInSeparateFile(cmdComponentType)) {
             String id = cmdComponentType.getComponentId();
-            CMDComponentSpec registeredComponent;
-            if (registry.isPublic()) { // public registry requires only published components
-                registeredComponent = registry.getMDComponent(id);
-                if (registeredComponent == null) {
-                    String error = cmdComponentType.getComponentId();
-                    if (userRegistry != null) {
-                        ComponentDescription desc = userRegistry.getComponentDescription(id);
-                        if (desc != null) {
-                            error = desc.getName() + " (" + cmdComponentType.getComponentId() + ")";
+            if (id == null) {
+                String name = (cmdComponentType.getName() == null) ? "null" : cmdComponentType.getName();
+                throw new NullIdException("The component with the name " + name + " has a null id. :(");
+            }
+            CMDComponentSpec registeredComponent = registry.getMDComponent(id);
+            if (registeredComponent != null) {
+                String componentId = cmdComponentType.getComponentId();
+                Boolean isPublicB = registry.isItemPublic(id);// throws ItemNotFoundException
+                boolean isPublic = isPublicB.booleanValue();
+                if (isPublic) {  // if  a component is public, it is available for any registry
+                    return;
+                };
+                // a private component for a private registry is available only if its owner is the owner of the resgitry
+                if (registry.getRegistrySpace().equals(RegistrySpace.PRIVATE)) {
+                    Number registryOwnerId = registry.getRegistryOwner().getId();
+                    Number componentOwnerId = registry.getBaseDescriptionOwnerId(cmdComponentType.getComponentId());
+                    if (registryOwnerId.equals(componentOwnerId)) {
+                        return;
+                    };
+                    errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (private registry)");
+                    return;
+
+                } else { // a private component in a group registry is availabe only if it belongs to the group
+                    if (registry.getRegistrySpace().equals(RegistrySpace.GROUP)) {
+                        if (registry.getGroupId() == null) {
+                            errorMessages.add(COMPONENT_REGISTRY_EXCEPTION_ERROR + "in the group space, the group id is null");
+                            return;
                         }
+                        List<Number> componentGroupIds = registry.getItemGroups(cmdComponentType.getComponentId());
+                        if (componentGroupIds.contains(registry.getGroupId())) {
+                            return;
+                        }
+                        errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (group registry) " + registry.getGroupId());
+                        return;
                     }
-                    errorMessages.add(COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR + error);
+                    errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (private component in public registry).");
+                    return;
                 }
-            } else { //User registry, can link to components from public registry and the user's registry
-                registeredComponent = registry.getMDComponent(id);
-                if (registeredComponent == null) {
-                    registeredComponent = publicRegistry.getMDComponent(id);
-                    if (registeredComponent == null) {
-                        errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + cmdComponentType.getComponentId());
-                    }
-                }
-                
-            }
-        }
-    }
-    
+
+            };
+            errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + cmdComponentType.getComponentId());
+        }
+
+    }
+
     private boolean isDefinedInSeparateFile(CMDComponentType cmdComponentType) {
         return cmdComponentType.getName() == null;
@@ -195,6 +217,5 @@
      * has validated. If you are not going to alter this copy, you can re-use
      * and share the copy used during validation by getting it from {@link #getCMDComponentSpec()
-     * }.
-     * <em>Do not call before having called {@link #validate() }!</em>
+     * }. <em>Do not call before having called {@link #validate() }!</em>
      *
      * @return a freshly unmarshalled copy of the spec based on the bytes
@@ -209,6 +230,8 @@
         // Re-unmarshall original bytes
         return unmarshalSpec(originalSpecBytes);
-    }
-    
+
+
+    }
+
     private CMDComponentSpec unmarshalSpec(byte[] inputBytes) throws JAXBException {
         return marshaller.unmarshal(CMDComponentSpec.class, new ByteArrayInputStream(inputBytes), null);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ProfileClosure.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ProfileClosure.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ProfileClosure.java	(revision 5549)
@@ -3,4 +3,6 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
 
@@ -8,6 +10,6 @@
 
     @Override
-    public ProfileDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException {
-        return registry.getProfileDescription(id);
+    public ProfileDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
+        return registry.getProfileDescriptionAccessControlled(id);
     }
 
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/PublishAction.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/PublishAction.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/PublishAction.java	(revision 5549)
@@ -4,4 +4,6 @@
 
 import clarin.cmdi.componentregistry.ComponentRegistry;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -17,5 +19,5 @@
 
     @Override
-    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) {
+    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) throws UserUnauthorizedException, ItemNotFoundException{
         response.setIsInUserSpace(false);
         return registry.publish(desc, spec, principal);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegisterAction.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegisterAction.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegisterAction.java	(revision 5549)
@@ -2,4 +2,6 @@
 
 import clarin.cmdi.componentregistry.ComponentRegistry;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -8,5 +10,5 @@
 public interface RegisterAction {
 
-    int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry);
+    int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) throws UserUnauthorizedException, ItemNotFoundException;
 
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegistryClosure.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegistryClosure.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegistryClosure.java	(revision 5549)
@@ -3,9 +3,11 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryException;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.model.BaseDescription;
 
 public interface RegistryClosure<T extends BaseDescription> {
     
-    T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException;
+    T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException,  UserUnauthorizedException, ItemNotFoundException;
 
 
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/UpdateAction.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/UpdateAction.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/UpdateAction.java	(revision 5549)
@@ -1,7 +1,9 @@
 package clarin.cmdi.componentregistry.rest;
 
-import java.security.Principal;
+//import java.security.Principal;
 
 import clarin.cmdi.componentregistry.ComponentRegistry;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -10,13 +12,13 @@
 public class UpdateAction implements RegisterAction {
     
-    private final Principal principal;
-
-    public UpdateAction(Principal principal) {
-        this.principal = principal;
-    }
+//    private final Principal principal;
+//
+//    public UpdateAction(Principal principal) {
+//        this.principal = principal;
+//    }
     
     @Override
-    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) {
-        return registry.update(desc, spec, principal, false);
+    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry)  throws UserUnauthorizedException, ItemNotFoundException{
+        return registry.update(desc, spec, false);
     }
 
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/Validator.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/Validator.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/Validator.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.rest;
 
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import java.util.List;
 
@@ -15,5 +16,5 @@
      * Validate and create an error message when something is wrong.
      */
-    public boolean validate();
+    public boolean validate()  throws UserUnauthorizedException;
 
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreator.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreator.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreator.java	(revision 5549)
@@ -20,10 +20,10 @@
     private String channelTitle;
     private Comparator<T> comparator;
-    protected final boolean userspace;
+    protected final boolean isPrivate;
     private List<T> objs;
     private int limit;
 
-    protected RssCreator(boolean userspace, String baseURI, int limit, List<T> objs) {
-        this.userspace = userspace;
+    protected RssCreator(boolean isPrivate, String baseURI, int limit, List<T> objs) {
+        this.isPrivate = isPrivate;
         this.baseURI = baseURI;
         this.limit = limit;
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorComments.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorComments.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorComments.java	(revision 5549)
@@ -14,5 +14,5 @@
     /**
      *
-     * @param userspace if "true" then profiles and components from the user's
+     * @param isPrivate if "true" then profiles and components from the user's
      * workspace, otherwise -- public (uri-parameter)
      * @param baseURI where the database is located
@@ -27,9 +27,9 @@
      * @param comparator compare comments by dates
      */
-    public RssCreatorComments(boolean userspace, String baseURI, int limit,
+    public RssCreatorComments(boolean isPrivate, String baseURI, int limit,
             String descriptionId, String descriptionName, String descriptionType, List<Comment> comms, Comparator<Comment> comparator) {
-        super(userspace, baseURI, limit, comms);
-        setChannelLink(baseURI + "?item=" + descriptionId + ((userspace) ? "&space=user" : "") + "&browserview=comments");
-        setChannelTitle((userspace ? "Your workspace " : "Public ") + descriptionType + " \"" + descriptionName + "\"");
+        super(isPrivate, baseURI, limit, comms);
+        setChannelLink(baseURI + "?item=" + descriptionId + ((isPrivate) ? "&space=user" : "") + "&browserview=comments");
+        setChannelTitle((isPrivate ? "Private " : "Public ") + descriptionType + " \"" + descriptionName + "\"");
         setChannelDescription(String.format("Comments feed for the %s \"%s\"", descriptionType, descriptionName));
         setComparator(comparator);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorDescriptions.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorDescriptions.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorDescriptions.java	(revision 5549)
@@ -14,5 +14,5 @@
     /**
      *
-     * @param userspace if "true" then profiles and components from the user's
+     * @param isPrivate if "true" then profiles and components from the user's
      * workspace, otherwise -- public (uri-parameter)
      * @param baseURI where the database is located
@@ -23,9 +23,9 @@
      * @param comparator compare descriptions by dates
      */
-    public RssCreatorDescriptions(boolean userspace, String baseURI, String descriptionType,
+    public RssCreatorDescriptions(boolean isPrivate, String baseURI, String descriptionType,
             int limit, List<T> descriptions, Comparator<T> comparator) {
-        super(userspace, baseURI, limit, descriptions);
+        super(isPrivate, baseURI, limit, descriptions);
         setChannelLink(baseURI + "/");
-        setChannelTitle((userspace ? "Your workspace " : "Public ") + descriptionType);
+        setChannelTitle((isPrivate ? "Private " : "Public ") + descriptionType);
         setChannelDescription(String.format("News feed for the %s", descriptionType));
         setComparator(comparator);
@@ -41,5 +41,5 @@
     @Override
     protected RssItem fromArgToRssItem(T desc) {
-        String href = getBaseURI() + "?item=" + desc.getId() + (userspace ? "&space=user" : "");
+        String href = getBaseURI() + "?item=" + desc.getId() + (isPrivate ? "&space=user" : "");
         RssItem retval = new RssItem();
         retval.setDescription(desc.getDescription());
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/resources/spring-config/applicationContext.xml
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/resources/spring-config/applicationContext.xml	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/resources/spring-config/applicationContext.xml	(revision 5549)
@@ -70,5 +70,5 @@
 
 	<!-- Prototype bean for component registry (service) -->
-	<bean id="componentRegistry"
+	<bean id="componentRegistryDbImpl"
 		class="clarin.cmdi.componentregistry.impl.database.ComponentRegistryDbImpl"
 		scope="prototype" />
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/META-INF/context.xml
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/META-INF/context.xml	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/META-INF/context.xml	(revision 5549)
@@ -36,62 +36,36 @@
 -->
 <Context antiJARLocking="true" path="/ComponentRegistry">
-    <!-- 
+  <!-- 
 	Passed to the Flex UI via index.jsp so that it can locate the 
 	ComponentRegistry REST service. Just supply the application root:
 	the '/rest/registry' part will be added by the application.
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.serviceRootUrl" 
-	value="${serviceRootUrl}" />
-    
-    <!--
+  <Parameter name="eu.clarin.cmdi.componentregistry.serviceRootUrl" value="${serviceRootUrl}"/>
+  <!--
 	Location that gets redirected to from /documentation.jsp, which in turn is linked to
 	from the Flex application through the 'Help' link button.
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.documentationUrl" 
-	value="http://www.clarin.eu/cmdi" />
-    
-    <!--
+  <Parameter name="eu.clarin.cmdi.componentregistry.documentationUrl" value="http://www.clarin.eu/cmdi"/>
+  <!--
 	Space-separated list of users (getRemoteUser()) that should have access to the admin area of the ComponentRegistry
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.adminUsers" 
-	value="twagoo@mpi.nl olhsha@mpi.nl daan.broeder@mpi.nl dietuyt@mpi.nl Menzo.Windhouwer@mpi.nl" />
-
-    <!--
+  <Parameter name="eu.clarin.cmdi.componentregistry.adminUsers" value="twagoo@mpi.nl olhsha@mpi.nl daan.broeder@mpi.nl dietuyt@mpi.nl Menzo.Windhouwer@mpi.nl"/>
+  <!--
 	Location of the CMDI general component schema that validates component specifications
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.generalComponentSchemaUrl" 
-	value="https://infra.clarin.eu/cmd/general-component-schema.xsd" />
-    
-    <!--
+  <Parameter name="eu.clarin.cmdi.componentregistry.generalComponentSchemaUrl" value="https://infra.clarin.eu/cmd/general-component-schema.xsd"/>
+  <!--
 	Location of the stylesheet that transforms component specifications into XML schema documents
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.component2SchemaXslUrl" 
-	value="https://infra.clarin.eu/cmd/xslt/comp2schema-v2/comp2schema.xsl" />
-
-    <!-- 
+  <Parameter name="eu.clarin.cmdi.componentregistry.component2SchemaXslUrl" value="https://infra.clarin.eu/cmd/xslt/comp2schema-v2/comp2schema.xsl"/>
+  <!-- 
         Schema location that will go into xsi:schemaLocation attribute of component specification. Beware this should follow
         XML standards and have a namespace component (URI) and schema location component (URL) separated by a space
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.componentSpecSchemaLocation" 
-	value="http://www.clarin.eu/cmd https://infra.clarin.eu/cmd/general-component-schema.xsd" />
-
-    <!--
+  <Parameter name="eu.clarin.cmdi.componentregistry.componentSpecSchemaLocation" value="http://www.clarin.eu/cmd https://infra.clarin.eu/cmd/general-component-schema.xsd"/>
+  <!--
 	Base location of the ISOcat service
     -->
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.isocatRestUrl" 
-	value="https://catalog.clarin.eu/isocat/rest/" />
-	
-    <Parameter 
-	name="eu.clarin.cmdi.componentregistry.jpaDialect" 
-	value="org.hibernate.dialect.PostgreSQLDialect" />
-
-	
-
+  <Parameter name="eu.clarin.cmdi.componentregistry.isocatRestUrl" value="https://catalog.clarin.eu/isocat/rest/"/>
+  <Parameter name="eu.clarin.cmdi.componentregistry.jpaDialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
 </Context>
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMineComponent.jsp
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMineComponent.jsp	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMineComponent.jsp	(revision 5549)
@@ -0,0 +1,25 @@
+<%-- 
+    Document   : testManipulateComponent
+    Created on : Aug 1, 2014, 3:44:30 PM
+    Author     : olhsha
+--%>
+
+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+        <title>Manipulate component</title>
+    </head>
+    <body>
+        
+        <h3>Manipulate my Component clarin.eu:cr1:larin.eu:cr1:c_1406902201688 (this id is obsolete)</h1>
+        <form action="rest/registry/components/larin.eu:cr1:c_1406902201688" method="post">
+        <input type="text" 
+               id="method" 
+               name="method">
+        <button type="submit">Send</button>
+       </form>
+       
+    </body>
+</html>
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMyProfile.jsp
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMyProfile.jsp	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateMyProfile.jsp	(revision 5549)
@@ -0,0 +1,23 @@
+<%-- 
+    Document   : testManipulateComponent
+    Created on : Aug 1, 2014, 3:44:30 PM
+    Author     : olhsha
+--%>
+
+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+        <title>Manipulate component</title>
+    </head>
+    <body>
+        <h3>Manipulate my Profile clarin.eu:cr1:p_1406902201690 (this id is obsolete) </h1>
+        <form action="rest/registry/profiles/clarin.eu:cr1:p_1406902201690" method="post">
+        <input type="text" 
+               id="method" 
+               name="method">
+        <button type="submit">Send</button>
+        </form> 
+    </body>
+</html>
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicComponent.jsp
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicComponent.jsp	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicComponent.jsp	(revision 5549)
@@ -0,0 +1,24 @@
+<%-- 
+    Document   : testManipulateComponent
+    Created on : Aug 1, 2014, 3:44:30 PM
+    Author     : olhsha
+--%>
+
+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+        <title>Manipulate component</title>
+    </head>
+    <body>
+        <h3>Manipulate Old Public Component clarin.eu:cr1:c_1349361150637</h1>
+        <form action="rest/registry/components/clarin.eu:cr1:c_1349361150637" method="post">
+        <input type="text" 
+               id="method" 
+               name="method">
+        <button type="submit">Send</button>
+        </form>
+        
+    </body>
+</html>
Index: /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicProfile.jsp
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicProfile.jsp	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/testManipulateOldPublicProfile.jsp	(revision 5549)
@@ -0,0 +1,26 @@
+<%-- 
+    Document   : testManipulateComponent
+    Created on : Aug 1, 2014, 3:44:30 PM
+    Author     : olhsha
+--%>
+
+<%@page contentType="text/html" pageEncoding="UTF-8"%>
+<!DOCTYPE html>
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+        <title>Manipulate component</title>
+    </head>
+    <body>
+        
+        <h3>Manipulate Old Public Profile clarin.eu:cr1:p_1345561703673 </h1>
+        <form action="rest/registry/profiles/clarin.eu:cr1:p_1345561703673" method="post">
+        <input type="text" 
+               id="method" 
+               name="method">
+        <button type="submit">Send</button>
+        </form>
+        
+    </body>
+</html>
+
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/frontend/CMDItemInfoTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/frontend/CMDItemInfoTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/frontend/CMDItemInfoTest.java	(revision 5549)
@@ -3,6 +3,5 @@
 import clarin.cmdi.componentregistry.BaseUnitTest;
 import clarin.cmdi.componentregistry.ComponentStatus;
-import clarin.cmdi.componentregistry.MDMarshaller;
-import static org.junit.Assert.assertEquals;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -15,27 +14,28 @@
 public class CMDItemInfoTest extends BaseUnitTest{
 
+    // this is component status "private/public" from the database v.s. registry space public/private
     @Test
     public void testGetUserDir() throws Exception {
 	CMDItemInfo info = new CMDItemInfo(marshaller);
 	//info.setDataNode(new FileNode(createFile("users/user1/components/c_123/description.xml"), false));
-	info.setDataNode(new DisplayDataNode("test", false, createDescription(), ComponentStatus.PRIVATE));
+	info.setDataNode(new DisplayDataNode("test", false, createDescription(), RegistrySpace.PRIVATE));
 	assertTrue(info.isDeletable());
 	assertFalse(info.isUndeletable());
 	assertTrue(info.isEditable());
 	assertFalse(info.getDataNode().isDeleted());
-	assertEquals(ComponentStatus.PRIVATE, info.getStatus());
+	assertEquals(RegistrySpace.PRIVATE, info.getSpace());
 	//info.setDataNode(new FileNode(createFile("users/user1/components/deleted/c_123/description.xml"), true));
-	info.setDataNode(new DisplayDataNode("test", true, createDescription(), ComponentStatus.PRIVATE));
+	info.setDataNode(new DisplayDataNode("test", true, createDescription(), RegistrySpace.PRIVATE));
 	assertFalse(info.isDeletable());
 	assertTrue(info.isUndeletable());
 	assertTrue(info.isEditable());
 	assertTrue(info.getDataNode().isDeleted());
-	assertEquals(ComponentStatus.PRIVATE, info.getStatus());
+	assertEquals(RegistrySpace.PRIVATE, info.getSpace());
 	//info.setDataNode(new FileNode(createFile("components/c_123/description.xml"), false));
-	info.setDataNode(new DisplayDataNode("test", false, createDescription(), ComponentStatus.PUBLISHED));
+	info.setDataNode(new DisplayDataNode("test", false, createDescription(), RegistrySpace.PUBLISHED));
 	assertTrue(info.isDeletable());
 	assertFalse(info.isUndeletable());
 	assertTrue(info.isEditable());
-	assertEquals(ComponentStatus.PUBLISHED, info.getStatus());
+	assertEquals(RegistrySpace.PUBLISHED, info.getSpace());
 	//info.setDataNode(new FileNode(createFile("components/c_123/"), false));
 	info.setDataNode(new DisplayDataNode("test", false));
@@ -44,9 +44,9 @@
 	assertFalse(info.isEditable());
 	//info.setDataNode(new FileNode(createFile("components/deleted/c_123/description.xml"), true));
-	info.setDataNode(new DisplayDataNode("test", true, createDescription(), ComponentStatus.PUBLISHED));
+	info.setDataNode(new DisplayDataNode("test", true, createDescription(), RegistrySpace.PUBLISHED));
 	assertFalse(info.isDeletable());
 	assertTrue(info.isUndeletable());
 	assertTrue(info.isEditable());
-	assertEquals(ComponentStatus.PUBLISHED, info.getStatus());
+	assertEquals(RegistrySpace.PUBLISHED, info.getSpace());
 	assertTrue(info.getDescription().startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<profileDescription"));
 	//info.setDataNode(new FileNode(createFile("components/deleted/c_123/"), true));
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDaoTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDaoTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDaoTest.java	(revision 5549)
@@ -14,4 +14,5 @@
 import clarin.cmdi.componentregistry.BaseUnitTest;
 import clarin.cmdi.componentregistry.model.BaseDescription;
+import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.componentregistry.persistence.ComponentDao;
 import clarin.cmdi.componentregistry.persistence.jpa.UserDao;
@@ -96,5 +97,5 @@
 	// returned. Should also test the case where there are userspace
 	// descriptions
-	List<BaseDescription> descriptions = getDao().getUserspaceComponents(-1);
+	List<BaseDescription> descriptions = getDao().getPrivateBaseDescriptions(-1, ComponentDescription.COMPONENT_PREFIX);
 	assertEquals(0, descriptions.size());
     }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java	(revision 5549)
@@ -1,5 +1,4 @@
 package clarin.cmdi.componentregistry.impl.database;
 
-import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -14,7 +13,7 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.DeleteFailedException;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.frontend.CMDItemInfo;
 import clarin.cmdi.componentregistry.frontend.DisplayDataNode;
@@ -22,5 +21,7 @@
 import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
+import clarin.cmdi.componentregistry.model.RegistryUser;
 import clarin.cmdi.componentregistry.persistence.ComponentDao;
+import clarin.cmdi.componentregistry.persistence.jpa.UserDao;
 import clarin.cmdi.componentregistry.rest.DummyPrincipal;
 import clarin.cmdi.componentregistry.rest.RegistryTestHelper;
@@ -35,4 +36,8 @@
     @Autowired
     private ComponentDao componentDao;
+    
+    @Autowired
+    private UserDao userDao;
+    
     @Autowired
     private ComponentRegistryFactory componentRegistryFactory;
@@ -46,6 +51,13 @@
     }
 
+    // TODO: two questions
     @Test
     public void testForceUpdate() throws Exception {
+        
+        RegistryUser adminUser = new RegistryUser();
+	adminUser.setName(PRINCIPAL_ADMIN.getName());
+	adminUser.setPrincipalName(PRINCIPAL_ADMIN.getName());
+        userDao.save(adminUser);
+
 	ComponentRegistry testRegistry = componentRegistryFactory.getPublicRegistry();
 	String content1 = "";
@@ -57,6 +69,8 @@
 	content1 += "    </CMD_Component>\n";
 	content1 += "</CMD_ComponentSpec>\n";
-	ComponentDescription compDesc1 = RegistryTestHelper.addComponent(testRegistry, "XXX1", content1);
-
+	ComponentDescription compDesc1 = RegistryTestHelper.addComponent(testRegistry, "XXX1", content1, true);
+       
+        assertEquals(1, testRegistry.getComponentDescriptions().size());
+        
 	String content2 = "";
 	content2 += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
@@ -68,6 +82,12 @@
 	content2 += "    </CMD_Component>\n";
 	content2 += "</CMD_ComponentSpec>\n";
-	ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2);
+	ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2, true);
+       
 
+        // why two registries? 
+        // if you are logged in as an admin then at any registry you have the same all-mighty rights?
+        // testRegistry with the owner admin should be ok?
+        // how are these two registries connected, via componentDao?
+        
 	AdminRegistry adminReg = new AdminRegistry();
 	adminReg.setComponentRegistryFactory(componentRegistryFactory);
@@ -76,9 +96,12 @@
 	CMDItemInfo fileInfo = new CMDItemInfo(marshaller);
 	fileInfo.setForceUpdate(false);
-	fileInfo.setDataNode(new DisplayDataNode(compDesc1.getName(), false, compDesc1, ComponentStatus.PUBLISHED));
+	fileInfo.setDataNode(new DisplayDataNode(compDesc1.getName(), false, compDesc1, RegistrySpace.PUBLISHED));
 	fileInfo.setContent(content1);
-	try {
+	// TODO: how it should be?
+        try {
 	    adminReg.submitFile(fileInfo, PRINCIPAL_ADMIN);
-	    fail();
+            
+            // Twan ?? when submit should fail?
+            //fail();
 	} catch (SubmitFailedException e) {
 	}
@@ -87,12 +110,13 @@
 
 	assertEquals(1, testRegistry.getComponentDescriptions().size());
-	try {
+	
+        try {
 	    fileInfo.setForceUpdate(false);
 	    adminReg.delete(fileInfo, PRINCIPAL_ADMIN);
-	    fail();
 	} catch (SubmitFailedException e) {
 	    assertTrue(e.getCause() instanceof DeleteFailedException);
 	}
-	assertEquals(1, testRegistry.getComponentDescriptions().size());
+	
+        assertEquals(1, testRegistry.getComponentDescriptions().size());
 	fileInfo.setForceUpdate(true);
 	adminReg.delete(fileInfo, PRINCIPAL_ADMIN);
@@ -101,5 +125,5 @@
 	assertEquals(1, testRegistry.getProfileDescriptions().size());
 	fileInfo.setForceUpdate(false);
-	fileInfo.setDataNode(new DisplayDataNode(profileDesc.getName(), false, profileDesc, ComponentStatus.PUBLISHED));
+	fileInfo.setDataNode(new DisplayDataNode(profileDesc.getName(), false, profileDesc, RegistrySpace.PUBLISHED));
 	adminReg.delete(fileInfo, PRINCIPAL_ADMIN); //Profile do not need to be forced they cannot be used by other profiles
 	assertEquals(0, testRegistry.getProfileDescriptions().size());
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java	(revision 5549)
@@ -93,5 +93,5 @@
     @Test
     public void testGetCommentsFromProfile() {
-	List<Comment> descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
+	List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
 	assertNotNull(descriptions);
 
@@ -102,5 +102,5 @@
 	commentsDao.save(comment1);
 
-	descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
+	descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
 	assertEquals(size + 1, descriptions.size());
 
@@ -110,5 +110,5 @@
 	commentsDao.save(comment2);
 
-	descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
+	descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
 	assertEquals(size + 2, descriptions.size());
     }
@@ -116,5 +116,5 @@
     @Test
     public void testGetCommentsFromComponent() {
-	List<Comment> descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
+	List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
 	assertNotNull(descriptions);
 
@@ -125,5 +125,5 @@
 	commentsDao.saveAndFlush(comment1);
 
-	descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
+	descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
 	assertEquals(size + 1, descriptions.size());
 
@@ -133,5 +133,5 @@
 	commentsDao.saveAndFlush(comment2);
 
-	descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
+	descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
 	assertEquals(size + 2, descriptions.size());
     }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java	(revision 5549)
@@ -9,4 +9,5 @@
 import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.OwnerUser;
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.UserCredentials;
 import clarin.cmdi.componentregistry.UserUnauthorizedException;
@@ -50,4 +51,13 @@
 		.getPublicRegistry();
 	assertNotNull(registry);
+        
+    }
+    
+    @Test
+    public void testGetBaseRegistry() {
+	ComponentRegistryDbImpl registry = componentRegistryFactory.getBaseRegistry(DummyPrincipal.DUMMY_CREDENTIALS);
+	assertNotNull(registry);
+        assertNotNull(registry.getRegistryOwner());
+        
     }
 
@@ -56,5 +66,5 @@
 	// Get public
 	assertNotNull(componentRegistryFactory.getComponentRegistry(
-		ComponentStatus.PUBLISHED, null, null));
+		RegistrySpace.PUBLISHED, null, null, null));
 
 	// Get for non-existing user
@@ -64,14 +74,14 @@
 
 	ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			credentials);
+		.getComponentRegistry(RegistrySpace.PRIVATE, null,
+			credentials,null);
 	assertNotNull(cr1);
 	// Get for existing user
 	ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			credentials);
+		.getComponentRegistry(RegistrySpace.PRIVATE, null,
+			credentials, null);
 	;
 	assertNotNull(cr2);
-	assertEquals(cr1.getOwner(), cr2.getOwner());
+	assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner());
 
 	// Get for another new user
@@ -79,8 +89,8 @@
 		testUser.getPrincipalName() + "2").getCredentials();
 	ComponentRegistryDbImpl cr3 = (ComponentRegistryDbImpl) componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			credentials2);
+		.getComponentRegistry(RegistrySpace.PRIVATE, null,
+			credentials2, null);
 	assertNotNull(cr3);
-	assertNotSame(cr1.getOwner(), cr3.getOwner());
+	assertNotSame(cr1.getRegistryOwner(), cr3.getRegistryOwner());
     }
 
@@ -93,23 +103,21 @@
 	// Create registry for new user
 	ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			userCredentials);
+		.getComponentRegistry(RegistrySpace.PRIVATE, null,
+			userCredentials, null);
 
-	Number id = cr1.getOwner().getId();
+	Number id = cr1.getRegistryOwner().getId();
 
 	// Get it as admin
 	ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
 		.getOtherUserComponentRegistry(
-			DummyPrincipal.DUMMY_ADMIN_PRINCIPAL,
-			ComponentStatus.PRIVATE, new OwnerUser(id));
+			DummyPrincipal.DUMMY_ADMIN_PRINCIPAL, new OwnerUser(id));
 	assertNotNull(cr2);
 	// Should be this user's registry
-	assertEquals(cr1.getOwner(), cr2.getOwner());
+	assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner());
 
 	// Try get it as non-admin
 	try {
 	    componentRegistryFactory.getOtherUserComponentRegistry(
-		    DummyPrincipal.DUMMY_PRINCIPAL, ComponentStatus.PRIVATE,
-		    new OwnerUser(id));
+		    DummyPrincipal.DUMMY_PRINCIPAL, new OwnerUser(id));
 	    fail("Non-admin can get other user's component registry");
 	} catch (Exception ex) {
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryTestDatabase.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryTestDatabase.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryTestDatabase.java	(revision 5549)
@@ -96,4 +96,5 @@
         createTableOwnership(jdbcTemplate);
         createTableGroupMembership(jdbcTemplate);
+      
     }
 }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImplTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImplTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImplTest.java	(revision 5549)
@@ -8,8 +8,8 @@
 
 import clarin.cmdi.componentregistry.BaseUnitTest;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.model.BaseDescription;
 import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.componentregistry.model.Group;
-import clarin.cmdi.componentregistry.model.GroupMembership;
 import clarin.cmdi.componentregistry.model.Ownership;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
@@ -47,4 +47,5 @@
 	profile.setId(ProfileDescription.PROFILE_PREFIX+sid);
 	profile.setName("profilename");
+        profile.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName());
 	Number id = componentDescriptionDao.insertDescription(profile, "someContent",
 		isPublic, ownerId);
@@ -58,4 +59,5 @@
 	componentDescription.setId(ComponentDescription.COMPONENT_PREFIX+"4567");
 	componentDescription.setName("componentname");
+        componentDescription.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName());
 	Number id = componentDescriptionDao.insertDescription(
 		componentDescription, "someContent", isPublic, ownerId);
@@ -255,5 +257,5 @@
 
     @Test
-    public void testTransferComponentOwnershipFromUserToGroup() {
+    public void testTransferComponentOwnershipFromUserToGroup()  throws UserUnauthorizedException{
 
 	// Make a group
@@ -307,5 +309,5 @@
 
     @Test
-    public void testtransferComponentOwnershipFromUserToGroup() {
+    public void testtransferComponentOwnershipFromUserToGroup()  throws UserUnauthorizedException{
 
 	// Make a group
@@ -360,5 +362,5 @@
 
     @Test
-    public void testTransferItemOwnershipFromUserToGroup() {
+    public void testTransferItemOwnershipFromUserToGroup()  throws UserUnauthorizedException{
 	//TODO: improve test by mixing in components and exclusing components/profiles
 	// Make a group
@@ -413,5 +415,5 @@
 
     @Test
-    public void testGetGroupsTheItemIsAMemberOf() {
+    public void testGetGroupsTheItemIsAMemberOf()  throws UserUnauthorizedException{
 	// Make a group
 	Group group1 = groupDao.findOne(groupService.createNewGroup("Group 1",
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java	(revision 5549)
@@ -3,5 +3,4 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.components.CMDComponentType;
@@ -14,5 +13,5 @@
 import clarin.cmdi.componentregistry.model.ProfileDescription;
 import clarin.cmdi.componentregistry.model.RegisterResponse;
-import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
+import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM;
 
 import com.sun.jersey.api.client.ClientResponse;
@@ -32,4 +31,5 @@
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -53,5 +53,5 @@
     @Autowired
     private JdbcTemplate jdbcTemplate;
-    private ComponentRegistry testRegistry;
+    private ComponentRegistry baseRegistry;
 
     @Before
@@ -59,10 +59,5 @@
 	ComponentRegistryTestDatabase.resetAndCreateAllTables(jdbcTemplate);
 	createUserRecord();
-	// Get public component registry
-	testRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
-    }
-
-    private ComponentRegistry getTestRegistry() {
-	return testRegistry;
+	baseRegistry = componentRegistryFactory.getBaseRegistry(DummyPrincipal.DUMMY_CREDENTIALS);
     }
 
@@ -76,39 +71,61 @@
     private ProfileDescription profile2;
     
+    private ComponentDescription component3;
+    private ProfileDescription profile3;
+    
     private Comment profile1Comment1;
     private Comment profile1Comment2;
     private Comment component1Comment3;
     private Comment component1Comment4;
-
-    private void fillUp() throws Exception {
-	profile1 = RegistryTestHelper.addProfile(getTestRegistry(), "profile2");
-	profile2 = RegistryTestHelper.addProfile(getTestRegistry(), "profile1");
-	component1 = RegistryTestHelper.addComponent(getTestRegistry(),
-		"component2");
-	component2 = RegistryTestHelper.addComponent(getTestRegistry(),
-		"component1");
-	profile1Comment2 = RegistryTestHelper.addComment(getTestRegistry(), "comment2",
+    
+    private Comment profile3Comment5;
+    private Comment component3Comment7;
+
+    private void fillUpPublicItems() throws Exception {
+        
+	profile1 = RegistryTestHelper.addProfile(baseRegistry, "profile2", true);
+	profile2 = RegistryTestHelper.addProfile(baseRegistry, "profile1", true);
+	component1 = RegistryTestHelper.addComponent(baseRegistry,
+		"component2", true);
+	component2 = RegistryTestHelper.addComponent(baseRegistry,
+		"component1", true);
+	profile1Comment2 = RegistryTestHelper.addComment(baseRegistry, "comment2",
 		ProfileDescription.PROFILE_PREFIX + "profile1",
 		"JUnit@test.com");
-	profile1Comment1 = RegistryTestHelper.addComment(getTestRegistry(), "comment1",
+	profile1Comment1 = RegistryTestHelper.addComment(baseRegistry, "comment1",
 		ProfileDescription.PROFILE_PREFIX + "profile1",
 		"JUnit@test.com");
-	component1Comment3 = RegistryTestHelper.addComment(getTestRegistry(), "comment3",
+	component1Comment3 = RegistryTestHelper.addComment(baseRegistry, "comment3",
 		ComponentDescription.COMPONENT_PREFIX + "component1",
 		"JUnit@test.com");
-	component1Comment4 = RegistryTestHelper.addComment(getTestRegistry(), "comment4",
+	component1Comment4 = RegistryTestHelper.addComment(baseRegistry, "comment4",
 		ComponentDescription.COMPONENT_PREFIX + "component1",
 		"JUnit@test.com");
     }
-
-    @Test
-    public void testGetRegisteredProfiles() throws Exception {
-	fillUp();
-	RegistryTestHelper.addProfile(getTestRegistry(), "PROFILE2");
-	List<ProfileDescription> response = getResource()
-		.path("/registry/profiles").accept(MediaType.APPLICATION_XML)
+    
+    private void fillUpPrivateItems() throws Exception {
+	profile3 = RegistryTestHelper.addProfile(baseRegistry, "profile3", false);
+	component3 = RegistryTestHelper.addComponent(baseRegistry,
+		"component3", false);
+	profile3Comment5 = RegistryTestHelper.addComment(baseRegistry, "comment5",
+		ProfileDescription.PROFILE_PREFIX + "profile3",
+		"JUnit@test.com");
+	component3Comment7 = RegistryTestHelper.addComment(baseRegistry, "comment7",
+		ComponentDescription.COMPONENT_PREFIX + "component3",
+		"JUnit@test.com");
+    }
+
+    @Test//ok
+    public void testGetPublicProfiles() throws Exception {
+        
+        fillUpPublicItems();
+        
+	RegistryTestHelper.addProfile(baseRegistry, "PROFILE2", true);
+	List<ProfileDescription> response = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles")).accept(MediaType.APPLICATION_XML)
 		.get(PROFILE_LIST_GENERICTYPE);
 	assertEquals(3, response.size());
-	response = getResource().path("/registry/profiles")
+	response = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles"))
 		.accept(MediaType.APPLICATION_JSON)
 		.get(PROFILE_LIST_GENERICTYPE);
@@ -119,13 +136,16 @@
     }
 
-    @Test
-    public void testGetRegisteredComponents() throws Exception {
-	fillUp();
-	RegistryTestHelper.addComponent(getTestRegistry(), "COMPONENT2");
-	List<ComponentDescription> response = getResource()
-		.path("/registry/components").accept(MediaType.APPLICATION_XML)
+    @Test //ok
+    public void testGetPublicComponents() throws Exception {
+        
+        fillUpPublicItems();
+        
+        RegistryTestHelper.addComponent(baseRegistry, "COMPONENT2", true);
+	List<ComponentDescription> response = this.getAuthenticatedResource(getResource()
+		.path("/registry/components")).accept(MediaType.APPLICATION_XML)
 		.get(COMPONENT_LIST_GENERICTYPE);
 	assertEquals(3, response.size());
-	response = getResource().path("/registry/components")
+	response = this.getAuthenticatedResource(getResource()
+		.path("/registry/components"))
 		.accept(MediaType.APPLICATION_JSON)
 		.get(COMPONENT_LIST_GENERICTYPE);
@@ -136,15 +156,21 @@
     }
 
-    @Test
+    @Test  //ok
     public void testGetUserComponents() throws Exception {
-	fillUp();
-	List<ComponentDescription> response = getUserComponents();
-	assertEquals(0, response.size());
-	response = getAuthenticatedResource(
-		getResource().path("/registry/components")).accept(
+        
+        fillUpPrivateItems();
+        
+       	List<ComponentDescription> response = this.getUserComponents();
+	assertEquals(1, response.size());
+        
+        ////
+        
+        fillUpPublicItems();
+	response = getAuthenticatedResource(getResource().path("/registry/components")).accept(
 		MediaType.APPLICATION_JSON).get(COMPONENT_LIST_GENERICTYPE);
 	assertEquals("Get public components", 2, response.size());
+        
 	ClientResponse cResponse = getResource().path("/registry/components")
-		.queryParam(USERSPACE_PARAM, "true")
+		.queryParam(REGISTRY_SPACE_PARAM, "private")
 		.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
 	assertEquals("Trying to get userspace without credentials", 401,
@@ -152,19 +178,22 @@
     }
 
-    @Test
-    public void testGetRegisteredComponent() throws Exception {
-	fillUp();
-	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
+    @Test //ok
+    public void testGetPublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
+        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
 	String id2 = ComponentDescription.COMPONENT_PREFIX + "component2";
-	CMDComponentSpec component = getResource()
-		.path("/registry/components/" + id)
+	CMDComponentSpec component = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id))
 		.accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class);
 	assertNotNull(component);
 	assertEquals("Access", component.getCMDComponent().getName());
-	component = getResource().path("/registry/components/" + id2)
+        
+        
+	component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id2))
 		.accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
 	assertNotNull(component);
 	assertEquals("Access", component.getCMDComponent().getName());
-
 	assertEquals(id2, component.getHeader().getID());
 	assertEquals("component2", component.getHeader().getName());
@@ -172,16 +201,19 @@
     }
 
-    @Test
-    public void testGetRegisteredCommentsInProfile() throws Exception {
-	fillUp();
+    @Test   // ok    
+    public void testGetCommentsInPublicProfile() throws Exception {
+        
+        fillUpPublicItems();
+        
 	String id = ProfileDescription.PROFILE_PREFIX + "profile1";
-	RegistryTestHelper.addComment(getTestRegistry(), "COMMENT1", id,
+	RegistryTestHelper.addComment(baseRegistry, "COMMENT1", id,
 		"JUnit@test.com");
-	List<Comment> response = getResource()
-		.path("/registry/profiles/" + id + "/comments/")
+	List<Comment> response = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + id + "/comments/"))
 		.accept(MediaType.APPLICATION_XML)
 		.get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(3, response.size());
-	response = getResource().path("/registry/profiles/" + id + "/comments")
+        
+	response = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id + "/comments"))
 		.accept(MediaType.APPLICATION_JSON)
 		.get(COMMENT_LIST_GENERICTYPE);
@@ -194,17 +226,18 @@
     }
 
-    @Test
-    public void testGetRegisteredCommentsInComponent() throws Exception {
-	fillUp();
+    @Test // ok
+    public void testGetCommentsInPubliComponent() throws Exception {
+        fillUpPublicItems();
+        
 	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
-	RegistryTestHelper.addComment(getTestRegistry(), "COMMENT2", id,
+	RegistryTestHelper.addComment(baseRegistry, "COMMENT2", id,
 		"JUnit@test.com");
-	List<Comment> response = getResource()
-		.path("/registry/components/" + id + "/comments/")
+	List<Comment> response = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id + "/comments/"))
 		.accept(MediaType.APPLICATION_XML)
 		.get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(3, response.size());
-	response = getResource()
-		.path("/registry/components/" + id + "/comments")
+	response = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id + "/comments"))
 		.accept(MediaType.APPLICATION_JSON)
 		.get(COMMENT_LIST_GENERICTYPE);
@@ -217,16 +250,18 @@
     }
 
-    @Test
-    public void testGetSpecifiedCommentInComponent() throws Exception {
-	fillUp();
+    @Test // ok
+    public void testGetSpecifiedCommentInPublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
 	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
-	Comment comment = getResource()
-		.path("/registry/components/" + id + "/comments/"+component1Comment3.getId())
+	Comment comment = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id + "/comments/"+component1Comment3.getId()))
 		.accept(MediaType.APPLICATION_JSON).get(Comment.class);
 	assertNotNull(comment);
 	assertEquals("comment3", comment.getComment());
 	assertEquals(component1Comment3.getId(), comment.getId());
-	comment = getResource()
-		.path("/registry/components/" + id + "/comments/"+component1Comment4.getId())
+	comment = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id + "/comments/"+component1Comment4.getId()))
 		.accept(MediaType.APPLICATION_JSON).get(Comment.class);
 	assertNotNull(comment);
@@ -236,17 +271,20 @@
     }
 
-    @Test
-    public void testGetSpecifiedCommentInProfile() throws Exception {
-	fillUp();
+    @Test //ok
+    public void testGetSpecifiedCommentInPublicProfile() throws Exception {
+        
+        fillUpPublicItems();
+        
 	String id = ProfileDescription.PROFILE_PREFIX + "profile1";
-	Comment comment = getResource()
-		.path("/registry/profiles/" + id + "/comments/"+profile1Comment2.getId())
+	Comment comment = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + id + "/comments/"+profile1Comment2.getId()))
 		.accept(MediaType.APPLICATION_JSON).get(Comment.class);
 	assertNotNull(comment);
 	assertEquals("comment2", comment.getComment());
 	assertEquals(profile1Comment2.getId(), comment.getId());
-	comment = getResource()
-		.path("/registry/profiles/" + id + "/comments/"+profile1Comment1.getId())
-		.accept(MediaType.APPLICATION_JSON).get(Comment.class);
+        
+	comment = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + id + "/comments/"+profile1Comment1.getId()))
+                .accept(MediaType.APPLICATION_JSON).get(Comment.class);
 	assertNotNull(comment);
 	assertEquals("comment1", comment.getComment());
@@ -255,15 +293,17 @@
     }
 
-    @Test
-    public void testDeleteCommentFromComponent() throws Exception {
-	fillUp();
+    @Test  //ok
+    public void testDeleteCommentFromPublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
 	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
 	String id2 = ComponentDescription.COMPONENT_PREFIX + "component2";
-	List<Comment> comments = getResource().path(
-		"/registry/components/" + id + "/comments").get(
+	List<Comment> comments = this.getAuthenticatedResource(getResource().path(
+		"/registry/components/" + id + "/comments")).get(
 		COMMENT_LIST_GENERICTYPE);
 	assertEquals(2, comments.size());
-	Comment aComment = getResource().path(
-		"/registry/components/" + id + "/comments/"+component1Comment3.getId())
+	Comment aComment = this.getAuthenticatedResource(getResource().path(
+		"/registry/components/" + id + "/comments/"+component1Comment3.getId()))
 		.get(Comment.class);
 	assertNotNull(aComment);
@@ -280,6 +320,6 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
-		"/registry/components/" + id + "/comments/").get(
+	comments = this.getAuthenticatedResource(getResource().path(
+		"/registry/components/" + id + "/comments/")).get(
 		COMMENT_LIST_GENERICTYPE);
 	assertEquals(1, comments.size());
@@ -290,6 +330,6 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
-		"/registry/components/" + id + "/comments").get(
+	comments = this.getAuthenticatedResource(getResource().path(
+		"/registry/components/" + id + "/comments")).get(
 		COMMENT_LIST_GENERICTYPE);
 	assertEquals(0, comments.size());
@@ -297,13 +337,15 @@
 
     @Test
-    public void testManipulateCommentFromComponent() throws Exception {
-	fillUp();
-	List<Comment> comments = getResource().path(
+    public void testManipulateCommentFromPublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
+	List<Comment> comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/components/" + ComponentDescription.COMPONENT_PREFIX
-			+ "component1/comments").get(COMMENT_LIST_GENERICTYPE);
+			+ "component1/comments")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(2, comments.size());
-	Comment aComment = getResource().path(
+	Comment aComment = this.getAuthenticatedResource(getResource().path(
 		"/registry/components/" + ComponentDescription.COMPONENT_PREFIX
-			+ "component1/comments/"+component1Comment3.getId()).get(Comment.class);
+			+ "component1/comments/"+component1Comment3.getId())).get(Comment.class);
 	assertNotNull(aComment);
 
@@ -318,20 +360,22 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
+	comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/components/" + ComponentDescription.COMPONENT_PREFIX
-			+ "component1/comments/").get(COMMENT_LIST_GENERICTYPE);
+			+ "component1/comments/")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(1, comments.size());
     }
 
     @Test
-    public void testDeleteCommentFromProfile() throws Exception {
-	fillUp();
-	List<Comment> comments = getResource().path(
+    public void testDeleteCommentFromPublicProfile() throws Exception {
+        
+        fillUpPublicItems();
+        
+	List<Comment> comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
+			+ "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(2, comments.size());
-	Comment aComment = getResource().path(
+	Comment aComment = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments/"+profile1Comment1.getId()).get(Comment.class);
+			+ "profile1/comments/"+profile1Comment1.getId())).get(Comment.class);
 	assertNotNull(aComment);
 
@@ -347,7 +391,7 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
+	comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments/").get(COMMENT_LIST_GENERICTYPE);
+			+ "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(1, comments.size());
 
@@ -357,20 +401,22 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
+	comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
+			+ "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(0, comments.size());
     }
 
     @Test
-    public void testManipulateCommentFromProfile() throws Exception {
-	fillUp();
-	List<Comment> comments = getResource().path(
+    public void testManipulateCommentFromPublicProfile() throws Exception {
+        
+        fillUpPublicItems();
+        
+	List<Comment> comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
+			+ "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(2, comments.size());
-	Comment aComment = getResource().path(
+	Comment aComment = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments/"+profile1Comment2.getId()).get(Comment.class);
+			+ "profile1/comments/"+profile1Comment2.getId())).get(Comment.class);
 	assertNotNull(aComment);
 
@@ -384,19 +430,21 @@
 	assertEquals(200, response.getStatus());
 
-	comments = getResource().path(
+	comments = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/comments/").get(COMMENT_LIST_GENERICTYPE);
+			+ "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE);
 	assertEquals(1, comments.size());
     }
 
     @Test
-    public void testDeleteRegisteredComponent() throws Exception {
-	fillUp();
-	List<ComponentDescription> components = getResource().path(
-		"/registry/components").get(COMPONENT_LIST_GENERICTYPE);
+    public void testDeletePublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
+	List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
+		"/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
 	assertEquals(2, components.size());
-	CMDComponentSpec profile = getResource().path(
+	CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
 		"/registry/components/" + ComponentDescription.COMPONENT_PREFIX
-			+ "component1").get(CMDComponentSpec.class);
+			+ "component1")).get(CMDComponentSpec.class);
 	assertNotNull(profile);
 	ClientResponse response = getAuthenticatedResource(
@@ -405,5 +453,5 @@
 	assertEquals(200, response.getStatus());
 
-	components = getResource().path("/registry/components").get(
+	components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
 		COMPONENT_LIST_GENERICTYPE);
 	assertEquals(1, components.size());
@@ -414,5 +462,5 @@
 	assertEquals(200, response.getStatus());
 
-	components = getResource().path("/registry/components").get(
+	components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
 		COMPONENT_LIST_GENERICTYPE);
 	assertEquals(0, components.size());
@@ -425,6 +473,9 @@
 
     @Test
-    public void testDeleteRegisteredComponentStillUsed() throws Exception {
-	String content = "";
+    public void testDeletePublicComponentStillUsed() throws Exception {
+        
+        fillUpPublicItems();
+        
+        String content = "";
 	content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
 	content += "    xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n";
@@ -435,5 +486,5 @@
 	content += "</CMD_ComponentSpec>\n";
 	ComponentDescription compDesc1 = RegistryTestHelper.addComponent(
-		getTestRegistry(), "XXX1", content);
+		baseRegistry, "XXX1", content, true);
 
 	content = "";
@@ -448,5 +499,5 @@
 	content += "</CMD_ComponentSpec>\n";
 	ComponentDescription compDesc2 = RegistryTestHelper.addComponent(
-		getTestRegistry(), "YYY1", content);
+		baseRegistry, "YYY1", content,true);
 
 	content = "";
@@ -461,9 +512,9 @@
 	content += "</CMD_ComponentSpec>\n";
 	ProfileDescription profile = RegistryTestHelper.addProfile(
-		getTestRegistry(), "TestProfile3", content);
-
-	List<ComponentDescription> components = getResource().path(
-		"/registry/components").get(COMPONENT_LIST_GENERICTYPE);
-	assertEquals(2, components.size());
+		baseRegistry, "TestProfile3", content, true);
+
+	List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
+		"/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
+	assertEquals(4, components.size());
 
 	ClientResponse response = getAuthenticatedResource(
@@ -475,7 +526,7 @@
 		response.getEntity(String.class));
 
-	components = getResource().path("/registry/components").get(
+	components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
 		COMPONENT_LIST_GENERICTYPE);
-	assertEquals(2, components.size());
+	assertEquals(4, components.size());
 
 	response = getAuthenticatedResource(
@@ -491,18 +542,20 @@
 		ClientResponse.class);
 	assertEquals(200, response.getStatus());
-	components = getResource().path("/registry/components").get(
+	components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
 		COMPONENT_LIST_GENERICTYPE);
-	assertEquals(0, components.size());
-    }
-
-    @Test
-    public void testManipulateRegisteredComponent() throws Exception {
-	fillUp();
-	List<ComponentDescription> components = getResource().path(
-		"/registry/components").get(COMPONENT_LIST_GENERICTYPE);
 	assertEquals(2, components.size());
-	CMDComponentSpec profile = getResource().path(
+    }
+
+    @Test
+    public void testManipulatePublicComponent() throws Exception {
+        
+        fillUpPublicItems();
+        
+	List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
+		"/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
+	assertEquals(2, components.size());
+	CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
 		"/registry/components/" + ComponentDescription.COMPONENT_PREFIX
-			+ "component1").get(CMDComponentSpec.class);
+			+ "component1")).get(CMDComponentSpec.class);
 	assertNotNull(profile);
 
@@ -516,5 +569,5 @@
 	assertEquals(200, response.getStatus());
 
-	components = getResource().path("/registry/components").get(
+	components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
 		COMPONENT_LIST_GENERICTYPE);
 	assertEquals(1, components.size());
@@ -529,13 +582,15 @@
     @Test
     public void testGetRegisteredProfile() throws Exception {
-	fillUp();
+        
+        fillUpPublicItems();
+        
 	String id = ProfileDescription.PROFILE_PREFIX + "profile1";
 	String id2 = ProfileDescription.PROFILE_PREFIX + "profile2";
-	CMDComponentSpec profile = getResource()
-		.path("/registry/profiles/" + id)
+	CMDComponentSpec profile = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + id))
 		.accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class);
 	assertNotNull(profile);
 	assertEquals("Actor", profile.getCMDComponent().getName());
-	profile = getResource().path("/registry/profiles/" + id2)
+	profile = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id2))
 		.accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
 	assertNotNull(profile);
@@ -547,7 +602,7 @@
 
 	try {
-	    profile = getResource()
+	    profile = this.getAuthenticatedResource(getResource()
 		    .path("/registry/profiles/"
-			    + ProfileDescription.PROFILE_PREFIX + "profileXXXX")
+			    + ProfileDescription.PROFILE_PREFIX + "profileXXXX"))
 		    .accept(MediaType.APPLICATION_XML)
 		    .get(CMDComponentSpec.class);
@@ -560,8 +615,10 @@
     @Test
     public void testGetRegisteredProfileRawData() throws Exception {
-	fillUp();
-	String profile = getResource()
+        
+        fillUpPublicItems();
+        
+	String profile = this.getAuthenticatedResource(getResource()
 		.path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/xsd").accept(MediaType.TEXT_XML)
+			+ "profile1/xsd")).accept(MediaType.TEXT_XML)
 		.get(String.class).trim();
 	assertTrue(profile
@@ -569,7 +626,7 @@
 	assertTrue(profile.endsWith("</xs:schema>"));
 
-	profile = getResource()
+	profile = this.getAuthenticatedResource(getResource()
 		.path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1/xml").accept(MediaType.TEXT_XML)
+			+ "profile1/xml")).accept(MediaType.TEXT_XML)
 		.get(String.class).trim();
 	assertTrue(profile
@@ -579,8 +636,8 @@
 
 	try {
-	    getResource()
+	    this.getAuthenticatedResource(getResource()
 		    .path("/registry/components/"
 			    + ComponentDescription.COMPONENT_PREFIX
-			    + "component1/xsl").accept(MediaType.TEXT_XML)
+			    + "component1/xsl")).accept(MediaType.TEXT_XML)
 		    .get(String.class);
 	    fail("Should have thrown exception, unsupported path parameter");
@@ -589,11 +646,14 @@
     }
 
+    // 
     @Test
     public void testPrivateProfileXsd() throws Exception {
+        
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getTestProfileContent());
-	RegisterResponse response = getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles").queryParam(
+			REGISTRY_SPACE_PARAM, "private")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -601,6 +661,6 @@
 	assertEquals(1, getUserProfiles().size());
 	BaseDescription desc = response.getDescription();
-	String profile = getResource()
-		.path("/registry/profiles/" + desc.getId() + "/xsd")
+	String profile = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + desc.getId() + "/xsd"))
 		.accept(MediaType.TEXT_XML).get(String.class).trim();
 	assertTrue(profile
@@ -611,9 +671,12 @@
     @Test
     public void testPrivateComponentXsd() throws Exception {
+        
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getComponentTestContent());
 	RegisterResponse response = getAuthenticatedResource(
 		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
+			REGISTRY_SPACE_PARAM, "private")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -621,6 +684,6 @@
 	assertEquals(1, getUserComponents().size());
 	BaseDescription desc = response.getDescription();
-	String profile = getResource()
-		.path("/registry/components/" + desc.getId() + "/xsd")
+	String profile = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + desc.getId() + "/xsd"))
 		.accept(MediaType.TEXT_XML).get(String.class).trim();
 	assertTrue(profile
@@ -631,11 +694,13 @@
     @Test
     public void testDeleteRegisteredProfile() throws Exception {
-	fillUp();
-	List<ProfileDescription> profiles = getResource().path(
-		"/registry/profiles").get(PROFILE_LIST_GENERICTYPE);
+        
+        fillUpPublicItems();
+        
+	List<ProfileDescription> profiles = this.getAuthenticatedResource(getResource().path(
+		"/registry/profiles")).get(PROFILE_LIST_GENERICTYPE);
 	assertEquals(2, profiles.size());
-	CMDComponentSpec profile = getResource().path(
+	CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1").get(CMDComponentSpec.class);
+			+ "profile1")).get(CMDComponentSpec.class);
 	assertNotNull(profile);
 
@@ -645,5 +710,5 @@
 	assertEquals(200, response.getStatus());
 
-	profiles = getResource().path("/registry/profiles").get(
+	profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
 		PROFILE_LIST_GENERICTYPE);
 	assertEquals(1, profiles.size());
@@ -654,5 +719,5 @@
 	assertEquals(200, response.getStatus());
 
-	profiles = getResource().path("/registry/profiles").get(
+	profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
 		PROFILE_LIST_GENERICTYPE);
 	assertEquals(0, profiles.size());
@@ -661,16 +726,18 @@
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
 			+ "profile1").delete(ClientResponse.class);
-	assertEquals(200, response.getStatus());
+	assertEquals(404, response.getStatus());
     }
 
     @Test
     public void testManipulateRegisteredProfile() throws Exception {
-	fillUp();
-	List<ProfileDescription> profiles = getResource().path(
-		"/registry/profiles").get(PROFILE_LIST_GENERICTYPE);
+        
+        fillUpPublicItems();
+        
+	List<ProfileDescription> profiles = this.getAuthenticatedResource(getResource().path(
+		"/registry/profiles")).get(PROFILE_LIST_GENERICTYPE);
 	assertEquals(2, profiles.size());
-	CMDComponentSpec profile = getResource().path(
+	CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
 		"/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
-			+ "profile1").get(CMDComponentSpec.class);
+			+ "profile1")).get(CMDComponentSpec.class);
 	assertNotNull(profile);
 
@@ -684,5 +751,5 @@
 	assertEquals(200, response.getStatus());
 
-	profiles = getResource().path("/registry/profiles").get(
+	profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
 		PROFILE_LIST_GENERICTYPE);
 	assertEquals(1, profiles.size());
@@ -697,8 +764,10 @@
     @Test
     public void testGetRegisteredComponentRawData() throws Exception {
-	fillUp();
+        
+        fillUpPublicItems();
+        
 	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
-	String component = getResource()
-		.path("/registry/components/" + id + "/xsd")
+	String component = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + id + "/xsd"))
 		.accept(MediaType.TEXT_XML).get(String.class).trim();
 	assertTrue(component
@@ -706,5 +775,5 @@
 	assertTrue(component.endsWith("</xs:schema>"));
 
-	component = getResource().path("/registry/components/" + id + "/xml")
+	component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id + "/xml"))
 		.accept(MediaType.TEXT_XML).get(String.class).trim();
 	assertTrue(component
@@ -714,8 +783,8 @@
 
 	try {
-	    getResource()
+	    this.getAuthenticatedResource(getResource()
 		    .path("/registry/components/"
 			    + ComponentDescription.COMPONENT_PREFIX
-			    + "component1/jpg").accept(MediaType.TEXT_XML)
+			    + "component1/jpg")).accept(MediaType.TEXT_XML)
 		    .get(String.class);
 	    fail("Should have thrown exception, unsopported path parameter");
@@ -726,4 +795,7 @@
     @Test
     public void testRegisterProfile() throws Exception {
+        
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
@@ -742,5 +814,5 @@
 		RegisterResponse.class, form);
 	assertTrue(response.isProfile());
-	assertFalse(response.isInUserSpace());
+	assertTrue(response.isInUserSpace());
 	ProfileDescription profileDesc = (ProfileDescription) response
 		.getDescription();
@@ -762,12 +834,14 @@
     @Test
     public void testPublishProfile() throws Exception {
-	assertEquals("user registered profiles", 0, getUserProfiles().size());
-	assertEquals("public registered profiles", 0, getPublicProfiles()
+        
+        fillUpPrivateItems();
+        fillUpPublicItems();
+        
+	assertEquals("user registered profiles", 1, getUserProfiles().size());
+	assertEquals("public registered profiles", 2, getPublicProfiles()
 		.size());
 	FormDataMultiPart form = createFormData(
 		RegistryTestHelper.getTestProfileContent(), "Unpublished");
-	RegisterResponse response = getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -775,19 +849,18 @@
 	BaseDescription desc = response.getDescription();
 	assertEquals("Unpublished", desc.getDescription());
-	assertEquals(1, getUserProfiles().size());
-	assertEquals(0, getPublicProfiles().size());
+	assertEquals(2, getUserProfiles().size());
+	assertEquals(2, getPublicProfiles().size());
 	form = createFormData(
 		RegistryTestHelper.getTestProfileContent("publishedName"),
 		"Published");
-	response = getAuthenticatedResource(
-		getResource().path(
+	response = getAuthenticatedResource(getResource().path(
 			"/registry/profiles/" + desc.getId() + "/publish"))
 		.type(MediaType.MULTIPART_FORM_DATA).post(
 			RegisterResponse.class, form);
 
-	assertEquals(0, getUserProfiles().size());
+	assertEquals(1, getUserProfiles().size());
 	List<ProfileDescription> profiles = getPublicProfiles();
-	assertEquals(1, profiles.size());
-	ProfileDescription profileDescription = profiles.get(0);
+	assertEquals(3, profiles.size());
+	ProfileDescription profileDescription = profiles.get(2);
 	assertNotNull(profileDescription.getId());
 	assertEquals(desc.getId(), profileDescription.getId());
@@ -801,8 +874,8 @@
     private CMDComponentSpec getPublicSpec(BaseDescription desc) {
 	if (desc.isProfile()) {
-	    return getResource().path("/registry/profiles/" + desc.getId())
+	    return this.getAuthenticatedResource(getResource().path("/registry/profiles/" + desc.getId()))
 		    .get(CMDComponentSpec.class);
 	} else {
-	    return getResource().path("/registry/components/" + desc.getId())
+	    return this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId()))
 		    .get(CMDComponentSpec.class);
 	}
@@ -810,12 +883,15 @@
 
     @Test
-    public void testPublishComponent() throws Exception {
-	assertEquals(0, getUserComponents().size());
-	assertEquals(0, getPublicComponents().size());
+    public void testPublishRegisteredComponent() throws Exception {
+        
+        fillUpPrivateItems();
+        fillUpPublicItems();
+        
+	assertEquals(1, getUserComponents().size());
+	assertEquals(2, getPublicComponents().size());
+        
 	FormDataMultiPart form = createFormData(
 		RegistryTestHelper.getComponentTestContent(), "Unpublished");
-	RegisterResponse response = getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/components")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -823,19 +899,18 @@
 	BaseDescription desc = response.getDescription();
 	assertEquals("Unpublished", desc.getDescription());
-	assertEquals(1, getUserComponents().size());
-	assertEquals(0, getPublicComponents().size());
+	assertEquals(2, getUserComponents().size());
+	assertEquals(2, getPublicComponents().size());
 	form = createFormData(
 		RegistryTestHelper.getComponentTestContentAsStream("publishedName"),
 		"Published");
-	response = getAuthenticatedResource(
-		getResource().path(
+	response = getAuthenticatedResource(getResource().path(
 			"/registry/components/" + desc.getId() + "/publish"))
 		.type(MediaType.MULTIPART_FORM_DATA).post(
 			RegisterResponse.class, form);
 
-	assertEquals(0, getUserComponents().size());
+	assertEquals(1, getUserComponents().size());
 	List<ComponentDescription> components = getPublicComponents();
-	assertEquals(1, components.size());
-	ComponentDescription componentDescription = components.get(0);
+	assertEquals(3, components.size());
+	ComponentDescription componentDescription = components.get(2);
 	assertNotNull(componentDescription.getId());
 	assertEquals(desc.getId(), componentDescription.getId());
@@ -848,15 +923,18 @@
     }
 
+    // duplicates ("extendedly") testRegisterProfile, since you can pot only in user space, and then publish or move to group or so
     @Test
     public void testRegisterUserspaceProfile() throws Exception {
+        
+        fillUpPrivateItems();
+        fillUpPublicItems();
+        
 	List<ProfileDescription> profiles = getUserProfiles();
-	assertEquals("user registered profiles", 0, profiles.size());
-	assertEquals("public registered profiles", 0, getPublicProfiles()
+	assertEquals("user registered profiles", 1, profiles.size());
+	assertEquals("public registered profiles", 2, getPublicProfiles()
 		.size());
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getTestProfileContent());
-	RegisterResponse response = getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -875,32 +953,26 @@
 	assertEquals(
 		"http://localhost:9998/registry/profiles/"
-			+ profileDesc.getId() + "?userspace=true",
+			+ profileDesc.getId(),
 		profileDesc.getHref());
 
 	profiles = getUserProfiles();
-	assertEquals(1, profiles.size());
-	assertEquals(0, getPublicProfiles().size());
+	assertEquals(2, profiles.size());
+	assertEquals(2, getPublicProfiles().size());
 
 	// Try to post unauthenticated
 	ClientResponse cResponse = getResource().path("/registry/profiles")
-		.queryParam(USERSPACE_PARAM, "true")
 		.type(MediaType.MULTIPART_FORM_DATA)
 		.post(ClientResponse.class, form);
 	assertEquals(401, cResponse.getStatus());
 
-	// Try get from public registry
-	cResponse = getResource()
-		.path("/registry/profiles/" + profileDesc.getId())
-		.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
-	// Should return 404 = not found
-	assertEquals(404, cResponse.getStatus());
-	CMDComponentSpec spec = getAuthenticatedResource(
-		getResource().path("/registry/profiles/" + profileDesc.getId())
-			.queryParam(USERSPACE_PARAM, "true")).accept(
+	
+	
+	CMDComponentSpec spec = getAuthenticatedResource(getResource().path("/registry/profiles/" + profileDesc.getId())
+			.queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
 		MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
 	assertNotNull(spec);
 
-	cResponse = getResource()
-		.path("/registry/profiles/" + profileDesc.getId() + "/xsd")
+	cResponse = this.getAuthenticatedResource(getResource()
+		.path("/registry/profiles/" + profileDesc.getId() + "/xsd"))
 		.accept(MediaType.TEXT_XML).get(ClientResponse.class);
 	assertEquals(200, cResponse.getStatus());
@@ -908,18 +980,16 @@
 	assertTrue(profile.length() > 0);
 
-	profile = getAuthenticatedResource(
-		getResource().path(
+	profile = getAuthenticatedResource(getResource().path(
 			"/registry/profiles/" + profileDesc.getId() + "/xml"))
 		.accept(MediaType.TEXT_XML).get(String.class);
 	assertTrue(profile.length() > 0);
 
-	cResponse = getAuthenticatedResource(
-		getResource().path("/registry/profiles/" + profileDesc.getId())
-			.queryParam(USERSPACE_PARAM, "true")).delete(
+	cResponse = getAuthenticatedResource(getResource().path("/registry/profiles/" + profileDesc.getId())
+			.queryParam(REGISTRY_SPACE_PARAM, "private")).delete(
 		ClientResponse.class);
 	assertEquals(200, cResponse.getStatus());
 
 	profiles = getUserProfiles();
-	assertEquals(0, profiles.size());
+	assertEquals(1, profiles.size());
     }
 
@@ -930,7 +1000,6 @@
 
     private List<ProfileDescription> getUserProfiles() {
-	return getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).accept(
+	return getAuthenticatedResource(getResource().path("/registry/profiles").queryParam(
+			REGISTRY_SPACE_PARAM, "private")).accept(
 		MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE);
     }
@@ -954,7 +1023,7 @@
     @Test
     public void testRegisterWithUserComponents() throws Exception {
-	ComponentRegistry userRegistry = componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			DummyPrincipal.DUMMY_CREDENTIALS);
+        fillUpPrivateItems();
+        
+        // kid component, not public
 	String content = "";
 	content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
@@ -966,6 +1035,7 @@
 	content += "</CMD_ComponentSpec>\n";
 	ComponentDescription compDesc1 = RegistryTestHelper.addComponent(
-		userRegistry, "XXX1", content);
-
+		baseRegistry, "XXX1", content, false);
+
+        // a containing component, referring to the kid (which is not public, so the containing component cannot be registered
 	content = "";
 	content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
@@ -982,20 +1052,9 @@
 		"/registry/components").type(MediaType.MULTIPART_FORM_DATA)
 		.post(RegisterResponse.class, form);
-	assertFalse(response.isRegistered());
-	assertEquals(1, response.getErrors().size());
-	assertEquals(
-		"referenced component cannot be found in the published components: "
-			+ compDesc1.getName() + " (" + compDesc1.getId() + ")",
-		response.getErrors().get(0));
-
-	response = getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
-		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
-		form);
+        // we first alway register in a private space, so reference to a private component should work
 	assertTrue(response.isRegistered());
-	ComponentDescription comp2 = (ComponentDescription) response
-		.getDescription();
-
+
+
+        /// profiles ///
 	content = "";
 	content += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
@@ -1003,5 +1062,5 @@
 	content += "    <Header/>\n";
 	content += "    <CMD_Component name=\"ZZZ\" CardinalityMin=\"1\" CardinalityMax=\"unbounded\">\n";
-	content += "        <CMD_Component ComponentId=\"" + comp2.getId()
+	content += "        <CMD_Component ComponentId=\"" + compDesc1.getId()
 		+ "\" CardinalityMin=\"0\" CardinalityMax=\"99\">\n";
 	content += "        </CMD_Component>\n";
@@ -1013,23 +1072,15 @@
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
-	assertFalse(response.isRegistered());
-	assertEquals(1, response.getErrors().size());
-	assertEquals(
-		"referenced component cannot be found in the published components: "
-			+ comp2.getName() + " (" + comp2.getId() + ")",
-		response.getErrors().get(0));
-
-	response = getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).type(
-		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
-		form);
 	assertTrue(response.isRegistered());
+
     }
 
     @Test
     public void testRegisterUserspaceComponent() throws Exception {
+        
+        fillUpPrivateItems();
+        
 	List<ComponentDescription> components = getUserComponents();
-	assertEquals("user registered components", 0, components.size());
+	assertEquals("user registered components", 1, components.size());
 	assertEquals("public registered components", 0, getPublicComponents()
 		.size());
@@ -1037,7 +1088,5 @@
 		.getComponentTestContent());
 
-	RegisterResponse response = getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/components")).type(
 		MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
 		form);
@@ -1057,28 +1106,26 @@
 	assertNotNull(desc.getRegistrationDate());
 	String url = getResource().getUriBuilder().build().toString();
-	assertEquals(url + "registry/components/" + desc.getId()
-		+ "?userspace=true", desc.getHref());
+	assertEquals(url + "registry/components/" + desc.getId(), desc.getHref());
 
 	components = getUserComponents();
-	assertEquals(1, components.size());
+	assertEquals(2, components.size());
 	assertEquals(0, getPublicComponents().size());
 
 	// Try to post unauthenticated
 	ClientResponse cResponse = getResource().path("/registry/components")
-		.queryParam(USERSPACE_PARAM, "true")
 		.type(MediaType.MULTIPART_FORM_DATA)
 		.post(ClientResponse.class, form);
 	assertEquals(401, cResponse.getStatus());
 
-	// Try to get from public registry
-	cResponse = getResource().path("/registry/components/" + desc.getId())
+	// Try to get 
+	cResponse = this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId()))
 		.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
-	// Should return 404 = not found
-	assertEquals(404, cResponse.getStatus());
+	
+	assertEquals(200, cResponse.getStatus());
 	CMDComponentSpec spec = getUserComponent(desc);
 	assertNotNull(spec);
 
-	cResponse = getResource()
-		.path("/registry/components/" + desc.getId() + "/xsd")
+	cResponse = this.getAuthenticatedResource(getResource()
+		.path("/registry/components/" + desc.getId() + "/xsd"))
 		.accept(MediaType.TEXT_XML).get(ClientResponse.class);
 	assertEquals(200, cResponse.getStatus());
@@ -1086,28 +1133,25 @@
 	assertTrue(result.length() > 0);
 
-	result = getAuthenticatedResource(
-		getResource().path(
+	result = getAuthenticatedResource(getResource().path(
 			"/registry/components/" + desc.getId() + "/xml"))
 		.accept(MediaType.TEXT_XML).get(String.class);
 	assertTrue(result.length() > 0);
 
-	cResponse = getAuthenticatedResource(
-		getResource().path("/registry/components/" + desc.getId())
-			.queryParam(USERSPACE_PARAM, "true")).delete(
+	cResponse = getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())).delete(
 		ClientResponse.class);
 	assertEquals(200, cResponse.getStatus());
 
 	components = getUserComponents();
-	assertEquals(0, components.size());
-    }
-
-    @Test
-    public void testCreateComponentWithRecursion() throws Exception {
+	assertEquals(1, components.size());
+    }
+//
+    @Test
+    public void testCreatePrivateComponentWithRecursion() throws Exception {
+        
+        fillUpPrivateItems();
 	// Create new componet
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getComponentTestContent());
-	ClientResponse cResponse = getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/components")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1140,8 +1184,6 @@
 		RegistryTestHelper.getComponentContentAsStream(compContent),
 		"UPDATE DESCRIPTION!");
-	cResponse = getAuthenticatedResource(
-		getResource().path(
-			"/registry/components/" + desc.getId() + "/update")
-			.queryParam(USERSPACE_PARAM, "true")).type(
+	cResponse = getAuthenticatedResource(getResource().path(
+			"/registry/components/" + desc.getId() + "/update")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1159,15 +1201,17 @@
 
     @Test
-    public void testUpdateComponent() throws Exception {
+    public void testUpdatePrivateComponent() throws Exception {
+        
+        fillUpPrivateItems();
+        
 	List<ComponentDescription> components = getUserComponents();
-	assertEquals("user registered components", 0, components.size());
+	assertEquals("user registered components", 1, components.size());
 	assertEquals("public registered components", 0, getPublicComponents()
 		.size());
-
+        
+        // first, post a component to update
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getComponentTestContent());
-	ClientResponse cResponse = getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/components")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1187,15 +1231,14 @@
 	assertEquals("Access", spec.getCMDComponent().getName());
 	components = getUserComponents();
-	assertEquals(1, components.size());
+	assertEquals(2, components.size());
 	assertEquals(0, getPublicComponents().size());
 
-	// Now update
+	// second, now update
 	form = createFormData(
 		RegistryTestHelper.getComponentTestContentAsStream("TESTNAME"),
 		"UPDATE DESCRIPTION!");
-	cResponse = getAuthenticatedResource(
-		getResource().path(
+	cResponse = getAuthenticatedResource(getResource().path(
 			"/registry/components/" + desc.getId() + "/update")
-			.queryParam(USERSPACE_PARAM, "true")).type(
+			.queryParam(REGISTRY_SPACE_PARAM, "private")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1216,19 +1259,20 @@
 	assertEquals("TESTNAME", spec.getCMDComponent().getName());
 	components = getUserComponents();
-	assertEquals(1, components.size());
+	assertEquals(2, components.size());
 	assertEquals(0, getPublicComponents().size());
     }
 
     @Test
-    public void testUpdateProfile() throws Exception {
+    public void testUpdatePrivateProfile() throws Exception {
+        
+        fillUpPrivateItems();
+        
 	List<ProfileDescription> profiles = getUserProfiles();
-	assertEquals(0, profiles.size());
+	assertEquals(1, profiles.size());
 	assertEquals(0, getPublicProfiles().size());
 
 	FormDataMultiPart form = createFormData(RegistryTestHelper
 		.getTestProfileContent());
-	ClientResponse cResponse = getAuthenticatedResource(
-		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "true")).type(
+	ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1249,5 +1293,5 @@
 	assertEquals("Actor", spec.getCMDComponent().getName());
 	profiles = getUserProfiles();
-	assertEquals(1, profiles.size());
+	assertEquals(2, profiles.size());
 	assertEquals(0, getPublicComponents().size());
 
@@ -1256,8 +1300,6 @@
 		RegistryTestHelper.getTestProfileContent("TESTNAME"),
 		"UPDATE DESCRIPTION!");
-	cResponse = getAuthenticatedResource(
-		getResource().path(
-			"/registry/profiles/" + desc.getId() + "/update")
-			.queryParam(USERSPACE_PARAM, "true")).type(
+	cResponse = getAuthenticatedResource(getResource().path(
+			"/registry/profiles/" + desc.getId() + "/update")).type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
 	assertEquals(ClientResponse.Status.OK.getStatusCode(),
@@ -1278,19 +1320,17 @@
 	assertEquals("TESTNAME", spec.getCMDComponent().getName());
 	profiles = getUserProfiles();
-	assertEquals(1, profiles.size());
+	assertEquals(2, profiles.size());
 	assertEquals(0, getPublicComponents().size());
     }
 
     private CMDComponentSpec getUserComponent(ComponentDescription desc) {
-	return getAuthenticatedResource(
-		getResource().path("/registry/components/" + desc.getId())
-			.queryParam(USERSPACE_PARAM, "true")).accept(
+	return getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())
+			.queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
 		MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
     }
 
     private CMDComponentSpec getUserProfile(ProfileDescription desc) {
-	return getAuthenticatedResource(
-		getResource().path("/registry/profiles/" + desc.getId())
-			.queryParam(USERSPACE_PARAM, "true")).accept(
+	return getAuthenticatedResource(getResource().path("/registry/profiles/" + desc.getId())
+			.queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
 		MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
     }
@@ -1302,7 +1342,6 @@
 
     private List<ComponentDescription> getUserComponents() {
-	return getAuthenticatedResource(
-		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "true")).accept(
+	return getAuthenticatedResource(getResource().path("/registry/components").queryParam(
+			REGISTRY_SPACE_PARAM, "private")).accept(
 		MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE);
     }
@@ -1310,4 +1349,7 @@
     @Test
     public void testRegisterComponent() throws Exception {
+        
+        fillUpPrivateItems();
+        
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
@@ -1326,5 +1368,5 @@
 	assertTrue(response.isRegistered());
 	assertFalse(response.isProfile());
-	assertFalse(response.isInUserSpace());
+	assertTrue(response.isInUserSpace());
 	ComponentDescription desc = (ComponentDescription) response
 		.getDescription();
@@ -1346,9 +1388,11 @@
     @Test
     public void testRegisterComment() throws Exception {
+        
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
 		RegistryTestHelper.getCommentTestContent(),
 		MediaType.APPLICATION_OCTET_STREAM_TYPE);
-	fillUp();
 	String id = ProfileDescription.PROFILE_PREFIX + "profile1";
 	CommentResponse response = getAuthenticatedResource(
@@ -1371,22 +1415,24 @@
     @Test
     public void testRegisterCommentToNonExistent() throws Exception {
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
 		RegistryTestHelper.getCommentTestContent(),
 		MediaType.APPLICATION_OCTET_STREAM_TYPE);
-	fillUp();
 	ClientResponse cResponse = getAuthenticatedResource(
 		"/registry/profiles/clarin.eu:cr1:profile99/comments").type(
 		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
-	assertEquals(500, cResponse.getStatus());
+	assertEquals(404, cResponse.getStatus());
     }
 
     @Test
     public void testRegisterCommentUnauthenticated() throws Exception {
+        fillUpPublicItems();
+        
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
 		RegistryTestHelper.getCommentTestContent(),
 		MediaType.APPLICATION_OCTET_STREAM_TYPE);
-	fillUp();
 	ClientResponse cResponse = getResource()
 		.path("/registry/profiles/clarin.eu:cr1:profile1/comments")
@@ -1398,4 +1444,5 @@
     @Test
     public void testRegisterProfileInvalidData() throws Exception {
+        fillUpPrivateItems();
 	FormDataMultiPart form = new FormDataMultiPart();
 	String notAValidProfile = "<CMD_ComponentSpec> </CMD_ComponentSpec>";
@@ -1426,4 +1473,5 @@
     @Test
     public void testRegisterInvalidProfile() throws Exception {
+        fillUpPrivateItems();
 	FormDataMultiPart form = new FormDataMultiPart();
 	String profileContent = "";
@@ -1469,4 +1517,5 @@
     public void testRegisterProfileInvalidDescriptionAndContent()
 	    throws Exception {
+        fillUpPrivateItems();
 	FormDataMultiPart form = new FormDataMultiPart();
 	String profileContent = "";
@@ -1499,4 +1548,5 @@
     @Test
     public void testRegisterLargeProfile() throws Exception {
+        //fillUpPrivateItems(); not necessary
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
@@ -1519,4 +1569,5 @@
     @Test
     public void testRegisterComponentAsProfile() throws Exception {
+        //fillUpPrivateItems();; not necessary
 	FormDataMultiPart form = new FormDataMultiPart();
 	form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
@@ -1641,6 +1692,6 @@
     @Test
     public void testGetDescription() throws Exception{
-        fillUp();
-    	String id = ComponentDescription.COMPONENT_PREFIX + "component1";
+        fillUpPublicItems();
+        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
         ComponentDescription component = getAuthenticatedResource(getResource().path("/registry/items/" + id)).accept(MediaType.APPLICATION_JSON).get(ComponentDescription.class);
         assertNotNull(component);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java	(revision 5549)
@@ -1,4 +1,5 @@
 package clarin.cmdi.componentregistry.rest;
 
+import clarin.cmdi.componentregistry.RegistrySpace;
 import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -20,5 +21,4 @@
 
 import org.junit.Before;
-import org.junit.BeforeClass;
 import org.junit.Test;
 import org.slf4j.Logger;
@@ -27,5 +27,5 @@
 import org.springframework.jdbc.core.JdbcTemplate;
 
-import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
+import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM;
 import static org.junit.Assert.*;
 
@@ -58,9 +58,11 @@
 	List<Thread> ts = new ArrayList<Thread>();
 
-	registerProfiles(ts, NR_OF_PROFILES, errors, false);
-	registerProfiles(ts, NR_OF_PROFILES, errors, true);
-
-	registerComponents(ts, NR_OF_COMPONENTS, errors, false);
-	registerComponents(ts, NR_OF_COMPONENTS, errors, true);
+	registerProfiles(ts, NR_OF_PROFILES, errors, RegistrySpace.PRIVATE);
+        //a profile can be first registered (created) only in private space, and then moved.
+	//registerProfiles(ts, NR_OF_PROFILES, errors, RegistrySpace.PUBLISHED);
+
+	registerComponents(ts, NR_OF_COMPONENTS, errors, RegistrySpace.PRIVATE);
+	//a profile can be first registered (created) only in private space, and then moved.
+        //registerComponents(ts, NR_OF_COMPONENTS, errors, RegistrySpace.PUBLISHED);
 	runAllThreads(ts);
 	if (errors.size() > 0) {
@@ -70,15 +72,15 @@
 	    fail();
 	}
-	assertProfiles(NR_OF_PROFILES, false);
-	assertProfiles(NR_OF_PROFILES, true);
-
-	assertComponents(NR_OF_COMPONENTS, false);
-	assertComponents(NR_OF_COMPONENTS, true);
-    }
-
-    private void assertProfiles(int nrOfProfiles, boolean userSpace) {
+	assertProfiles(NR_OF_PROFILES, RegistrySpace.PRIVATE);
+	//assertProfiles(NR_OF_PROFILES, RegistrySpace.PUBLISHED);
+
+	assertComponents(NR_OF_COMPONENTS, RegistrySpace.PRIVATE);
+	//assertComponents(NR_OF_COMPONENTS, RegistrySpace.PUBLISHED);
+    }
+
+    private void assertProfiles(int nrOfProfiles, RegistrySpace registrySpace) {
 	List<ProfileDescription> response = getAuthenticatedResource(
 		getResource().path("/registry/profiles").queryParam(
-			USERSPACE_PARAM, "" + userSpace)).accept(
+			REGISTRY_SPACE_PARAM, registrySpace.name())).accept(
 		MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE);
 	Collections.sort(response, descriptionComparator);
@@ -101,8 +103,8 @@
     };
 
-    private void assertComponents(int nrOfComponents, boolean userSpace) {
+    private void assertComponents(int nrOfComponents, RegistrySpace registrySpace) {
 	List<ComponentDescription> cResponse = getAuthenticatedResource(
 		getResource().path("/registry/components").queryParam(
-			USERSPACE_PARAM, "" + userSpace)).accept(
+			REGISTRY_SPACE_PARAM, registrySpace.name())).accept(
 		MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE);
 	Collections.sort(cResponse, descriptionComparator);
@@ -128,5 +130,5 @@
 
     private void registerProfiles(List<Thread> ts, int size,
-	    final List<String> errors, boolean userSpace)
+	    final List<String> errors, RegistrySpace registrySpace)
 	    throws InterruptedException {
 	for (int i = 0; i < size; i++) {
@@ -134,7 +136,7 @@
 	    LOG.debug("Profile {} should be registered in {} and {}",
 		    new Object[] { i + 1000,
-			    userSpace ? "user space" : "public space",
+			    registrySpace.name(),
 			    shouldDelete ? "ALSO DELETED" : "not deleted" });
-	    Thread thread = createThread("/registry/profiles/", userSpace,
+	    Thread thread = createThread("/registry/profiles/", registrySpace,
 		    "Test Profile" + (i + 1000), shouldDelete,
 		    RegistryTestHelper.getTestProfileContent(), errors);
@@ -144,5 +146,5 @@
 
     private void registerComponents(List<Thread> ts, int size,
-	    final List<String> errors, boolean userSpace)
+	    final List<String> errors, RegistrySpace registrySpace)
 	    throws InterruptedException {
 	for (int i = 0; i < size; i++) {
@@ -150,7 +152,7 @@
 	    LOG.debug("Component {} should be registered in {} and {}",
 		    new Object[] { i + 1000,
-			    userSpace ? "user space" : "public space",
+			    registrySpace.name(),
 			    shouldDelete ? "ALSO DELETED" : "not deleted" });
-	    Thread thread = createThread("/registry/components/", userSpace,
+	    Thread thread = createThread("/registry/components/", registrySpace,
 		    "Test Component" + (i + 1000), shouldDelete,
 		    RegistryTestHelper.getComponentTestContent(), errors);
@@ -159,5 +161,5 @@
     }
 
-    private Thread createThread(final String path, final boolean userSpace,
+    private Thread createThread(final String path, final RegistrySpace registrySpace,
 	    final String name, final boolean alsoDelete, InputStream content,
 	    final List<String> errors) throws InterruptedException {
@@ -176,6 +178,5 @@
 		    // System.out.println("THREAD STARTED"+Thread.currentThread().getName());
 		    RegisterResponse registerResponse = getAuthenticatedResource(
-			    getResource().path(path).queryParam(
-				    USERSPACE_PARAM, "" + userSpace)).type(
+			    getResource().path(path)).type(
 			    MediaType.MULTIPART_FORM_DATA).post(
 			    RegisterResponse.class, form);
@@ -188,5 +189,5 @@
 			    + "] REGISTERING DESCRIPTION " + name + " "
 			    + registerResponse.getDescription().getId()
-			    + (Boolean.valueOf(userSpace) ? " userspace" : "")
+			    + registrySpace.name()
 			    + (alsoDelete ? " alsoDelete" : ""));
 		    if (alsoDelete) {
@@ -197,6 +198,5 @@
 				+ " "
 				+ registerResponse.getDescription().getId()
-				+ (Boolean.valueOf(userSpace) ? " userspace "
-					: "")
+				+ registrySpace.name()
 				+ (alsoDelete ? " alsoDelete" : ""));
 			ClientResponse response = getAuthenticatedResource(
@@ -205,6 +205,5 @@
 						+ registerResponse
 							.getDescription()
-							.getId()).queryParam(
-					USERSPACE_PARAM, "" + userSpace))
+							.getId()))
 				.delete(ClientResponse.class);
 			if (response.getStatus() != 200) {
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java	(revision 5549)
@@ -4,11 +4,11 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
-import clarin.cmdi.componentregistry.ComponentStatus;
-import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.OwnerUser;
+import clarin.cmdi.componentregistry.RegistrySpace;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
-import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
 import clarin.cmdi.componentregistry.model.ComponentDescription;
 import clarin.cmdi.componentregistry.model.ProfileDescription;
-
+import clarin.cmdi.componentregistry.model.RegistryUser;
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
@@ -17,9 +17,8 @@
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.jdbc.core.JdbcTemplate;
-
-import static org.junit.Assert.*;
+
 
 /**
@@ -31,20 +30,29 @@
 
     @Autowired
-    private ComponentRegistryFactory componentRegistryFactory;
-    private ComponentRegistry publicRegistry;
-
+    private ComponentRegistryFactory componentRegistryFactory; 
+    @Autowired
+    private ComponentRegistry testRegistry;
+    
+    private RegistryUser user;
+   
+    
     @Before
-    public void setUp() throws TransformerException {
-	publicRegistry = componentRegistryFactory.getPublicRegistry();
-    }
-
-    @Test
-    public void testValidateSucces() {
-	MDValidator validator = getValidProfileValidator();
-	assertTrue(validator.validate());
-    }
-
-    @Test
-    public void testValidateIllegalComponentAttributeName() {
+    @Override
+    public void setUp() throws TransformerException, UserUnauthorizedException {
+        testRegistry = componentRegistryFactory.getPublicRegistry();
+        user = componentRegistryFactory.getOrCreateUser(DummyPrincipal.DUMMY_CREDENTIALS);
+    }
+    
+   
+
+    @Test
+    public void testValidateSucces() throws UserUnauthorizedException{
+	MDValidator validator = this.getValidProfileValidator();
+        boolean result = validator.validate();
+	assertTrue(result);
+    }
+
+    @Test 
+    public void testValidateIllegalComponentAttributeName() throws UserUnauthorizedException{
 	String profileContent = "";
 	profileContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
@@ -93,6 +101,6 @@
 
 	ProfileDescription desc = ProfileDescription.createNewDescription();
-	MDValidator validator = new MDValidator(input, desc, publicRegistry,
-		null, publicRegistry, marshaller);
+        
+	MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
 	assertFalse(validator.validate());
 	assertEquals(4, validator.getErrorMessages().size());
@@ -115,14 +123,15 @@
 
 	ProfileDescription desc = ProfileDescription.createNewDescription();
-	MDValidator validator = new MDValidator(input, desc, publicRegistry,
-		null, publicRegistry, marshaller);
-	assertFalse(validator.validate());
-	assertTrue(validator
-		.getErrorMessages()
-		.get(0)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-    }
-
-    @Test
+        desc.setPublic(true);
+	MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
+	assertFalse(validator.validate());
+	assertTrue(validator
+		.getErrorMessages()
+		.get(0)
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
+        //
+    }
+
+    @Test  
     public void testValidateComponentIdNotRegistered() throws Exception {
 	String id1 = "component1";
@@ -144,25 +153,22 @@
 	profileContent += "</CMD_ComponentSpec>";
 
-	// Ids not registered will return two errors. One for each id
-	ProfileDescription desc = ProfileDescription.createNewDescription();
+	// Ids not registered. will return 2 errors: one per each id.
+	ProfileDescription desc = ProfileDescription.createNewDescription();
+        desc.setPublic(true);
 	MDValidator validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, publicRegistry, null,
-		publicRegistry, marshaller);
-	assertFalse(validator.validate());
-	assertEquals(2, validator.getErrorMessages().size());
-	assertTrue(validator
-		.getErrorMessages()
-		.get(0)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-	assertTrue(validator
-		.getErrorMessages()
-		.get(1)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-
-	// id1 will be added and therefore only id2 is not registered
-	RegistryTestHelper.addComponent(publicRegistry, id1);
+		profileContent.getBytes()), desc, testRegistry, marshaller);
+	assertFalse(validator.validate());
+	assertEquals(1, validator.getErrorMessages().size());
+	assertTrue(validator
+		.getErrorMessages()
+		.get(0)
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
+	
+
+	// id1 will be added as public and therefore only id2 is not registered
+	RegistryTestHelper.addComponent(testRegistry, id1, true);
 	validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, publicRegistry, null,
-		publicRegistry, marshaller);
+		profileContent.getBytes()), desc, testRegistry
+                , marshaller);
 	assertFalse(validator.validate());
 	assertEquals(1, validator.getErrorMessages().size());
@@ -170,11 +176,10 @@
 		.getErrorMessages()
 		.get(0)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-
-	// id2 is added, no more errors shoud be return
-	RegistryTestHelper.addComponent(publicRegistry, id2);
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
+
+	// id2 is added as public, no more errors shoud be return
+	RegistryTestHelper.addComponent(testRegistry, id2, true);
 	validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, publicRegistry, null,
-		publicRegistry, marshaller);
+		profileContent.getBytes()), desc, testRegistry, marshaller);
 	assertTrue("component is registered should be valid now",
 		validator.validate());
@@ -183,10 +188,7 @@
 
     @Test
-    public void testValidateUserRegistry() throws Exception {
+    public void testValidateBaseAndUserRegistry() throws Exception {
 	String id1 = "component1";
 	String id2 = "component2";
-	ComponentRegistry userRegistry = componentRegistryFactory
-		.getComponentRegistry(ComponentStatus.PRIVATE, null,
-			DummyPrincipal.DUMMY_CREDENTIALS);
 
 	String profileContent = "";
@@ -205,20 +207,28 @@
 	profileContent += "</CMD_ComponentSpec>";
 
+        // Public Registry
 	ProfileDescription desc = ProfileDescription.createNewDescription();
 	MDValidator validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, userRegistry, userRegistry,
-		publicRegistry, marshaller);
-	assertFalse(validator.validate());
-	assertEquals(2, validator.getErrorMessages().size());
+		profileContent.getBytes()), desc, testRegistry, marshaller);
+	assertFalse(validator.validate());
+	assertEquals(1, validator.getErrorMessages().size()); // the exception is thrown and propagated on the first non-registered component
 	assertTrue(validator.getErrorMessages().get(0)
 		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
-	assertTrue(validator.getErrorMessages().get(1)
-		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
-
-	RegistryTestHelper.addComponent(userRegistry, id1);
-	RegistryTestHelper.addComponent(publicRegistry, id2);
+        
+	
+        // registering publically the first component
+	RegistryTestHelper.addComponent(testRegistry, id1, true);
+        validator = new MDValidator(new ByteArrayInputStream(
+		profileContent.getBytes()), desc, testRegistry, marshaller);
+        assertFalse(validator.validate());
+	assertEquals(1, validator.getErrorMessages().size()); // the exception is thrown on the second non-registered component
+	assertTrue(validator.getErrorMessages().get(0)
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
+        
+        
+        
+	RegistryTestHelper.addComponent(testRegistry, id2, false);
 	validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, publicRegistry, null,
-		publicRegistry, marshaller);
+		profileContent.getBytes()), desc, testRegistry, marshaller);
 	assertFalse(validator.validate());
 	assertEquals(1, validator.getErrorMessages().size());
@@ -226,10 +236,16 @@
 		.getErrorMessages()
 		.get(0)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR));
+        
+        
+        // make it user registry
+        testRegistry.setRegistryOwner(new OwnerUser(user.getId()));
+        testRegistry.setRegistrySpace(RegistrySpace.PRIVATE);       
+	
+        
 	validator = new MDValidator(new ByteArrayInputStream(
-		profileContent.getBytes()), desc, userRegistry, userRegistry,
-		publicRegistry, marshaller);
-	assertTrue(validator.validate());
+		profileContent.getBytes()), desc, testRegistry,  marshaller);
+        Boolean result =validator.validate(); 
+	assertTrue(result);
 	assertEquals(0, validator.getErrorMessages().size());
     }
@@ -254,6 +270,5 @@
 	ComponentDescription desc = ComponentDescription.createNewDescription();
 	MDValidator validator = new MDValidator(new ByteArrayInputStream(
-		content.getBytes()), desc, publicRegistry, null,
-		publicRegistry, marshaller);
+		content.getBytes()), desc, testRegistry, marshaller);
 	assertFalse(validator.validate());
 	assertEquals(1, validator.getErrorMessages().size());
@@ -261,10 +276,9 @@
 		.getErrorMessages()
 		.get(0)
-		.startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
-
-	RegistryTestHelper.addComponent(publicRegistry, id1);
+		.startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
+
+	RegistryTestHelper.addComponent(testRegistry, id1, true);
 	validator = new MDValidator(
-		new ByteArrayInputStream(content.getBytes()), desc,
-		publicRegistry, null, publicRegistry, marshaller);
+		new ByteArrayInputStream(content.getBytes()), desc,testRegistry, marshaller);
 	assertTrue(validator.validate());
 	assertEquals(0, validator.getErrorMessages().size());
@@ -280,6 +294,5 @@
 
 	ProfileDescription desc = ProfileDescription.createNewDescription();
-	MDValidator validator = new MDValidator(input, desc, publicRegistry,
-		null, publicRegistry, marshaller);
+	MDValidator validator = new MDValidator(input, desc, testRegistry,marshaller);
 
 	// Spec is created during validation, before it should be null
@@ -309,6 +322,7 @@
 	InputStream input = new ByteArrayInputStream(profileContent.getBytes());
 	ProfileDescription desc = ProfileDescription.createNewDescription();
-	MDValidator validator = new MDValidator(input, desc, publicRegistry,
-		null, publicRegistry, marshaller);
+        desc.setPublic(true);
+        desc.setName("test_name");
+	MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
 	return validator;
     }
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java	(revision 5549)
@@ -16,5 +16,7 @@
 import clarin.cmdi.componentregistry.ComponentRegistry;
 import clarin.cmdi.componentregistry.DatesHelper;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.components.CMDComponentSpec;
 import clarin.cmdi.componentregistry.model.Comment;
@@ -27,8 +29,4 @@
 import java.io.InputStreamReader;
 
-import javax.xml.transform.TransformerException;
-
-import org.junit.Before;
-import org.junit.BeforeClass;
 import org.springframework.beans.factory.annotation.Autowired;
 
@@ -46,22 +44,23 @@
     }
 
-    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id) throws ParseException, JAXBException {
-	return addComponent(testRegistry, id, getComponentTestContent());
-    }
-
-    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, String content) throws ParseException,
+    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException {
+	return addComponent(testRegistry, id, getComponentTestContent(), isPublic);
+    }
+
+    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
 	    JAXBException, UnsupportedEncodingException {
-	return addComponent(testRegistry, id, new ByteArrayInputStream(content.getBytes("UTF-8")));
-    }
-
-    private static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, InputStream content) throws ParseException,
+	return addComponent(testRegistry, id, new ByteArrayInputStream(content.getBytes("UTF-8")), isPublic);
+    }
+
+    private static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
 	    JAXBException {
 	ComponentDescription desc = ComponentDescription.createNewDescription();
 	desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
-	desc.setUserId(DummyPrincipal.DUMMY_CREDENTIALS.getPrincipalName());
+        desc.setUserId(DummyPrincipal.DUMMY_PRINCIPAL.getName());
 	desc.setName(id);
 	desc.setDescription("Test Description");
 	desc.setId(ComponentDescription.COMPONENT_PREFIX + id);
 	desc.setHref("link:" + desc.getId());
+        desc.setPublic(isPublic);
 	CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
 	testRegistry.register(desc, spec);
@@ -104,15 +103,15 @@
     }
 
-    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id) throws ParseException, JAXBException {
-	return addProfile(testRegistry, id, RegistryTestHelper.getTestProfileContent());
-    }
-
-    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, String content) throws ParseException,
-	    JAXBException {
-	return addProfile(testRegistry, id, new ByteArrayInputStream(content.getBytes()));
-    }
-
-    private static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, InputStream content) throws ParseException,
-	    JAXBException {
+    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException, ItemNotFoundException {
+	return addProfile(testRegistry, id, RegistryTestHelper.getTestProfileContent(), isPublic);
+    }
+
+    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
+	    JAXBException, ItemNotFoundException {
+	return addProfile(testRegistry, id, new ByteArrayInputStream(content.getBytes()), isPublic);
+    }
+
+    private static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
+	    JAXBException, ItemNotFoundException {
 	ProfileDescription desc = ProfileDescription.createNewDescription();
 	desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
@@ -122,4 +121,5 @@
 	desc.setId(ProfileDescription.PROFILE_PREFIX + id);
 	desc.setHref("link:" + ProfileDescription.PROFILE_PREFIX + id);
+        desc.setPublic(isPublic);
 	CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
 	testRegistry.register(desc, spec);
@@ -216,5 +216,5 @@
     }
 
-    public static Comment addComment(ComponentRegistry testRegistry, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException {
+    public static Comment addComment(ComponentRegistry testRegistry, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException, ItemNotFoundException,UserUnauthorizedException {
 	return addComment(testRegistry, RegistryTestHelper.getTestCommentContent(id, descriptionId), principal);
     }
@@ -222,5 +222,5 @@
     private static Comment addComment(ComponentRegistry testRegistry, InputStream content, String principal) throws ParseException,
 	    JAXBException,
-	    ComponentRegistryException {
+	    ComponentRegistryException, ItemNotFoundException,UserUnauthorizedException {
 	Comment spec = marshaller.unmarshal(Comment.class, content, null);
 	testRegistry.registerComment(spec, principal);
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/SanboxTest.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/SanboxTest.java	(revision 5549)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/SanboxTest.java	(revision 5549)
@@ -0,0 +1,170 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package clarin.cmdi.componentregistry.rest;
+
+import clarin.cmdi.componentregistry.ComponentRegistry;
+import clarin.cmdi.componentregistry.ComponentRegistryFactory;
+import clarin.cmdi.componentregistry.impl.database.ComponentRegistryBeanFactory;
+import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
+import clarin.cmdi.componentregistry.model.Comment;
+import clarin.cmdi.componentregistry.model.ComponentDescription;
+import clarin.cmdi.componentregistry.model.ProfileDescription;
+import clarin.cmdi.componentregistry.model.RegisterResponse;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.multipart.FormDataMultiPart;
+import javax.ws.rs.core.MediaType;
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.JdbcTemplate;
+
+import org.springframework.util.Assert;
+import static org.junit.Assert.*;
+/**
+ *
+ * @author olhsha
+ */
+public class SanboxTest extends
+	ComponentRegistryRestServiceTestCase {
+
+    @Autowired
+    private ComponentRegistryFactory componentRegistryFactory;
+    @Autowired
+    private ComponentRegistryBeanFactory componentRegistryBeanFactory;
+    @Autowired
+    private JdbcTemplate jdbcTemplate;
+    private ComponentRegistry baseRegistry;
+
+    @Before
+    public void init() {
+	ComponentRegistryTestDatabase.resetAndCreateAllTables(jdbcTemplate);
+	createUserRecord();
+	baseRegistry = componentRegistryFactory.getBaseRegistry(DummyPrincipal.DUMMY_CREDENTIALS);
+    }
+
+    private String expectedUserId(String principal) {
+	return getUserDao().getByPrincipalName(principal).getId().toString();
+    }
+
+    private ComponentDescription component1;
+    private ComponentDescription component2;
+    private ProfileDescription profile1;
+    private ProfileDescription profile2;
+    
+    private ComponentDescription component3;
+    private ProfileDescription profile3;
+    
+    private Comment profile1Comment1;
+    private Comment profile1Comment2;
+    private Comment component1Comment3;
+    private Comment component1Comment4;
+    
+    private Comment profile3Comment5;
+    private Comment component3Comment7;
+
+    private void fillUpPublicItems() throws Exception {
+        
+	profile1 = RegistryTestHelper.addProfile(baseRegistry, "profile2", true);
+	profile2 = RegistryTestHelper.addProfile(baseRegistry, "profile1", true);
+	component1 = RegistryTestHelper.addComponent(baseRegistry,
+		"component2", true);
+	component2 = RegistryTestHelper.addComponent(baseRegistry,
+		"component1", true);
+	profile1Comment2 = RegistryTestHelper.addComment(baseRegistry, "comment2",
+		ProfileDescription.PROFILE_PREFIX + "profile1",
+		"JUnit@test.com");
+	profile1Comment1 = RegistryTestHelper.addComment(baseRegistry, "comment1",
+		ProfileDescription.PROFILE_PREFIX + "profile1",
+		"JUnit@test.com");
+	component1Comment3 = RegistryTestHelper.addComment(baseRegistry, "comment3",
+		ComponentDescription.COMPONENT_PREFIX + "component1",
+		"JUnit@test.com");
+	component1Comment4 = RegistryTestHelper.addComment(baseRegistry, "comment4",
+		ComponentDescription.COMPONENT_PREFIX + "component1",
+		"JUnit@test.com");
+    }
+    
+    private void fillUpPrivateItems() throws Exception {
+	profile3 = RegistryTestHelper.addProfile(baseRegistry, "profile3", false);
+	component3 = RegistryTestHelper.addComponent(baseRegistry,
+		"component3", false);
+	profile3Comment5 = RegistryTestHelper.addComment(baseRegistry, "comment5",
+		ProfileDescription.PROFILE_PREFIX + "profile3",
+		"JUnit@test.com");
+	component3Comment7 = RegistryTestHelper.addComment(baseRegistry, "comment7",
+		ComponentDescription.COMPONENT_PREFIX + "component3",
+		"JUnit@test.com");
+    }
+    
+       @Test
+    public void testCreatePrivateComponentWithRecursion() throws Exception {
+        
+        fillUpPrivateItems();
+	// Create new componet
+	FormDataMultiPart form = createFormData(RegistryTestHelper
+		.getComponentTestContent());
+	ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/components")).type(
+		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
+	assertEquals(ClientResponse.Status.OK.getStatusCode(),
+		cResponse.getStatus());
+	RegisterResponse response = cResponse.getEntity(RegisterResponse.class);
+	assertTrue(response.isRegistered());
+	ComponentDescription desc = (ComponentDescription) response
+		.getDescription();
+
+	// Re-define with self-recursion
+	String compContent = "";
+	compContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
+	compContent += "\n";
+	compContent += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
+	compContent += "    xsi:noNamespaceSchemaLocation=\"../../general-component-schema.xsd\">\n";
+	compContent += "    \n";
+	compContent += "    <Header/>\n";
+	compContent += "    \n";
+	compContent += "    <CMD_Component name=\"Nested\" CardinalityMin=\"1\" CardinalityMax=\"1\">\n";
+	compContent += "        <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
+	compContent += "        <CMD_Component ComponentId=\""
+		+ desc.getId()
+		+ "\" name=\"Recursive\" CardinalityMin=\"1\" CardinalityMax=\"1\" />\n";
+	compContent += "    </CMD_Component>\n";
+	compContent += "\n";
+	compContent += "</CMD_ComponentSpec>\n";
+
+	// Update component
+	form = createFormData(
+		RegistryTestHelper.getComponentContentAsStream(compContent),
+		"UPDATE DESCRIPTION!");
+	cResponse = getAuthenticatedResource(getResource().path(
+			"/registry/components/" + desc.getId() + "/update")).type(
+		MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
+	assertEquals(ClientResponse.Status.OK.getStatusCode(),
+		cResponse.getStatus());
+	response = cResponse.getEntity(RegisterResponse.class);
+	assertFalse("Recursive definition should fail", response.isRegistered());
+	assertEquals("There should be an error message for the recursion", 1,
+		response.getErrors().size());
+	assertTrue(
+		"There error message should specify the point of recursion",
+		response.getErrors().get(0)
+			.contains("already contains " + desc.getId()));
+
+    }
+
+     private FormDataMultiPart createFormData(Object content) {
+	return createFormData(content, "My Test");
+    }
+
+    private FormDataMultiPart createFormData(Object content, String description) {
+	FormDataMultiPart form = new FormDataMultiPart();
+	form.field(IComponentRegistryRestService.DATA_FORM_FIELD, content,
+		MediaType.APPLICATION_OCTET_STREAM_TYPE);
+	form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "Test1");
+	form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD,
+		description);
+	form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "My domain");
+	form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "TestGroup");
+	return form;
+    }
+}
Index: /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rss/PrintXmlFromRssRunner.java
===================================================================
--- /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rss/PrintXmlFromRssRunner.java	(revision 5548)
+++ /ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rss/PrintXmlFromRssRunner.java	(revision 5549)
@@ -5,5 +5,7 @@
 import clarin.cmdi.componentregistry.ComponentRegistryFactory;
 import clarin.cmdi.componentregistry.DatesHelper;
+import clarin.cmdi.componentregistry.ItemNotFoundException;
 import clarin.cmdi.componentregistry.MDMarshaller;
+import clarin.cmdi.componentregistry.UserUnauthorizedException;
 import clarin.cmdi.componentregistry.impl.ComponentUtils;
 import clarin.cmdi.componentregistry.model.BaseDescription;
@@ -20,7 +22,4 @@
 
 import javax.xml.bind.JAXBException;
-import javax.xml.transform.TransformerException;
-
-import org.junit.BeforeClass;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.ApplicationContext;
@@ -93,5 +92,5 @@
      * input: sort of rss -- profiles, or comopnents, or comments (see below the prompt string)
      */
-    public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException {
+    public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException, UserUnauthorizedException, ItemNotFoundException {
 
 	System.out.println("Type 1 or 2, or 3, or 4, \n "
@@ -137,6 +136,6 @@
 		System.exit(1);
 	    }
-	    final List<Comment> comments = (kind == 3) ? registry.getCommentsInProfile(buffer, null) : registry.getCommentsInComponent(buffer, null);
-	    final String name = (kind == 3) ? registry.getProfileDescription(buffer).getName() : registry.getComponentDescription(buffer).getName();
+	    final List<Comment> comments = (kind == 3) ? registry.getCommentsInProfile(buffer) : registry.getCommentsInComponent(buffer);
+	    final String name = (kind == 3) ? registry.getProfileDescriptionAccessControlled(buffer).getName() : registry.getComponentDescriptionAccessControlled(buffer).getName();
 	    rss = makeRssForComments(comments, kind, baseUri, 10, buffer, name);
 
