Changeset 5549


Ignore:
Timestamp:
08/11/14 16:07:55 (10 years ago)
Author:
olhsha@mpi.nl
Message:

Added group service. Tested via the tomcat on loclahots (test URI and postman), old unit tests are adjusted and work well. Todo: retest on localhost tomcat, look at run-time exceptions, add new unit tests, adjust front-end

Location:
ComponentRegistry/trunk/ComponentRegistry
Files:
9 added
49 edited

Legend:

Unmodified
Added
Removed
  • ComponentRegistry/trunk/ComponentRegistry/nbactions.xml

    r2531 r5549  
    3535            </properties>
    3636        </action>
     37        <action>
     38            <actionName>debug.test.single</actionName>
     39            <goals>
     40                <goal>test-compile</goal>
     41                <goal>surefire:test</goal>
     42            </goals>
     43            <properties>
     44                <test>${packageClassName}</test>
     45                <forkMode>once</forkMode>
     46                <maven.surefire.debug>-Xdebug -Xrunjdwp:transport=dt_socket,server=n,address=${jpda.address} -Xmx512m</maven.surefire.debug>
     47                <jpda.listen>true</jpda.listen>
     48               
     49            </properties>
     50        </action>
    3751    </actions>
  • ComponentRegistry/trunk/ComponentRegistry/pom.xml

    r4847 r5549  
    3131                <flexDebug>0</flexDebug>
    3232                <spring-data-jpa.version>1.3.4.RELEASE</spring-data-jpa.version>
    33                 <spring.version>3.2.4.RELEASE</spring.version>
     33                <spring.version>3.2.10.RELEASE</spring.version>
    3434                <jackson.version>1.9.13</jackson.version>
    3535                <jersey.version>1.17.1</jersey.version>
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistry.java

    r4098 r5549  
    2323    public static final String PUBLIC_NAME = "Public Registry";
    2424
     25   
     26   
     27    public Owner getRegistryOwner(); 
     28    public void setRegistryOwner(Owner registryOwner);     
     29   
     30    public RegistrySpace getRegistrySpace();
     31    public void setRegistrySpace(RegistrySpace registrySpace);
     32   
     33    public Number getGroupId();
     34    public void setGroupId(Number groupId);
     35   
     36    public Number getBaseDescriptionOwnerId(String cmdId);
     37   
     38    public List<Number> getItemGroups(String cmdId);
    2539    /**
    2640     * @return List of component descriptions ordered by name ascending
    2741     * @throws ComponentRegistryException
    2842     */
    29     List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException;
    30 
    31     /**
    32      * @param principalName
    33      * @param groupId
    34      * @return List of component descriptions ordered by name ascending
    35      * @throws ComponentRegistryException
    36      */
    37     List<ComponentDescription> getComponentDescriptionsInGroup(String principalName, String groupId) throws ComponentRegistryException;
    38 
    39     ComponentDescription getComponentDescription(String id) throws ComponentRegistryException;
    40 
     43    List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException, UserUnauthorizedException;
     44
     45   
     46    ComponentDescription getComponentDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     47
     48   
    4149    /**
    4250     *
     
    4452     * @throws ComponentRegistryException
    4553     */
    46     List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException;
    47 
    48     /**
    49     * @param groupId
    50     * @return List of profile descriptions ordered by name ascending
    51     * @throws ComponentRegistryException
    52     */
    53    List<ProfileDescription> getProfileDescriptionsInGroup(String groupId) throws ComponentRegistryException;
     54    List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException, UserUnauthorizedException;
     55
    5456
    5557   /**
     
    6567    * @throws ComponentRegistryException
    6668    */
    67    List<ProfileDescription> getProfileDescriptionsForMetadaEditor(String groupId) throws ComponentRegistryException;
    68 
    69    ProfileDescription getProfileDescription(String id) throws ComponentRegistryException;
    70 
    71     CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException;
     69   List<ProfileDescription> getProfileDescriptionsForMetadaEditor(Number groupId) throws ComponentRegistryException, UserUnauthorizedException;
     70
     71   ProfileDescription getProfileDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     72
     73    CMDComponentSpec getMDProfileAccessControled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     74
     75    CMDComponentSpec getMDComponentAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
    7276
    7377    CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException;
    74 
    7578    /**
    7679     *
     
    8487     * @return -1 if comment could not be registered
    8588     */
    86     int registerComment(Comment comment, String userId) throws ComponentRegistryException;
     89    int registerComment(Comment comment, String userId) throws ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException;
    8790
    8891    /**
     
    9093     * @return -1 if component could not be updated
    9194     */
    92     int update(BaseDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate);
     95    int update(BaseDescription description, CMDComponentSpec spec, boolean forceUpdate)  throws UserUnauthorizedException, ItemNotFoundException;
    9396
    9497    /**
     
    97100     * current (private) workspace to public workspace.
    98101     */
    99     int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal);
    100 
    101     void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException;
    102 
    103     void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException;
    104 
    105     void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException;
    106 
    107     void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException;
    108 
    109     /**
    110      *
    111      * @param profileId
    112      * @param principal
     102    int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal)  throws UserUnauthorizedException, ItemNotFoundException;
     103
     104    void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     105
     106    void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     107
     108    void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     109
     110    void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
     111
     112    /**
     113     *
     114     * @param profileIds
    113115     * @throws IOException
    114116     * @throws UserUnauthorizedException
     
    116118     * @throws DeleteFailedException
    117119     */
    118     void deleteMDProfile(String profileId, Principal principal) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException;
     120    void deleteMDProfile(String profileId) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException, ItemNotFoundException;
    119121
    120122    /**
     
    130132     * @throws DeleteFailedException
    131133     */
    132     void deleteMDComponent(String componentId, Principal principal, boolean forceDelete) throws IOException, ComponentRegistryException, UserUnauthorizedException,
    133             DeleteFailedException;
     134    void deleteMDComponent(String componentId, boolean forceDelete) throws IOException, ComponentRegistryException, UserUnauthorizedException,
     135            DeleteFailedException, ItemNotFoundException;
    134136
    135137    /**
     
    149151    List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException;
    150152
    151     /**
    152      * Return true if this registry is the public registry as opposed to a
    153      * registry used for the user privately.
    154      * */
    155     boolean isPublic();
    156 
    157     ComponentStatus getStatus();
    158 
    159     Owner getOwner();
     153 
    160154
    161155    /**
     
    168162     * @return List of profile descriptions ordered by name ascending
    169163     */
    170     List<ProfileDescription> getDeletedProfileDescriptions();
     164    List<ProfileDescription> getDeletedProfileDescriptions()throws ComponentRegistryException;
    171165
    172166    /**
     
    174168     * @return List of component descriptions ordered by name ascending
    175169     */
    176     List<ComponentDescription> getDeletedComponentDescriptions();
     170    List<ComponentDescription> getDeletedComponentDescriptions() throws ComponentRegistryException;
    177171
    178172    /**
     
    182176     * @throws ComponentRegistryException
    183177     */
    184     List<Comment> getCommentsInProfile(String profileId, Principal principal) throws ComponentRegistryException;
     178    List<Comment> getCommentsInProfile(String profileId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
    185179
    186180    /**
     
    191185     * @throws ComponentRegistryException
    192186     */
    193     Comment getSpecifiedCommentInProfile(String profileId, String commentId, Principal principal) throws ComponentRegistryException;
     187    Comment getSpecifiedCommentInProfile(String profileId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
    194188
    195189    /**
     
    199193     * @throws ComponentRegistryException
    200194     */
    201     List<Comment> getCommentsInComponent(String componentId, Principal principal) throws ComponentRegistryException;
     195    List<Comment> getCommentsInComponent(String componentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
    202196
    203197    /**
     
    208202     * @throws ComponentRegistryException
    209203     */
    210     Comment getSpecifiedCommentInComponent(String componentId, String commentId, Principal principal) throws ComponentRegistryException;
     204    Comment getSpecifiedCommentInComponent(String componentId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException;
    211205
    212206    /**
     
    219213     * @throws DeleteFailedException
    220214     */
    221     public void deleteComment(String commentId, Principal principal) throws IOException, ComponentRegistryException, UserUnauthorizedException,
    222             DeleteFailedException;
     215    public void deleteComment(String commentId) throws IOException, ComponentRegistryException, UserUnauthorizedException,
     216            DeleteFailedException, ItemNotFoundException;
    223217
    224218    /**
     
    239233     */
    240234    List<String> getAllNonDeletedComponentIds();
     235   
     236    Boolean isItemPublic(String id) throws ItemNotFoundException;
     237   
    241238}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistryFactory.java

    r1993 r5549  
    2323     * @return
    2424     */
    25     ComponentRegistry getComponentRegistry(ComponentStatus status, Owner owner, UserCredentials credentials) throws UserUnauthorizedException;
    26 
    27     ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, ComponentStatus status, Owner owner);
     25    ComponentRegistry getComponentRegistry(RegistrySpace space, Owner owner, UserCredentials credentials, Number groupId) throws UserUnauthorizedException;
    2826
    2927    ComponentRegistry getPublicRegistry();
     28   
     29    ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, Owner owner);
     30   
     31    ComponentRegistry getBaseRegistry(UserCredentials credentials);
    3032
    3133    RegistryUser getOrCreateUser(UserCredentials credentials);
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentStatus.java

    r3035 r5549  
    77public enum ComponentStatus {
    88
    9     /**
    10      * Private mode, editable non-public
    11      */
    12     PRIVATE(false, true),
    13     /**
    14      * Development mode, editable and publicly visible
    15      */
    16     DEVELOPMENT(false, true),
    17     /**
    18      * Published mode, non-editable and publicly visible
    19      */
    20     PUBLISHED(true, false),
    21     /**
    22      * Deprecated mode, non-editable and not publicly listed
    23      */
    24     DEPRECATED(false, false);
    25     final boolean publiclyListable;
    26     final boolean editable;
    27 
    28     private ComponentStatus(boolean publiclyListable, boolean editable) {
    29         this.publiclyListable = publiclyListable;
    30         this.editable = editable;
    31     }
    32 
    33     public boolean isEditable() {
    34         return editable;
    35     }
    36 
    37     public boolean isPubliclyListable() {
    38         return publiclyListable;
    39     }
     9   
     10    DEVELOPMENT,
     11   
     12    PRIDUCTION,
     13   
     14    DEPRECATED;
     15   
    4016}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/Configuration.java

    r3088 r5549  
    7474    }
    7575
     76    public boolean isAdminUser(String name) {
     77        if (name != null) {
     78            return name.trim().length() > 0 // user name must be set (in case an empty entry is in admin users list)
     79                    && adminUsers.contains(name);
     80        }
     81        return false;
     82    }
     83   
    7684    public void setAdminUsers(Collection<String> adminUsers) {
    7785        LOG.debug("Setting adminUsers to {}", Arrays.toString(adminUsers.toArray()));
    7886        this.adminUsers = adminUsers;
    7987    }
    80 
     88   
     89   
    8190    /**
    8291     *
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java

    r4098 r5549  
    2929import clarin.cmdi.componentregistry.ComponentRegistryException;
    3030import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    31 import clarin.cmdi.componentregistry.ComponentStatus;
    3231import clarin.cmdi.componentregistry.MDMarshaller;
     32import clarin.cmdi.componentregistry.RegistrySpace;
     33import clarin.cmdi.componentregistry.UserUnauthorizedException;
    3334import clarin.cmdi.componentregistry.impl.database.AdminRegistry;
    3435import clarin.cmdi.componentregistry.model.BaseDescription;
     
    4344    private final static Logger LOG = LoggerFactory.getLogger(AdminHomePage.class);
    4445    private final CMDItemInfo info;
    45     private final LinkTree tree;
     46    private LinkTree tree;
    4647    private transient AdminRegistry adminRegistry = new AdminRegistry();
    4748    @SpringBean(name = "componentRegistryFactory")
     
    5354
    5455    public AdminHomePage(final PageParameters parameters) throws ComponentRegistryException {
    55         super(parameters);
    56         adminRegistry.setComponentRegistryFactory(componentRegistryFactory);
    57         adminRegistry.setComponentDao(componentDao);
    58         adminRegistry.setMarshaller(marshaller);
    59         info = new CMDItemInfo(marshaller);
    60         addLinks();
    61         final FeedbackPanel feedback = new FeedbackPanel("feedback");
    62         feedback.setOutputMarkupId(true);
    63         add(feedback);
    64         Form form = new ItemEditForm("form");
    65         add(form);
    66 
    67         Button deleteButton = new AjaxFallbackButton("delete", form) {
    68 
    69             @Override
    70             protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
    71                 CMDItemInfo info = (CMDItemInfo) form.getModelObject();
    72                 info("deleting:" + info.getName());
    73                 Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
    74                 try {
    75                     adminRegistry.delete(info, userPrincipal);
    76                     info("Item deleted.");
    77                     reloadTreeModel(info);
    78                 } catch (SubmitFailedException e) {
    79                     LOG.error("Admin: ", e);
    80                     error("Cannot delete: " + info.getName() + "\n error=" + e);
    81                 }
    82                 if (target != null) {
    83                     target.addComponent(form);
    84                     target.addComponent(tree);
    85                     target.addComponent(feedback);
    86                 }
    87             }
    88 
    89             @Override
    90             public boolean isEnabled() {
    91                 return info.isDeletable();
    92 
    93             }
    94         ;
    95         };
     56        super(parameters);
     57        adminRegistry.setComponentRegistryFactory(componentRegistryFactory);
     58        adminRegistry.setComponentDao(componentDao);
     59        adminRegistry.setMarshaller(marshaller);
     60        info = new CMDItemInfo(marshaller);
     61        addLinks();
     62        final FeedbackPanel feedback = new FeedbackPanel("feedback");
     63        feedback.setOutputMarkupId(true);
     64        add(feedback);
     65        Form form = new ItemEditForm("form");
     66        add(form);
     67
     68        Button deleteButton = new AjaxFallbackButton("delete", form) {
     69            @Override
     70            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
     71                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
     72                info("deleting:" + info.getName());
     73                Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
     74                try {
     75                    adminRegistry.delete(info, userPrincipal);
     76                    info("Item deleted.");
     77                    reloadTreeModel(info);
     78                } catch (Exception e) {
     79                    LOG.error("Admin: ", e);
     80                    error("Cannot delete: " + info.getName() + "\n error=" + e);
     81                }
     82                if (target != null) {
     83                    target.addComponent(form);
     84                    target.addComponent(tree);
     85                    target.addComponent(feedback);
     86                }
     87            }
     88
     89            @Override
     90            public boolean isEnabled() {
     91                return info.isDeletable();
     92
     93            }
     94        ;
     95        };
    9696        form.add(deleteButton);
    9797
    98         Button undeleteButton = new AjaxFallbackButton("undelete", form) {
    99 
    100             @Override
    101             protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
    102                 CMDItemInfo info = (CMDItemInfo) form.getModelObject();
    103                 info("undeleting:" + info.getName());
    104                 try {
    105                     adminRegistry.undelete(info);
    106                     info("Item put back.");
    107                     reloadTreeModel(info);
    108                 } catch (SubmitFailedException e) {
    109                     LOG.error("Admin: ", e);
    110                     error("Cannot undelete: " + info.getName() + "\n error=" + e);
    111                 }
    112                 if (target != null) {
    113                     target.addComponent(form);
    114                     target.addComponent(tree);
    115                     target.addComponent(feedback);
    116                 }
    117             }
    118 
    119             @Override
    120             public boolean isEnabled() {
    121                 return info.isUndeletable();
    122             }
    123         };
    124         form.add(undeleteButton);
    125 
    126         CheckBox forceUpdateCheck = new CheckBox("forceUpdate");
    127         form.add(forceUpdateCheck);
    128 
    129         Button submitButton = new AjaxFallbackButton("submit", form) {
    130 
    131             @Override
    132             protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
    133                 CMDItemInfo info = (CMDItemInfo) form.getModelObject();
    134                 Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
    135                 info("submitting:" + info.getName() + " id=(" + info.getDataNode().getDescription().getId() + ")");
    136                 try {
    137                     adminRegistry.submitFile(info, userPrincipal);
    138                     info("submitting done.");
    139                     reloadTreeModel(info);
    140                 } catch (SubmitFailedException e) {
    141                     LOG.error("Admin: ", e);
    142                     error("Cannot submit: " + info.getName() + "\n error=" + e);
    143                 }
    144                 if (target != null) {
    145                     target.addComponent(form);
    146                     target.addComponent(tree);
    147                     target.addComponent(feedback);
    148                 }
    149             }
    150 
    151             @Override
    152             public boolean isEnabled() {
    153                 return info.isEditable();
    154             }
    155         };
    156         form.add(submitButton);
    157 
    158         tree = createTree("tree", form, createDBTreeModel());
    159         add(tree);
    160         add(new Link("expandAll") {
    161 
    162             @Override
    163             public void onClick() {
    164                 tree.getTreeState().expandAll();
    165             }
    166         });
    167 
    168         add(new Link("collapseAll") {
    169 
    170             @Override
    171             public void onClick() {
    172                 tree.getTreeState().collapseAll();
    173             }
    174         });
    175 
    176     }
    177 
    178     private void reloadTreeModel(CMDItemInfo info) {
    179         try {
    180             tree.setModelObject(createDBTreeModel());
    181         } catch (ComponentRegistryException e) {
    182             LOG.error("Admin: ", e);
    183             error("Cannot reload tree: " + info.getName() + "\n error=" + e);
    184         }
     98        Button undeleteButton = new AjaxFallbackButton("undelete", form) {
     99            @Override
     100            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
     101                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
     102                info("undeleting:" + info.getName());
     103                try {
     104                    adminRegistry.undelete(info);
     105                    info("Item put back.");
     106                    reloadTreeModel(info);
     107                } catch (Exception e) {
     108                    LOG.error("Admin: ", e);
     109                    error("Cannot undelete: " + info.getName() + "\n error=" + e);
     110                }
     111                if (target != null) {
     112                    target.addComponent(form);
     113                    target.addComponent(tree);
     114                    target.addComponent(feedback);
     115                }
     116            }
     117
     118            @Override
     119            public boolean isEnabled() {
     120                return info.isUndeletable();
     121            }
     122        };
     123        form.add(undeleteButton);
     124
     125        CheckBox forceUpdateCheck = new CheckBox("forceUpdate");
     126        form.add(forceUpdateCheck);
     127
     128        Button submitButton = new AjaxFallbackButton("submit", form) {
     129            @Override
     130            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
     131                CMDItemInfo info = (CMDItemInfo) form.getModelObject();
     132                Principal userPrincipal = getWebRequest().getHttpServletRequest().getUserPrincipal();
     133                info("submitting:" + info.getName() + " id=(" + info.getDataNode().getDescription().getId() + ")");
     134                try {
     135                    adminRegistry.submitFile(info, userPrincipal);
     136                    info("submitting done.");
     137                    reloadTreeModel(info);
     138                } catch (Exception e) {
     139                    LOG.error("Admin: ", e);
     140                    error("Cannot submit: " + info.getName() + "\n error=" + e);
     141                }
     142                if (target != null) {
     143                    target.addComponent(form);
     144                    target.addComponent(tree);
     145                    target.addComponent(feedback);
     146                }
     147            }
     148
     149            @Override
     150            public boolean isEnabled() {
     151                return info.isEditable();
     152            }
     153        };
     154        form.add(submitButton);
     155
     156
     157
     158
     159        try {
     160            tree = createTree("tree", form, createDBTreeModel());
     161            add(tree);
     162            add(new Link("expandAll") {
     163                @Override
     164                public void onClick() {
     165                    tree.getTreeState().expandAll();
     166                }
     167            });
     168
     169            add(new Link("collapseAll") {
     170                @Override
     171                public void onClick() {
     172                    tree.getTreeState().collapseAll();
     173                }
     174            });
     175
     176        } catch (UserUnauthorizedException e) {           
     177            LOG.error("Admin: ", e);
     178            error("Cannot create tree: error = " + e);
     179        }
     180       
     181    }
     182
     183    private void reloadTreeModel(CMDItemInfo info) throws UserUnauthorizedException {
     184        try {
     185            tree.setModelObject(createDBTreeModel());
     186        } catch (ComponentRegistryException e) {
     187            LOG.error("Admin: ", e);
     188            error("Cannot reload tree: " + info.getName() + "\n error=" + e);
     189        }
    185190    }
    186191
    187192    private void addLinks() {
    188         add(new Label("linksMessage", "Browse the data below or choose on of the following options:"));
    189         add(new Link("massMigrate") {
    190 
    191             @Override
    192             public void onClick() {
    193                 setResponsePage(MassMigratePage.class);
    194             }
    195         });
    196         add(new Link("log") {
    197 
    198             @Override
    199             public void onClick() {
    200                 setResponsePage(ViewLogPage.class);
    201             }
    202         });
    203         add(new Link("statistics") {
    204 
    205             @Override
    206             public void onClick() {
    207                 setResponsePage(StatisticsPage.class);
    208             }
    209         });
     193        add(new Label("linksMessage", "Browse the data below or choose on of the following options:"));
     194        add(new Link("massMigrate") {
     195            @Override
     196            public void onClick() {
     197                setResponsePage(MassMigratePage.class);
     198            }
     199        });
     200        add(new Link("log") {
     201            @Override
     202            public void onClick() {
     203                setResponsePage(ViewLogPage.class);
     204            }
     205        });
     206        add(new Link("statistics") {
     207            @Override
     208            public void onClick() {
     209                setResponsePage(StatisticsPage.class);
     210            }
     211        });
    210212    }
    211213
    212214    private LinkTree createTree(String id, final Form form, TreeModel treeModel) {
    213         final LinkTree adminTree = new LinkTree(id, treeModel) {
    214 
    215             @Override
    216             protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
    217                 super.onNodeLinkClicked(node, tree, target);
    218                 ITreeState treeState = tree.getTreeState();
    219                 if (treeState.isNodeExpanded(node)) {
    220                     treeState.collapseNode(node);
    221                 } else {
    222                     treeState.expandNode(node);
    223                 }
    224                 DisplayDataNode dn = (DisplayDataNode) ((DefaultMutableTreeNode) node).getUserObject();
    225                 info.setDataNode(dn);
    226                 BaseDescription desc = dn.getDescription();
    227                 if (desc != null) {
    228                     String content = componentDao.getContent(dn.isDeleted(), desc.getId());
    229                     info.setContent(content);
    230                 }
    231                 if (target != null) {
    232                     target.addComponent(form);
    233                 }
    234             }
    235         };
    236         return adminTree;
     215        final LinkTree adminTree = new LinkTree(id, treeModel) {
     216            @Override
     217            protected void onNodeLinkClicked(Object node, BaseTree tree, AjaxRequestTarget target) {
     218                super.onNodeLinkClicked(node, tree, target);
     219                ITreeState treeState = tree.getTreeState();
     220                if (treeState.isNodeExpanded(node)) {
     221                    treeState.collapseNode(node);
     222                } else {
     223                    treeState.expandNode(node);
     224                }
     225                DisplayDataNode dn = (DisplayDataNode) ((DefaultMutableTreeNode) node).getUserObject();
     226                info.setDataNode(dn);
     227                BaseDescription desc = dn.getDescription();
     228                if (desc != null) {
     229                    String content = componentDao.getContent(dn.isDeleted(), desc.getId());
     230                    info.setContent(content);
     231                }
     232                if (target != null) {
     233                    target.addComponent(form);
     234                }
     235            }
     236        };
     237        return adminTree;
    237238    }
    238239
    239240    private class ItemEditForm extends Form<CMDItemInfo> {
    240241
    241         public ItemEditForm(String name) {
    242             super(name);
    243             CompoundPropertyModel model = new CompoundPropertyModel(info);
    244             setModel(model);
    245 
    246             TextArea descriptionArea = new TextArea("description");
    247             descriptionArea.setOutputMarkupId(true);
    248             add(descriptionArea);
    249             TextArea contentArea = new TextArea("content");
    250             contentArea.setOutputMarkupId(true);
    251             add(contentArea);
    252         }
    253     }
    254 
    255     private TreeModel createDBTreeModel() throws ComponentRegistryException {
    256         DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new DisplayDataNode("ComponentRegistry", false));
    257         DefaultMutableTreeNode publicNode = new DefaultMutableTreeNode(new DisplayDataNode("Public", false));
    258         rootNode.add(publicNode);
    259         ComponentRegistry publicRegistry = componentRegistryFactory.getPublicRegistry();
    260         add(publicNode, publicRegistry);
    261         List<ComponentRegistry> userRegistries = componentRegistryFactory.getAllUserRegistries();
    262         for (ComponentRegistry registry : userRegistries) {
    263             DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(new DisplayDataNode(registry.getName(), false));
    264             rootNode.add(userNode);
    265             add(userNode, registry);
    266         }
    267         TreeModel model = new DefaultTreeModel(rootNode);
    268         return model;
    269     }
    270 
    271     private void add(DefaultMutableTreeNode parent, ComponentRegistry registry) throws ComponentRegistryException {
    272         DefaultMutableTreeNode componentsNode = new DefaultMutableTreeNode(new DisplayDataNode("Components", false));
    273         parent.add(componentsNode);
    274         add(componentsNode, registry.getComponentDescriptions(), false, registry.getStatus());
    275 
    276         DefaultMutableTreeNode profilesNode = new DefaultMutableTreeNode(new DisplayDataNode("Profiles", false));
    277         parent.add(profilesNode);
    278         add(profilesNode, registry.getProfileDescriptions(), false, registry.getStatus());
    279 
    280         DefaultMutableTreeNode deletedCompNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Components", true));
    281         parent.add(deletedCompNode);
    282 
    283         List<ComponentDescription> deletedComponentDescriptions = registry.getDeletedComponentDescriptions();
    284         add(deletedCompNode, deletedComponentDescriptions, true, registry.getStatus());
    285 
    286         DefaultMutableTreeNode deletedProfNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Profiles", true));
    287         parent.add(deletedProfNode);
    288         List<ProfileDescription> deletedProfileDescriptions = registry.getDeletedProfileDescriptions();
    289         add(deletedProfNode, deletedProfileDescriptions, true, registry.getStatus());
    290     }
    291 
    292     private void add(DefaultMutableTreeNode parent, List<? extends BaseDescription> descs, boolean isDeleted, ComponentStatus status) {
    293         for (BaseDescription desc : descs) {
    294             DefaultMutableTreeNode child = new DefaultMutableTreeNode(new DisplayDataNode(desc.getName(), isDeleted, desc, status));
    295             parent.add(child);
    296         }
     242        public ItemEditForm(String name) {
     243            super(name);
     244            CompoundPropertyModel model = new CompoundPropertyModel(info);
     245            setModel(model);
     246
     247            TextArea descriptionArea = new TextArea("description");
     248            descriptionArea.setOutputMarkupId(true);
     249            add(descriptionArea);
     250            TextArea contentArea = new TextArea("content");
     251            contentArea.setOutputMarkupId(true);
     252            add(contentArea);
     253        }
     254    }
     255
     256    private TreeModel createDBTreeModel() throws ComponentRegistryException, UserUnauthorizedException {
     257        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new DisplayDataNode("ComponentRegistry", false));
     258        DefaultMutableTreeNode publicNode = new DefaultMutableTreeNode(new DisplayDataNode("Public", false));
     259        rootNode.add(publicNode);
     260        ComponentRegistry publicRegistry = componentRegistryFactory.getPublicRegistry();
     261        add(publicNode, publicRegistry);
     262        List<ComponentRegistry> userRegistries = componentRegistryFactory.getAllUserRegistries();
     263        for (ComponentRegistry registry : userRegistries) {
     264            DefaultMutableTreeNode userNode = new DefaultMutableTreeNode(new DisplayDataNode(registry.getName(), false));
     265            rootNode.add(userNode);
     266            add(userNode, registry);
     267        }
     268        TreeModel model = new DefaultTreeModel(rootNode);
     269        return model;
     270    }
     271
     272    private void add(DefaultMutableTreeNode parent, ComponentRegistry registry) throws ComponentRegistryException, UserUnauthorizedException {
     273        DefaultMutableTreeNode componentsNode = new DefaultMutableTreeNode(new DisplayDataNode("Components", false));
     274        parent.add(componentsNode);
     275        add(componentsNode, registry.getComponentDescriptions(), false, registry.getRegistrySpace());
     276
     277        DefaultMutableTreeNode profilesNode = new DefaultMutableTreeNode(new DisplayDataNode("Profiles", false));
     278        parent.add(profilesNode);
     279        add(profilesNode, registry.getProfileDescriptions(), false, registry.getRegistrySpace());
     280
     281        DefaultMutableTreeNode deletedCompNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Components", true));
     282        parent.add(deletedCompNode);
     283
     284        List<ComponentDescription> deletedComponentDescriptions = registry.getDeletedComponentDescriptions();
     285        add(deletedCompNode, deletedComponentDescriptions, true, registry.getRegistrySpace());
     286
     287        DefaultMutableTreeNode deletedProfNode = new DefaultMutableTreeNode(new DisplayDataNode("Deleted Profiles", true));
     288        parent.add(deletedProfNode);
     289        List<ProfileDescription> deletedProfileDescriptions = registry.getDeletedProfileDescriptions();
     290        add(deletedProfNode, deletedProfileDescriptions, true, registry.getRegistrySpace());
     291    }
     292
     293    private void add(DefaultMutableTreeNode parent, List<? extends BaseDescription> descs, boolean isDeleted, RegistrySpace space) {
     294        for (BaseDescription desc : descs) {
     295            DefaultMutableTreeNode child = new DefaultMutableTreeNode(new DisplayDataNode(desc.getName(), isDeleted, desc, space));
     296            parent.add(child);
     297        }
    297298    }
    298299}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/CMDItemInfo.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.frontend;
    22
    3 import clarin.cmdi.componentregistry.ComponentStatus;
    43import java.io.Serializable;
    54
    65import clarin.cmdi.componentregistry.MDMarshaller;
     6import clarin.cmdi.componentregistry.RegistrySpace;
    77import clarin.cmdi.componentregistry.model.BaseDescription;
    88
     
    9999
    100100   
    101     public ComponentStatus getStatus() {
    102         return displayNode.getStatus();
     101    public RegistrySpace getSpace() {
     102        return displayNode.getSpace();
    103103    }
    104104       
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/DisplayDataNode.java

    r4098 r5549  
    22
    33import clarin.cmdi.componentregistry.ComponentStatus;
     4import clarin.cmdi.componentregistry.RegistrySpace;
    45import java.io.Serializable;
    56
     
    1213    private final boolean isDeleted;
    1314    private BaseDescription desc;
    14     private final ComponentStatus status;
     15    private final RegistrySpace space;
    1516
    1617    public DisplayDataNode(String name, boolean isDeleted) {
    1718        // TODO: what is sensible default status?
    18         this(name, isDeleted, null, ComponentStatus.PRIVATE);
     19        this(name, isDeleted, null, RegistrySpace.PRIVATE);
    1920    }
    2021
    21     public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, ComponentStatus status) {
     22    public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, RegistrySpace space) {
    2223        this.name = name;
    2324        this.isDeleted = isDeleted;
    2425        this.desc = desc;
    25         this.status = status;
     26        this.space = space;
    2627    }
    2728
     
    4445    }
    4546
    46     public ComponentStatus getStatus() {
    47         return status;
     47    public RegistrySpace getSpace() {
     48        return space;
    4849    }
    4950}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/StatisticsPage.java

    r4550 r5549  
    1414import clarin.cmdi.componentregistry.ComponentRegistryException;
    1515import clarin.cmdi.componentregistry.ComponentRegistryFactory;
     16import clarin.cmdi.componentregistry.RegistrySpace;
     17import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1618import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    1719import clarin.cmdi.componentregistry.components.CMDComponentType;
     
    4042    }
    4143
    42     public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException {
     44    public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException, UserUnauthorizedException {
    4345        super(pageParameters);
    44         ComponentRegistry registry = componentRegistryFactory.getPublicRegistry();
     46        ComponentRegistry registry = componentRegistryFactory.getComponentRegistry(RegistrySpace.PUBLISHED, null, null, null);
    4547        addLinks();
    4648        displayStatistics(registry);
    4749    }
    4850
    49     private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException {
     51    private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException, UserUnauthorizedException {
    5052        List<ProfileDescription> profileList = registry.getProfileDescriptions();
    5153        RepeatingView repeating = new RepeatingView("repeating");
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentRegistryImplBase.java

    r4550 r5549  
    1414import clarin.cmdi.componentregistry.ComponentRegistry;
    1515import clarin.cmdi.componentregistry.ComponentRegistryException;
    16 import clarin.cmdi.componentregistry.DeleteFailedException;
     16import clarin.cmdi.componentregistry.ItemNotFoundException;
    1717import clarin.cmdi.componentregistry.MDMarshaller;
     18import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1819import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    19 import clarin.cmdi.componentregistry.components.CMDComponentType;
    2020import clarin.cmdi.componentregistry.components.CMDComponentSpec.Header;
    2121import clarin.cmdi.componentregistry.model.BaseDescription;
    22 import clarin.cmdi.componentregistry.model.ComponentDescription;
    2322import clarin.cmdi.componentregistry.model.ProfileDescription;
    2423
     
    3332    protected abstract MDMarshaller getMarshaller();
    3433
    35     @Override
    36     public List<ComponentDescription> getUsageInComponents(String componentId) throws ComponentRegistryException {
    37         LOG.debug("Checking usage of component {} in components", componentId);
    38         List<ComponentDescription> result = new ArrayList<ComponentDescription>();
    39         List<String> ids = getAllNonDeletedComponentIds();
    40         for (String id : ids) {
    41             CMDComponentSpec spec = getMDComponent(id);
    42             if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
    43                 LOG.debug("Component {} used in component {}", componentId, spec.getHeader().getID());
    44                 result.add(getComponentDescription(id));
    45             }
    46         }
    47         return result;
    48     }
    49 
    50     @Override
    51     public List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException {
    52         LOG.debug("Checking usage of component {} in profiles", componentId);
    53         List<ProfileDescription> result = new ArrayList<ProfileDescription>();
    54         for (String id : getAllNonDeletedProfileIds()) {
    55             CMDComponentSpec profile = getMDProfile(id);
    56             if (profile != null && hasComponentId(componentId, profile.getCMDComponent())) {
    57                 LOG.debug("Component {} used in profile {}", componentId, profile.getHeader().getID());
    58                 result.add(getProfileDescription(id));
    59             }
    60         }
    61         return result;
    62     }
     34   
    6335
    6436    /**
     
    7042    @Override
    7143    public List<ProfileDescription> getProfileDescriptionsForMetadaEditor() throws ComponentRegistryException {
    72         // TODO: Below can also be done by accepting and passing a parameter in the ProfileDescriptionDaoImpl, should have better performance
     44        // TODO: Below can also be done by accepting and passing a parameter in the ProfileDescriptionDaoImpl, should have better performance
    7345
    7446        // Get all profile descriptions
     
    7749        ArrayList<ProfileDescription> descriptions = new ArrayList<ProfileDescription>();
    7850        for (String id : descriptionsCollectionIds) {
    79             ProfileDescription profile = getProfileDescription(id);
    80             if (profile.isShowInEditor()) {
    81                 descriptions.add(profile);
     51            try {
     52                ProfileDescription profile = getProfileDescriptionAccessControlled(id);
     53                if (profile.isShowInEditor()) {
     54                    descriptions.add(profile);
     55                }
     56            } catch (UserUnauthorizedException e) {
     57            } catch (ItemNotFoundException e) {
    8258            }
     59
    8360        }
    8461        // Return filtered list
     
    10279    }
    10380
    104     protected static boolean findComponentId(String componentId, List<CMDComponentType> componentReferences) {
    105         for (CMDComponentType cmdComponent : componentReferences) {
    106             if (hasComponentId(componentId, cmdComponent)) {
    107                 return true;
    108             }
    109         }
    110         return false;
    111     }
    112 
    113     private static boolean hasComponentId(String componentId, CMDComponentType cmdComponent) {
    114         if (componentId.equals(cmdComponent.getComponentId())) {
    115             return true;
    116         } else if (findComponentId(componentId, cmdComponent.getCMDComponent())) {
    117             return true;
    118         } else {
    119             return false;
    120         }
    121     }
     81   
     82   
     83   
    12284
    12385    protected void writeXsd(CMDComponentSpec expandedSpec, OutputStream outputStream) {
     
    13597    }
    13698
    137     protected void checkStillUsed(String componentId) throws DeleteFailedException, ComponentRegistryException {
    138         for (String id : getAllNonDeletedProfileIds()) {
    139             CMDComponentSpec spec = getMDProfile(id);
    140             if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
    141                 LOG.warn("Cannot delete component {}, still used in profile {} and possibly other profiles and/or components", componentId, spec.getHeader().getID());
    142                 // Profile match - throw
    143                 throw new DeleteFailedException("Component is still in use by other components or profiles. Request component usage for details.");
    144             }
    145         }
    146 
    147         LOG.debug("Component {} is not used in any profiles", componentId);
    148 
    149         for (String id : getAllNonDeletedComponentIds()) {
    150             CMDComponentSpec spec = getMDComponent(id);
    151             if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
    152                 LOG.warn("Cannot delete component {}, still used in component {} and possibly other components", componentId, spec.getHeader().getID());
    153                 // Component match -> throw
    154                 throw new DeleteFailedException("Component is still in use by one or more other components. Request component usage for details.");
    155             }
    156         }
    157     }
    15899}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentUtils.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.impl;
    22
     3import clarin.cmdi.componentregistry.ComponentRegistryException;
    34import java.text.ParseException;
    45import java.util.ArrayList;
     
    1112import org.springframework.beans.BeanUtils;
    1213
    13 import clarin.cmdi.componentregistry.DatesHelper;
    1414import clarin.cmdi.componentregistry.model.BaseDescription;
    1515import clarin.cmdi.componentregistry.model.ComponentDescription;
     
    1818/**
    1919 * Utilities for working with {@link BaseDescription}s
    20  * 
     20 *
    2121 * @author george.georgovassilis@mpi.nl
    22  * 
     22 *
    2323 */
    2424public class ComponentUtils {
    2525
    2626    public static boolean isProfileId(String componentId) {
    27         return ("" + componentId).startsWith(ProfileDescription.PROFILE_PREFIX);
     27        return ("" + componentId).startsWith(ProfileDescription.PROFILE_PREFIX);
    2828    }
    2929
    3030    public static boolean isComponentId(String componentId) {
    31         return ("" + componentId)
    32                 .startsWith(ComponentDescription.COMPONENT_PREFIX);
     31        return ("" + componentId)
     32                .startsWith(ComponentDescription.COMPONENT_PREFIX);
    3333    }
    3434
    3535    public static void copyPropertiesFrom(BaseDescription from, BaseDescription to) {
    36         BeanUtils.copyProperties(from, to);
     36        BeanUtils.copyProperties(from, to);
    3737    }
    3838
    3939    public static Date getDate(String registrationDate) throws ParseException {
    40         return DateUtils.parseDate(registrationDate,
    41                 new String[] { DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
    42                         .getPattern() });
     40        return DateUtils.parseDate(registrationDate,
     41                new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
     42                    .getPattern()});
    4343    }
    4444
    4545    public static String createPublicHref(String href) {
    46         String result = href;
    47         if (href != null) {
    48             int index = href.indexOf("?");
    49             if (index != -1) { // strip off query params the rest should be the
    50                                // public href.
    51                 result = href.substring(0, index);
    52             }
    53         }
    54         return result;
     46        String result = href;
     47        if (href != null) {
     48            int index = href.indexOf("?");
     49            if (index != -1) { // strip off query params the rest should be the
     50                // public href.
     51                result = href.substring(0, index);
     52            }
     53        }
     54        return result;
    5555    }
    56 
    5756    /**
    58      * Compares two descriptions by the their value as returned by
    59      * {@link BaseDescription#getName()
     57     * Compares two descriptions by the their value as returned by      {@link BaseDescription#getName()
    6058     * }
    6159     */
    6260    public static final Comparator<? super BaseDescription> COMPARE_ON_NAME = new Comparator<BaseDescription>() {
    63         @Override
    64         public int compare(BaseDescription o1, BaseDescription o2) {
    65             int result = 0;
    66             if (o1.getName() != null && o2.getName() != null) {
    67                 result = o1.getName().compareToIgnoreCase(o2.getName());
    68             }
    69             if (o1.getId() != null && result == 0) {
    70                 result = o1.getId().compareTo(o2.getId());
    71             }
    72             return result;
    73         }
     61        @Override
     62        public int compare(BaseDescription o1, BaseDescription o2) {
     63            int result = 0;
     64            if (o1.getName() != null && o2.getName() != null) {
     65                result = o1.getName().compareToIgnoreCase(o2.getName());
     66            }
     67            if (o1.getId() != null && result == 0) {
     68                result = o1.getId().compareTo(o2.getId());
     69            }
     70            return result;
     71        }
    7472    };
    7573    /**
     
    7876     */
    7977    public static final Comparator<? super BaseDescription> COMPARE_ON_DATE = new Comparator<BaseDescription>() {
    80         /**
    81         * @returns 1 if o11 is older than o2, returns -1 if o1 is younger than
    82          *          o2
    83         */
    84         @Override
    85         public int compare(BaseDescription o1, BaseDescription o2) {
    86             return o1.getRegistrationDate().compareTo(o2.getRegistrationDate());
    87         }
     78        /**
     79        * @returns 1 if o11 is older than o2, returns -1 if o1 is younger than
     80         * o2
     81        */
     82        @Override
     83        public int compare(BaseDescription o1, BaseDescription o2) {
     84            return o1.getRegistrationDate().compareTo(o2.getRegistrationDate());
     85        }
    8886    };
    8987
    90     public static ProfileDescription toProfile(BaseDescription baseDescription) {
    91         if (baseDescription == null)
    92             return null;
    93         ProfileDescription copy = new ProfileDescription();
    94         BeanUtils.copyProperties(baseDescription, copy);
    95         return copy;
     88    public static ProfileDescription toProfile(BaseDescription baseDescription) throws ComponentRegistryException {
     89        if (baseDescription == null) {
     90            return null;
     91        }
     92        if (baseDescription.getId().startsWith(ProfileDescription.PROFILE_PREFIX)) {
     93            ProfileDescription copy = new ProfileDescription();
     94            BeanUtils.copyProperties(baseDescription, copy);
     95            return copy;
     96        } else {
     97            throw new ComponentRegistryException("The item is not a profile.");
     98        }
    9699    }
    97100
    98     public static ComponentDescription toComponent(BaseDescription baseDescription) {
    99         if (baseDescription == null)
    100             return null;
    101         ComponentDescription copy = new ComponentDescription();
    102         BeanUtils.copyProperties(baseDescription, copy);
    103         return copy;
     101    public static ComponentDescription toComponent(BaseDescription baseDescription) throws ComponentRegistryException {
     102        if (baseDescription == null) {
     103            return null;
     104        }
     105        if (baseDescription.getId().startsWith(ComponentDescription.COMPONENT_PREFIX)) {
     106            ComponentDescription copy = new ComponentDescription();
     107            BeanUtils.copyProperties(baseDescription, copy);
     108            return copy;
     109        } else {
     110            throw new ComponentRegistryException("The item is not a component");
     111        }
    104112    }
    105113
    106114    public static List<ProfileDescription> toProfiles(
    107             List<BaseDescription> baseDescription) {
    108         if (baseDescription == null)
    109             return null;
    110         List<ProfileDescription> list = new ArrayList<ProfileDescription>();
    111         for (BaseDescription c : baseDescription)
    112             list.add(toProfile(c));
    113         return list;
     115            List<BaseDescription> baseDescription) {
     116        if (baseDescription == null) {
     117            return null;
     118        }
     119        List<ProfileDescription> list = new ArrayList<ProfileDescription>();
     120        for (BaseDescription c : baseDescription) {
     121            try {
     122                list.add(toProfile(c));
     123            } catch (ComponentRegistryException e) {
     124            }
     125        }
     126        return list;
    114127    }
    115128
    116129    public static List<ComponentDescription> toComponents(
    117             List<BaseDescription> baseDescription) {
    118         if (baseDescription == null)
    119             return null;
    120         List<ComponentDescription> list = new ArrayList<ComponentDescription>();
    121         for (BaseDescription c : baseDescription)
    122             list.add(toComponent(c));
    123         return list;
     130            List<BaseDescription> baseDescription) {
     131        if (baseDescription == null) {
     132            return null;
     133        }
     134        List<ComponentDescription> list = new ArrayList<ComponentDescription>();
     135        for (BaseDescription c : baseDescription) {
     136            try {
     137                list.add(toComponent(c));
     138            } catch (ComponentRegistryException e) {
     139            }
     140        }
     141        return list;
    124142    }
    125 
    126143}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java

    r4098 r5549  
    1414import clarin.cmdi.componentregistry.ComponentRegistryException;
    1515import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    16 import clarin.cmdi.componentregistry.ComponentStatus;
    1716import clarin.cmdi.componentregistry.DeleteFailedException;
     17import clarin.cmdi.componentregistry.ItemNotFoundException;
    1818import clarin.cmdi.componentregistry.MDMarshaller;
    19 import clarin.cmdi.componentregistry.OwnerUser;
     19import clarin.cmdi.componentregistry.UserCredentials;
    2020import clarin.cmdi.componentregistry.UserUnauthorizedException;
    2121import clarin.cmdi.componentregistry.components.CMDComponentSpec;
     
    5454
    5555    public void submitFile(CMDItemInfo info, Principal userPrincipal)
    56             throws SubmitFailedException {
     56            throws SubmitFailedException, UserUnauthorizedException {
     57        if (userPrincipal == null) {
     58            LOG.info("Null user principal, nothings is submitted.");
     59            return;
     60        }
     61       
    5762        try {
    5863            BaseDescription originalDescription = info.getDataNode()
     
    7277                    IOUtils.toInputStream(info.getContent(), "UTF-8"), null);
    7378            checkId(originalDescription.getId(), description.getId());
    74 
    75             int result = getRegistry(userPrincipal, originalDescription, info)
    76                     .update(description, spec, userPrincipal,
    77                             info.isForceUpdate());
     79            ComponentRegistry cr = this.getRegistry(new UserCredentials(userPrincipal));
     80            int result = cr.update(description, spec, info.isForceUpdate());
    7881            if (result < 0) {
    7982                throw new SubmitFailedException(
     
    8386            throw new SubmitFailedException(e);
    8487        } catch (IOException e) {
     88            throw new SubmitFailedException(e);
     89        } catch (ItemNotFoundException e) {
    8590            throw new SubmitFailedException(e);
    8691        }
     
    109114        BaseDescription desc = info.getDataNode().getDescription();
    110115        try {
    111             deleteFromRegistry(userPrincipal, desc, info);
     116            this.deleteFromRegistry(userPrincipal, desc, info);
    112117            LOG.info("Deleted item: " + id);
    113118        } catch (IOException e) {
     
    119124        } catch (ComponentRegistryException e) {
    120125            throw new SubmitFailedException(e);
     126        } catch (ItemNotFoundException e) {
     127            throw new SubmitFailedException(e);
    121128        }
    122129
     
    125132    private void deleteFromRegistry(Principal userPrincipal,
    126133            BaseDescription desc, CMDItemInfo info) throws IOException,
    127             UserUnauthorizedException, ComponentRegistryException {
    128         ComponentRegistry registry = getRegistry(userPrincipal, desc, info);
     134            UserUnauthorizedException, ComponentRegistryException, ItemNotFoundException {
     135       
     136        if (userPrincipal == null) {
     137           LOG.info("Bnull user principal, nothing is deleted");
     138           return;
     139        }
     140       
     141        ComponentRegistry registry = this.getRegistry(new UserCredentials(userPrincipal));
    129142        LOG.info("Deleting item: " + desc);
    130143        if (desc.isProfile()) {
    131             registry.deleteMDProfile(desc.getId(), userPrincipal);
     144            registry.deleteMDProfile(desc.getId());
    132145        } else {
    133             registry.deleteMDComponent(desc.getId(), userPrincipal,
    134                     info.isForceUpdate());
     146            registry.deleteMDComponent(desc.getId(), info.isForceUpdate());
    135147        }
    136148    }
    137149
    138     private ComponentRegistry getRegistry(Principal userPrincipal,
    139             BaseDescription desc, CMDItemInfo info) {
    140         ComponentRegistry registry = componentRegistryFactory
    141                 .getPublicRegistry();
    142         // TODO: More generic check
    143         if (info.getStatus() == ComponentStatus.PRIVATE /*
    144                                                          * || info.getStatus()
    145                                                          * == ComponentStatus.
    146                                                          * DEVELOPMENT
    147                                                          */) {
    148             registry = componentRegistryFactory.getOtherUserComponentRegistry(
    149                     userPrincipal, info.getStatus(),
    150                     new OwnerUser(Integer.parseInt(desc.getUserId())));
    151         }
    152         return registry;
    153     }
     150    private ComponentRegistry getRegistry(UserCredentials credentials) throws UserUnauthorizedException{
     151        return componentRegistryFactory.getBaseRegistry(credentials);
     152        }
     153   
    154154}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java

    r4190 r5549  
    44import clarin.cmdi.componentregistry.ComponentRegistry;
    55import clarin.cmdi.componentregistry.ComponentRegistryException;
    6 import clarin.cmdi.componentregistry.ComponentStatus;
    76import clarin.cmdi.componentregistry.Configuration;
    87import clarin.cmdi.componentregistry.DeleteFailedException;
     8import clarin.cmdi.componentregistry.ItemNotFoundException;
    99import clarin.cmdi.componentregistry.MDMarshaller;
    1010import clarin.cmdi.componentregistry.Owner;
    1111import clarin.cmdi.componentregistry.OwnerUser;
     12import clarin.cmdi.componentregistry.RegistrySpace;
    1213import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1314import clarin.cmdi.componentregistry.components.CMDComponentSpec;
     15import clarin.cmdi.componentregistry.components.CMDComponentType;
    1416import clarin.cmdi.componentregistry.impl.ComponentRegistryImplBase;
    1517import clarin.cmdi.componentregistry.impl.ComponentUtils;
     
    1719import clarin.cmdi.componentregistry.model.Comment;
    1820import clarin.cmdi.componentregistry.model.ComponentDescription;
     21import clarin.cmdi.componentregistry.model.Group;
    1922import clarin.cmdi.componentregistry.model.ProfileDescription;
    2023import clarin.cmdi.componentregistry.model.RegistryUser;
     
    3033import java.io.UnsupportedEncodingException;
    3134import java.security.Principal;
    32 import java.text.ParseException;
    3335import java.util.ArrayList;
    3436import java.util.Calendar;
     
    5153 * Implementation of ComponentRegistry that uses Database Acces Objects for
    5254 * accessing the registry (ergo: a database implementation)
    53  * 
     55 *
    5456 * @author Twan Goosen <twan.goosen@mpi.nl>
    5557 * @author George.Georgovassilis@mpi.nl
     
    5860public class ComponentRegistryDbImpl extends ComponentRegistryImplBase implements ComponentRegistry {
    5961
    60         private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryDbImpl.class);
    61         private Owner registryOwner;
    62         private ComponentStatus registryStatus;
    63         @Autowired
    64         private Configuration configuration;
    65         @Autowired
    66         @Qualifier("componentsCache")
    67         private CMDComponentSpecCache componentsCache;
    68         @Autowired
    69         @Qualifier("profilesCache")
    70         private CMDComponentSpecCache profilesCache;
    71         // DAO's
    72         @Autowired
    73         private ComponentDao componentDao;
    74         @Autowired
    75         private UserDao userDao;
    76         @Autowired
    77         private CommentsDao commentsDao;
    78         @Autowired
    79         private MDMarshaller marshaller;
    80         @Autowired
    81         private GroupService groupService;
    82 
    83         /**
    84          * Default constructor, to use this as a (spring) bean. The public registry
    85          * by default. Use setStatus() and setOwner() to make it another kind of
    86          * registry.
    87          *
    88          * @see setUser
    89          */
    90         public ComponentRegistryDbImpl() throws TransformerException {
    91                 this.registryStatus = ComponentStatus.PUBLISHED;
    92         }
    93 
    94         /**
    95          * Creates a new ComponentRegistry (either public or not) for the provided
    96          * user. Only use for test and/or make sure to inject all dao's and other
    97          * services
    98          *
    99          * @param userId
    100          *            User id of the user to create registry for. Pass null for
    101          *            public
    102          */
    103         public ComponentRegistryDbImpl(ComponentStatus status, Owner owner) {
    104                 this.registryStatus = status;
    105                 this.registryOwner = owner;
    106         }
    107 
    108         @Override
    109         public List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException {
    110                 try {
    111                         switch (registryStatus) {
    112                         // TODO: support other status types
    113                         case PRIVATE:
    114                                 if (registryOwner == null) {
    115                                         throw new ComponentRegistryException("Private workspace without owner!");
    116                                 }
    117                                 // TODO: Support group space
    118                                 return ComponentUtils.toProfiles(componentDao.getUserspaceProfiles(registryOwner.getId()));
    119                         case PUBLISHED:
    120                                 return ComponentUtils.toProfiles(componentDao.getPublicProfileDescriptions());
    121                         default:
    122                                 throw new ComponentRegistryException("Unsupported status type" + registryStatus);
    123                         }
    124                 } catch (DataAccessException ex) {
    125                         throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
    126                 }
    127         }
    128 
    129         @Override
    130         public ProfileDescription getProfileDescription(String id) throws ComponentRegistryException {
    131                 try {
    132                         return ComponentUtils.toProfile(componentDao.getByCmdId(id, getUserId()));
    133                 } catch (DataAccessException ex) {
    134                         throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
    135                 }
    136         }
    137 
    138         @Override
    139         public List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException {
    140                 try {
    141                         if (isPublic()) {
    142                                 return ComponentUtils.toComponents(componentDao.getPublicComponentDescriptions());
    143                         } else {
    144                                 return ComponentUtils.toComponents(componentDao.getUserspaceComponents(getUserId()));
    145                         }
    146                 } catch (DataAccessException ex) {
    147                         throw new ComponentRegistryException("Database access error while trying to get component descriptions", ex);
    148                 }
    149         }
    150 
    151         @Override
    152         public ComponentDescription getComponentDescription(String id) throws ComponentRegistryException {
    153                 try {
    154                         return ComponentUtils.toComponent(componentDao.getByCmdId(id, getUserId()));
    155                 } catch (DataAccessException ex) {
    156                         throw new ComponentRegistryException("Database access error while trying to get component description", ex);
    157                 }
    158         }
    159 
    160         @Override
    161         public List<Comment> getCommentsInProfile(String profileId, Principal principal) throws ComponentRegistryException {
    162                 try {
    163                         if (componentDao.isInRegistry(profileId, getUserId())) {
    164                                 final List<Comment> commentsFromProfile = commentsDao.getCommentsFromComponent(profileId);
    165                                 setCanDeleteInComments(commentsFromProfile, principal);
    166                                 return commentsFromProfile;
    167                         } else {
    168                                 // Profile does not exist (at least not in this registry)
    169                                 throw new ComponentRegistryException("Profile " + profileId + " does not exist in specified registry");
    170                         }
    171                 } catch (DataAccessException ex) {
    172                         throw new ComponentRegistryException(
    173                                         "Database access error while trying to get list of comments from profile", ex);
    174                 }
    175         }
    176 
    177         @Override
    178         public Comment getSpecifiedCommentInProfile(String profileId, String commentId, Principal principal)
    179                         throws ComponentRegistryException {
    180                 try {
    181                         Comment comment = commentsDao.findOne(Long.parseLong(commentId));
    182                         if (comment != null && profileId.equals(comment.getComponentId())
    183                                         && componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
    184                                 setCanDeleteInComments(Collections.singleton(comment), principal);
    185                                 return comment;
    186                         } else {
    187                                 // Comment exists in DB, but profile is not in this registry
    188                                 throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
    189                         }
    190                 } catch (DataAccessException ex) {
    191                         throw new ComponentRegistryException("Database access error while trying to get comment from profile", ex);
    192                 }
    193         }
    194 
    195         @Override
    196         public List<Comment> getCommentsInComponent(String componentId, Principal principal)
    197                         throws ComponentRegistryException {
    198                 try {
    199                         if (componentDao.isInRegistry(componentId, getUserId())) {
    200                                 final List<Comment> commentsFromComponent = commentsDao.getCommentsFromComponent(componentId);
    201                                 setCanDeleteInComments(commentsFromComponent, principal);
    202                                 return commentsFromComponent;
    203                         } else {
    204                                 // Component does not exist (at least not in this registry)
    205                                 throw new ComponentRegistryException("Component " + componentId
    206                                                 + " does not exist in specified registry");
    207                         }
    208                 } catch (DataAccessException ex) {
    209                         throw new ComponentRegistryException(
    210                                         "Database access error while trying to get list of comments from component", ex);
    211                 }
    212         }
    213 
    214         @Override
    215         public Comment getSpecifiedCommentInComponent(String componentId, String commentId, Principal principal)
    216                         throws ComponentRegistryException {
    217                 try {
    218                         Comment comment = commentsDao.findOne(Long.parseLong(commentId));
    219                         if (comment != null && componentId.equals(comment.getComponentId().toString())
    220                                         && componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
    221                                 setCanDeleteInComments(Collections.singleton(comment), principal);
    222                                 return comment;
    223                         } else {
    224                                 // Comment does not exists in DB or component is not in this
    225                                 // registry
    226                                 throw new ComponentRegistryException("Comment " + commentId
    227                                                 + " cannot be found in specified registry for specified component");
    228                         }
    229                 } catch (DataAccessException ex) {
    230                         throw new ComponentRegistryException("Database access error while trying to get comment from component", ex);
    231                 }
    232         }
    233 
    234         /**
    235          * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all
    236          * comments in the provided collection for the perspective of the specified
    237          * principal. Comment owners (determined by {@link Comment#getUserId() }) and
    238          * admins can delete, others cannot.
    239          *
    240          * @param comments
    241          *            comments to configure
    242          * @param principal
    243          *            user to configure for
    244          * @see Comment#isCanDelete()
    245          */
    246         private void setCanDeleteInComments(Collection<Comment> comments, Principal principal) {
    247                 if (principal != null && principal.getName() != null) {
    248                         final RegistryUser registryUser = userDao.getByPrincipalName(principal.getName());
    249                         final long registryUserId = registryUser == null ? -1 : registryUser.getId();
    250                         final boolean isAdmin = registryUser != null && configuration.isAdminUser(principal);
    251                         for (Comment comment : comments) {
    252                                 comment.setCanDelete(isAdmin || comment.getUserId() == registryUserId);
    253                         }
    254                 }
    255         }
    256 
    257         @Override
    258         public CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException {
    259                 if (inWorkspace(id)||canCurrentUserAccessDescription(id)) {
    260                         CMDComponentSpec result = profilesCache.get(id);
    261                         if (result == null && !profilesCache.containsKey(id)) {
    262                                 result = getUncachedMDProfile(id);
    263                                 profilesCache.put(id, result);
    264                         }
    265                         return result;
    266                 } else {
    267                         // May exist, but not in this workspace
    268                         LOG.debug("Could not find profile '{}' in registry '{}'", new Object[] { id, this.toString() });
    269                         return null;
    270                 }
    271         }
    272 
    273         public CMDComponentSpec getUncachedMDProfile(String id) throws ComponentRegistryException {
    274                 try {
    275                         return getUncachedMDComponent(id, componentDao);
    276                 } catch (DataAccessException ex) {
    277                         throw new ComponentRegistryException("Database access error while trying to get profile", ex);
    278                 }
    279         }
    280 
    281         @Override
    282         public CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException {
    283                 if (inWorkspace(id)||canCurrentUserAccessDescription(id)) {
    284                         CMDComponentSpec result = componentsCache.get(id);
    285                         if (result == null && !componentsCache.containsKey(id)) {
    286                                 result = getUncachedMDComponent(id);
    287                                 componentsCache.put(id, result);
    288                         }
    289                         return result;
    290                 } else {
    291                         // May exist, but not in this workspace
    292                         LOG.info("Could not find component '{}' was in registry '{}'", new Object[] { id, this.toString() });
    293                         return null;
    294                 }
    295         }
    296 
    297         public CMDComponentSpec getUncachedMDComponent(String id) throws ComponentRegistryException {
    298                 try {
    299                         return getUncachedMDComponent(id, componentDao);
    300                 } catch (DataAccessException ex) {
    301                         throw new ComponentRegistryException("Database access error while trying to get component", ex);
    302                 }
    303         }
    304 
    305         @Override
    306         public int register(BaseDescription description, CMDComponentSpec spec) {
    307                 enrichSpecHeader(spec, description);
    308                 try {
    309                         String xml = componentSpecToString(spec);
    310                         // Convert principal name to user record id
    311                         Number uid = convertUserInDescription(description);
    312                         componentDao.insertDescription(description, xml, isPublic(), uid);
    313                         invalidateCache(description);
    314                         return 0;
    315                 } catch (DataAccessException ex) {
    316                         LOG.error("Database error while registering component", ex);
    317                         return -1;
    318                 } catch (JAXBException ex) {
    319                         LOG.error("Error while registering component", ex);
    320                         return -2;
    321                 } catch (UnsupportedEncodingException ex) {
    322                         LOG.error("Error while registering component", ex);
    323                         return -3;
    324                 }
    325         }
    326 
    327         @Override
    328         public int registerComment(Comment comment, String principalName) throws ComponentRegistryException {
    329                 try {
    330                         if (comment.getComponentId() != null && componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
    331                                 // Convert principal name to user record id
    332                                 Number uid = convertUserIdInComment(comment, principalName);
    333                                 // Set date to current date
    334                                 comment.setCommentDate(new Date());
    335                                 comment.setUserId(uid.longValue());
    336                                 commentsDao.saveAndFlush(comment);
    337                         } else {
    338                                 throw new ComponentRegistryException(
    339                                                 "Cannot insert comment into this registry. Unknown profileId or componentId");
    340                         }
    341                         return 0;
    342                 } catch (DataAccessException ex) {
    343                         LOG.error("Database error while registering component", ex);
    344                         return -1;
    345                 }
    346         }
    347 
    348         /**
    349          * Calling service sets user id to principle. Our task is to convert this to
    350          * an id for later reference. If none is set and this is a user's workspace,
    351          * set from that user's id.
    352          *
    353          * It also sets the name in the description according to the display name in
    354          * the database.
    355          *
    356          * @param description
    357          *            Description containing principle name as userId
    358          * @return Id (from database)
    359          * @throws DataAccessException
    360          */
    361         private Number convertUserInDescription(BaseDescription description) throws DataAccessException {
    362                 Number uid = null;
    363                 String name = null;
    364                 if (description.getUserId() != null) {
    365                         RegistryUser user = userDao.getByPrincipalName(description.getUserId());
    366                         if (user != null) {
    367                                 uid = user.getId();
    368                                 name = user.getName();
    369                         }
    370                 } else {
    371                         uid = getUserId(); // this can be null as well
    372                 }
    373                 if (uid != null) {
    374                         description.setUserId(uid.toString());
    375                 }
    376                 if (name != null) {
    377                         description.setCreatorName(name);
    378                 }
    379                 return uid;
    380         }
    381 
    382         /**
    383          * Calling service sets user id to principle. Our task is to convert this to
    384          * an id for later reference. If none is set and this is a user's workspace,
    385          * set from that user's id.
    386          *
    387          * @param comment
    388          *            Comment containing principle name as userId
    389          * @return Id (from database)
    390          * @throws DataAccessException
    391          */
    392         private Number convertUserIdInComment(Comment comment, String principalName) throws DataAccessException,
    393                         ComponentRegistryException {
    394                 if (principalName != null) {
    395                         RegistryUser user = userDao.getByPrincipalName(principalName);
    396                         if (user != null) {
    397                                 Long id = user.getId();
    398                                 if (id != null) {
    399                                         // Set user id in comment for convenience of calling method
    400                                         comment.setUserId(id);
    401                                         // Set name to user's preferred display name
    402                                         comment.setUserName(user.getName());
    403                                         return id;
    404                                 } else {
    405                                         throw new ComponentRegistryException("Cannot find user with principal name: " + principalName);
    406                                 }
    407                         }
    408                 }
    409                 return null;
    410         }
    411 
    412         @Override
    413         public int update(BaseDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate) {
    414                 try {
    415                         checkAuthorisation(description, principal);
    416                         checkAge(description, principal);
    417                         // For public components, check if used in other components or
    418                         // profiles (unless forced)
    419                         if (!forceUpdate && this.isPublic() && !description.isProfile()) {
    420                                 checkStillUsed(description.getId());
    421                         }
    422                         componentDao.updateDescription(getIdForDescription(description), description, componentSpecToString(spec));
    423                         invalidateCache(description);
    424                         return 0;
    425                 } catch (JAXBException ex) {
    426                         LOG.error("Error while updating component", ex);
    427                         return -1;
    428                 } catch (UnsupportedEncodingException ex) {
    429                         LOG.error("Error while updating component", ex);
    430                         return -1;
    431                 } catch (IllegalArgumentException ex) {
    432                         LOG.error("Error while updating component", ex);
    433                         return -1;
    434                 } catch (UserUnauthorizedException e) {
    435                         LOG.error("Error while updating component", e);
    436                         return -1;
    437                 } catch (DeleteFailedException e) {
    438                         LOG.error("Error while updating component", e);
    439                         return -1;
    440                 } catch (ComponentRegistryException e) {
    441                         LOG.error("Error while updating component", e);
    442                         return -1;
    443                 }
    444         }
    445 
    446         @Override
    447         public int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal) {
    448                 int result = 0;
    449                 if (!isPublic()) { // if already in public workspace there is nothing
    450                         // todo
    451                         desc.setHref(ComponentUtils.createPublicHref(desc.getHref()));
    452                         Number id = getIdForDescription(desc);
    453                         try {
    454                                 // Update description & content
    455                                 componentDao.updateDescription(id, desc, componentSpecToString(spec));
    456                                 // Set to public
    457                                 componentDao.setPublished(id, true);
    458                         } catch (DataAccessException ex) {
    459                                 LOG.error("Database error while updating component", ex);
    460                                 return -1;
    461                         } catch (JAXBException ex) {
    462                                 LOG.error("Error while updating component", ex);
    463                                 return -2;
    464                         } catch (UnsupportedEncodingException ex) {
    465                                 LOG.error("Error while updating component", ex);
    466                                 return -3;
    467                         }
    468                 }
    469                 return result;
    470         }
    471 
    472         @Override
    473         public void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException {
    474                 CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
    475                 writeXml(expandedSpec, output);
    476         }
    477 
    478         @Override
    479         public void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException {
    480                 CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
    481                 writeXsd(expandedSpec, outputStream);
    482         }
    483 
    484         @Override
    485         public void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException {
    486                 CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
    487                 writeXml(expandedSpec, output);
    488         }
    489 
    490         @Override
    491         public void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException {
    492                 CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
    493                 writeXsd(expandedSpec, outputStream);
    494         }
    495 
    496         @Override
    497         public void deleteMDProfile(String profileId, Principal principal) throws UserUnauthorizedException,
    498                         DeleteFailedException, ComponentRegistryException {
    499                 ProfileDescription desc = getProfileDescription(profileId);
    500                 if (desc != null) {
    501                         try {
    502                                 checkAuthorisation(desc, principal);
    503                                 checkAge(desc, principal);
    504                                 componentDao.setDeleted(desc, true);
    505                                 invalidateCache(desc);
    506                         } catch (DataAccessException ex) {
    507                                 throw new DeleteFailedException("Database access error while trying to delete profile", ex);
    508                         }
    509                 }
    510         }
    511 
    512         @Override
    513         public void deleteMDComponent(String componentId, Principal principal, boolean forceDelete)
    514                         throws UserUnauthorizedException, DeleteFailedException, ComponentRegistryException {
    515                 BaseDescription desc = componentDao.getByCmdId(componentId);
    516                 if (desc != null) {
    517                         try {
    518                                 checkAuthorisation(desc, principal);
    519                                 checkAge(desc, principal);
    520 
    521                                 if (!forceDelete) {
    522                                         checkStillUsed(componentId);
    523                                 }
    524                                 componentDao.setDeleted(desc, true);
    525                                 invalidateCache(desc);
    526                         } catch (DataAccessException ex) {
    527                                 throw new DeleteFailedException("Database access error while trying to delete component", ex);
    528                         }
    529                 }
    530         }
    531 
    532         /**
    533          *
    534          * @return whether this is the public registry
    535          * @deprecated use {@link #getStatus() } to check if this is the
    536          *             {@link ComponentStatus#PUBLISHED public registry}
    537          */
    538         @Override
    539         @Deprecated
    540         public boolean isPublic() {
    541                 return registryStatus == ComponentStatus.PUBLISHED;
    542         }
    543 
    544         /**
    545          * @return The user id, or null if there is no owner or it is not a user.
    546          */
    547         private Number getUserId() {
    548                 if (registryOwner instanceof OwnerUser) {
    549                         return registryOwner.getId();
    550                 } else {
    551                         return null;
    552                 }
    553         }
    554 
    555         @Override
    556         public Owner getOwner() {
    557                 return registryOwner;
    558         }
    559 
    560         /**
    561          * Sets status and owner of this registry
    562          *
    563          * @param status
    564          *            new status for registry
    565          * @param owner
    566          *            new owner for registry
    567          */
    568         public void setStatus(ComponentStatus status, Owner owner) {
    569                 setStatus(status);
    570                 this.registryOwner = owner;
    571         }
    572 
    573         public void setStatus(ComponentStatus status) {
    574                 this.registryStatus = status;
    575         }
    576 
    577         @Override
    578         public ComponentStatus getStatus() {
    579                 return registryStatus;
    580         }
    581 
    582         private void invalidateCache(BaseDescription description) {
    583                 if (description.isProfile()) {
    584                         profilesCache.remove(description.getId());
    585                 } else {
    586                         componentsCache.remove(description.getId());
    587                 }
    588         }
    589 
    590         /**
    591          * Looks up description on basis of CMD Id. This will also check if such a
    592          * record even exists.
    593          *
    594          * @param description
    595          *            Description to look up
    596          * @return Database id for description
    597          * @throws IllegalArgumentException
    598          *             If description with non-existing id is passed
    599          */
    600         private Number getIdForDescription(BaseDescription description) throws IllegalArgumentException {
    601                 Number dbId = null;
    602                 try {
    603                         dbId = componentDao.getDbId(description.getId());
    604                 } catch (DataAccessException ex) {
    605                         LOG.error("Error getting dbId for component with id " + description.getId(), ex);
    606                 }
    607                 if (dbId == null) {
    608                         throw new IllegalArgumentException("Could not get database Id for description");
    609                 } else {
    610                         return dbId;
    611                 }
    612         }
    613 
    614         private String componentSpecToString(CMDComponentSpec spec) throws UnsupportedEncodingException, JAXBException {
    615                 ByteArrayOutputStream os = new ByteArrayOutputStream();
    616                 getMarshaller().marshal(spec, os);
    617                 String xml = os.toString("UTF-8");
    618                 return xml;
    619         }
    620 
    621         private CMDComponentSpec getUncachedMDComponent(String id, ComponentDao dao) {
    622                 String xml = dao.getContent(false, id);
    623                 if (xml != null) {
    624                         try {
    625                                 InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    626                                 return getMarshaller().unmarshal(CMDComponentSpec.class, is, null);
    627 
    628                         } catch (JAXBException ex) {
    629                                 LOG.error("Error while unmarshalling", ex);
    630                         } catch (UnsupportedEncodingException ex) {
    631                                 LOG.error("Exception while reading XML from database", ex);
    632                         }
    633                 }
    634                 return null;
    635         }
    636 
    637         private void checkAuthorisation(BaseDescription desc, Principal principal) throws UserUnauthorizedException {
    638                 if (!isOwnerOfDescription(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
    639                         throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
    640                                         + "' is not the creator (nor an administrator) of the "
    641                                         + (desc.isProfile() ? "profile" : "component") + "(" + desc + ").");
    642                 }
    643         }
    644 
    645         private void checkAuthorisationComment(Comment desc, Principal principal) throws UserUnauthorizedException {
    646                 if (!isOwnerOfComment(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
    647                         throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
    648                                         + "' is not the creator (nor an administrator) of the " + (desc.getId()) + "(" + desc + ").");
    649                 }
    650         }
    651 
    652         private boolean isOwnerOfDescription(BaseDescription desc, String principalName) {
    653                 String owner = componentDao.getOwnerPrincipalName(getIdForDescription(desc));
    654                 return owner != null // If owner is null, no one can be owner
    655                                 && principalName.equals(owner);
    656         }
    657 
    658         private boolean isOwnerOfComment(Comment com, String principalName) {
    659                 RegistryUser owner = commentsDao.getOwnerOfComment(Integer.parseInt(com.getId()));
    660                 return owner != null // If owner is null, no one can be owner
    661                                 && principalName.equals(owner.getPrincipalName());
    662         }
    663 
    664         private void checkAge(BaseDescription desc, Principal principal) throws DeleteFailedException {
    665                 if (isPublic() && !configuration.isAdminUser(principal)) {
    666                         Date regDate = desc.getRegistrationDate();
    667                         Calendar calendar = Calendar.getInstance();
    668                         calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
    669                         if (regDate.before(calendar.getTime())) { // More then month old
    670                                 throw new DeleteFailedException(
    671                                                 "The "
    672                                                                 + (desc.isProfile() ? "Profile" : "Component")
    673                                                                 + " 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.");
    674                         }
    675                 }
    676         }
    677 
    678         private boolean inWorkspace(String cmdId) {
    679                 if (isPublic()) {
    680                         return componentDao.isPublic(cmdId);
    681                 } else {
    682                         return componentDao.isInUserSpace(cmdId, getUserId());
    683                 }
    684         }
    685 
    686         @Override
    687         public String getName() {
    688                 if (isPublic()) {
    689                         return ComponentRegistry.PUBLIC_NAME;
    690                 } else {
    691                         RegistryUser u = userDao.findOne(getUserId().longValue());
    692                         return "Registry of " + u.getName();
    693                 }
    694         }
    695 
    696         private boolean canCurrentUserAccessDescription(String cmdId) {
    697                 if (cmdId == null)
    698                         return false;
    699                 Number userId = getUserId();
    700                 if (userId == null)
    701                         return false;
    702                 RegistryUser user = userDao.findOne(userId.longValue());
    703                 if (user == null)
    704                         return false;
    705                 BaseDescription description = componentDao.getByCmdId(cmdId);
    706                 if (description == null)
    707                         return false;
    708                 return groupService.canUserAccessComponentEitherOnHisOwnOrThroughGroupMembership(user, description);
    709         }
    710 
    711         @Override
    712         public List<ProfileDescription> getDeletedProfileDescriptions() {
    713                 return ComponentUtils.toProfiles(componentDao.getDeletedDescriptions(getUserId()));
    714         }
    715 
    716         @Override
    717         public List<ComponentDescription> getDeletedComponentDescriptions() {
    718                 return ComponentUtils.toComponents(componentDao.getDeletedDescriptions(getUserId()));
    719         }
    720 
    721         @Override
    722         public void deleteComment(String commentId, Principal principal) throws IOException, ComponentRegistryException,
    723                         UserUnauthorizedException, DeleteFailedException {
    724                 try {
    725                         Comment comment = commentsDao.findOne(Long.parseLong(commentId));
    726                         if (comment != null
    727                                         // Comment must have an existing (in this registry)
    728                                         // componentId or profileId
    729                                         && comment.getComponentId() != null
    730                                         && componentDao.isInRegistry(comment.getComponentId(), getUserId())) {
    731                                 checkAuthorisationComment(comment, principal);
    732                                 commentsDao.delete(comment);
    733                         } else {
    734                                 // Comment exists in DB, but component is not in this registry
    735                                 throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
    736                         }
    737                 } catch (DataAccessException ex) {
    738                         throw new DeleteFailedException("Database access error while trying to delete component", ex);
    739                 } catch (NumberFormatException ex) {
    740                         throw new DeleteFailedException("Illegal comment ID, cannot parse integer", ex);
    741                 }
    742         }
    743 
    744         @Override
    745         public CMDComponentSpecExpander getExpander() {
    746                 return new CMDComponentSpecExpanderDbImpl(this);
    747         }
    748 
    749         @Override
    750         protected MDMarshaller getMarshaller() {
    751                 return marshaller;
    752         }
    753 
    754         @Override
    755         public String toString() {
    756                 return getName();
    757         }
    758 
    759         @Override
    760         public List<ComponentDescription> getComponentDescriptionsInGroup(String principalName, String groupId)
    761                         throws ComponentRegistryException {
    762                 List<String> componentIds = groupService.getComponentIdsInGroup(Long.parseLong(groupId));
    763                 List<ComponentDescription> components = new ArrayList<ComponentDescription>();
    764                 for (String id : componentIds) {
    765                         BaseDescription description = componentDao.getByCmdId(id);
    766                         components.add(ComponentUtils.toComponent(description));
    767                 }
    768                 return components;
    769         }
    770 
    771         @Override
    772         public List<ProfileDescription> getProfileDescriptionsForMetadaEditor(String groupId)
    773                         throws ComponentRegistryException {
    774                 List<String> componentIds = groupService.getProfileIdsInGroup(Long.parseLong(groupId));
    775                 List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
    776                 for (String id : componentIds) {
    777                         ProfileDescription profile = getProfileDescription(id);
    778                         if (profile != null)
    779                                 profiles.add(profile);
    780                 }
    781                 return profiles;
    782         }
    783 
    784         @Override
    785         public List<ProfileDescription> getProfileDescriptionsInGroup(String groupId) throws ComponentRegistryException {
    786                 List<String> componentIds = groupService.getProfileIdsInGroup(Long.parseLong(groupId));
    787                 List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
    788                 for (String id : componentIds) {
    789                         ProfileDescription profile = getProfileDescription(id);
    790                         if (profile != null)
    791                                 profiles.add(profile);
    792                 }
    793                 return profiles;
    794         }
    795 
    796         @Override
    797         public List<String> getAllNonDeletedProfileIds() {
    798                 return componentDao.getAllNonDeletedProfileIds();
    799         }
    800 
    801         @Override
    802         public List<String> getAllNonDeletedComponentIds() {
    803                 return componentDao.getAllNonDeletedComponentIds();
    804         }
     62    private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryDbImpl.class);
     63    private Owner registryOwner;
     64    private RegistrySpace registrySpace;
     65    private Number groupId;
     66    @Autowired
     67    private Configuration configuration;
     68    @Autowired
     69    @Qualifier("componentsCache")
     70    private CMDComponentSpecCache componentsCache;
     71    @Autowired
     72    @Qualifier("profilesCache")
     73    private CMDComponentSpecCache profilesCache;
     74    // DAO's
     75    @Autowired
     76    private ComponentDao componentDao;
     77    @Autowired
     78    private UserDao userDao;
     79    @Autowired
     80    private CommentsDao commentsDao;
     81    @Autowired
     82    private MDMarshaller marshaller;
     83    @Autowired
     84    private GroupService groupService;
     85
     86   
     87    //
     88    /**
     89     * Default constructor, to use this as a (spring) bean. The public registry
     90     * by default. Use setRegistryStatus(), setRegistryOwner(), setGroupId() to make it another kind of
     91     * registry.
     92     *
     93     *
     94     */
     95    public ComponentRegistryDbImpl() throws TransformerException {
     96        this.registrySpace = RegistrySpace.PUBLISHED;
     97    }
     98
     99
     100    @Override
     101    public Owner getRegistryOwner() {
     102        return this.registryOwner;
     103    }
     104   
     105    @Override
     106    public void setRegistryOwner(Owner registryOwner) {
     107        this.registryOwner = registryOwner;
     108    }
     109   
     110   
     111    @Override
     112    public RegistrySpace getRegistrySpace() {
     113        return this.registrySpace;
     114    }
     115
     116    @Override
     117    public void setRegistrySpace(RegistrySpace registrySpace) {
     118        this.registrySpace = registrySpace;
     119    }
     120
     121    @Override
     122    public Number getGroupId() {
     123        return this.groupId;
     124    }
     125   
     126    @Override
     127    public void setGroupId(Number groupId) {
     128        this.groupId = groupId;
     129    }
     130   
     131    @Override
     132    public Number getBaseDescriptionOwnerId(String cmdId){
     133        BaseDescription bd = componentDao.getByCmdId(cmdId);
     134        return bd.getDbUserId();
     135    }
     136   
     137    @Override
     138    public  List<Number> getItemGroups(String cmdId){
     139        List<Group> groups = groupService.getGroupsTheItemIsAMemberOf(cmdId);
     140        List<Number> result = new ArrayList<Number>();
     141        if (groups != null) {
     142            for (Group group: groups) {
     143                result.add(group.getId());
     144            }
     145        }
     146        return result;
     147    }
     148   
     149    /**
     150     * @return The user id, or null if there is no owner or it is not a user.
     151     */
     152    private Number getUserId() {
     153        if (registryOwner instanceof OwnerUser) {
     154            return registryOwner.getId();
     155        } else {
     156            return null;
     157        }
     158    }
     159   
     160    @Override
     161    public List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException, UserUnauthorizedException {
     162        try {
     163            switch (registrySpace) {
     164                case PRIVATE:
     165                    if (registryOwner == null) {
     166                        throw new ComponentRegistryException("Private workspace without owner!");
     167                    }
     168                    return ComponentUtils.toProfiles(componentDao.getPrivateBaseDescriptions(registryOwner.getId(), ProfileDescription.PROFILE_PREFIX));
     169                case GROUP:
     170                    return this.getProfileDescriptionsInGroup(groupId);
     171                case PUBLISHED:
     172                    return ComponentUtils.toProfiles(componentDao.getPublicBaseDescriptions(ProfileDescription.PROFILE_PREFIX));
     173                default:
     174                    throw new ComponentRegistryException("Unsupported status type" + registrySpace);
     175            }
     176        } catch (DataAccessException ex) {
     177            throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
     178        }
     179    }
     180
     181    @Override
     182    public Boolean isItemPublic(String id) throws ItemNotFoundException{
     183        BaseDescription desc = componentDao.getByCmdId(id);
     184        if (desc == null) {
     185            String idS = (id == null) ? "null" : id;
     186            throw new ItemNotFoundException("The component with the id " + idS+ "is not found in the database.");
     187        }
     188        return desc.isPublic();
     189    }
     190
     191    @Override
     192    public ProfileDescription getProfileDescriptionAccessControlled(String id) throws ItemNotFoundException, UserUnauthorizedException, ComponentRegistryException {
     193        boolean hasAccess = this.canCurrentUserAccessDescription(id);
     194        if (hasAccess) {
     195            try {
     196                return ComponentUtils.toProfile(componentDao.getByCmdId(id));
     197            } catch (DataAccessException ex) {
     198                throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
     199            }
     200        } else {
     201            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
     202        }
     203    }
     204
     205    private ProfileDescription getProfileDescription(String id) throws ComponentRegistryException {
     206        try {
     207            return ComponentUtils.toProfile(componentDao.getByCmdId(id));
     208        } catch (DataAccessException ex) {
     209            throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
     210        }
     211
     212    }
     213
     214    @Override
     215    public List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException, UserUnauthorizedException {
     216        try {
     217            switch (registrySpace) {
     218                case PRIVATE:
     219                    if (registryOwner == null) {
     220                        throw new ComponentRegistryException("Private workspace without owner!");
     221                    }
     222                    return ComponentUtils.toComponents(componentDao.getPrivateBaseDescriptions(registryOwner.getId(), ComponentDescription.COMPONENT_PREFIX));
     223                case GROUP:
     224                    return this.getComponentDescriptionsInGroup(groupId);
     225                case PUBLISHED:
     226                    return ComponentUtils.toComponents(componentDao.getPublicBaseDescriptions(ComponentDescription.COMPONENT_PREFIX));
     227                default:
     228                    throw new ComponentRegistryException("Unsupported status type" + registrySpace);
     229            }
     230        } catch (DataAccessException ex) {
     231            throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
     232        }
     233    }
     234
     235    @Override
     236    public ComponentDescription getComponentDescriptionAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     237        boolean hasAccess = this.canCurrentUserAccessDescription(id);
     238        if (hasAccess) {
     239            try {
     240                return ComponentUtils.toComponent(componentDao.getByCmdId(id));
     241            } catch (DataAccessException ex) {
     242                throw new ComponentRegistryException("Database access error while trying to get component description", ex);
     243            }
     244        } else {
     245            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
     246        }
     247    }
     248
     249    private ComponentDescription getComponentDescription(String id) throws ComponentRegistryException {
     250        try {
     251            return ComponentUtils.toComponent(componentDao.getByCmdId(id));
     252        } catch (DataAccessException ex) {
     253            throw new ComponentRegistryException("Database access error while trying to get component description", ex);
     254        }
     255
     256    }
     257
     258    @Override
     259    public List<Comment> getCommentsInProfile(String profileId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     260        try {
     261            //Olha was here
     262            //if (componentDao.isInRegistry(profileId, getUserId())) {
     263            if (this.canCurrentUserAccessDescription(profileId)) {
     264                final List<Comment> commentsFromProfile = commentsDao.getCommentsFromItem(profileId);
     265                this.setCanDeleteInComments(commentsFromProfile);
     266                return commentsFromProfile;
     267            } else {
     268                throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
     269            }
     270        } catch (DataAccessException ex) {
     271            throw new ComponentRegistryException(
     272                    "Database access error while trying to get list of comments from profile", ex);
     273        }
     274    }
     275
     276    @Override
     277    public Comment getSpecifiedCommentInProfile(String profileId, String commentId)
     278            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     279        if (this.canCurrentUserAccessDescription(profileId)) {
     280            try {
     281                Comment comment = commentsDao.findOne(Long.parseLong(commentId));
     282                if (comment != null && profileId.equals(comment.getComponentId())) {
     283                    this.setCanDeleteInComments(Collections.singleton(comment));
     284                    return comment;
     285                } else {
     286                    // Comment exists in DB, but profile is not in this registry
     287                    throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
     288                }
     289            } catch (DataAccessException ex) {
     290                throw new ComponentRegistryException("Database access error while trying to get comment from profile", ex);
     291            }
     292        } else {
     293            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile");
     294        }
     295    }
     296
     297    @Override
     298    public List<Comment> getCommentsInComponent(String componentId)
     299            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     300        if (this.canCurrentUserAccessDescription(componentId)) {
     301            try {
     302                final List<Comment> commentsFromComponent = commentsDao.getCommentsFromItem(componentId);
     303                this.setCanDeleteInComments(commentsFromComponent);
     304                return commentsFromComponent;
     305
     306            } catch (DataAccessException ex) {
     307                throw new ComponentRegistryException(
     308                        "Database access error while trying to get list of comments from component", ex);
     309            }
     310        } else {
     311            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
     312        }
     313    }
     314
     315    @Override
     316    public Comment getSpecifiedCommentInComponent(String componentId, String commentId)
     317            throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     318        if (this.canCurrentUserAccessDescription(componentId)) {
     319            try {
     320                Comment comment = commentsDao.findOne(Long.parseLong(commentId));
     321                if (comment != null && componentId.equals(comment.getComponentId().toString())) {
     322                    this.setCanDeleteInComments(Collections.singleton(comment));
     323                    return comment;
     324                } else {
     325                    // Comment does not exists in DB or component is not in this
     326                    // registry
     327                    throw new ComponentRegistryException("Comment " + commentId
     328                            + " cannot be found in specified registry for specified component");
     329                }
     330            } catch (DataAccessException ex) {
     331                throw new ComponentRegistryException("Database access error while trying to get comment from component", ex);
     332            }
     333        } else {
     334            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component");
     335        }
     336    }
     337
     338    /**
     339     * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all
     340     * comments in the provided collection for the perspective of the specified
     341     * principal. Comment owners (determined by {@link Comment#getUserId() })
     342     * and admins can delete, others cannot.
     343     *
     344     * @param comments comments to configure
     345     * @param principal user to configure for
     346     * @see Comment#isCanDelete()
     347     */
     348    private void setCanDeleteInComments(Collection<Comment> comments) {
     349        String principalName = (userDao.getPrincipalNameById(registryOwner.getId())).getPrincipalName();
     350        final boolean isAdmin = configuration.isAdminUser(principalName);
     351        for (Comment comment : comments) {
     352            comment.setCanDelete(isAdmin || comment.getUserId() == registryOwner.getId().longValue());
     353        }
     354
     355    }
     356
     357    @Override
     358    public CMDComponentSpec getMDProfileAccessControled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     359        if (this.canCurrentUserAccessDescription(id)) {
     360            return this.getMDProfile(id);
     361        } else {
     362            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given profile or the profile is not found.");
     363        }
     364    }
     365
     366    private CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException {
     367        if (id.startsWith(ProfileDescription.PROFILE_PREFIX)) {
     368            CMDComponentSpec result = profilesCache.get(id);
     369            if (result == null && !profilesCache.containsKey(id)) {
     370                result = this.getUncachedMDProfile(id);
     371                profilesCache.put(id, result);
     372            }
     373            return result;
     374        } else {
     375            throw new ComponentRegistryException("the id " + id + " is not a profile id.");
     376        }
     377    }
     378
     379    public CMDComponentSpec getUncachedMDProfile(String id) throws ComponentRegistryException {
     380        try {
     381            return this.getUncachedMDComponent(id, componentDao);
     382        } catch (DataAccessException ex) {
     383            throw new ComponentRegistryException("Database access error while trying to get profile", ex);
     384        }
     385    }
     386
     387    @Override
     388    public CMDComponentSpec getMDComponentAccessControlled(String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     389        if (this.canCurrentUserAccessDescription(id)) {
     390            return this.getMDComponent(id);
     391        } else {
     392            throw new UserUnauthorizedException("The logged-in user (aka registry owner) does not have access the the given component or the component is not found.");
     393        }
     394    }
     395
     396    @Override
     397    public CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException {
     398        if (id.startsWith(ComponentDescription.COMPONENT_PREFIX)) {
     399            CMDComponentSpec result = componentsCache.get(id);
     400            if (result == null && !componentsCache.containsKey(id)) {
     401                result = getUncachedMDComponent(id);
     402                componentsCache.put(id, result);
     403            }
     404            return result;
     405        } else {
     406            throw new ComponentRegistryException("The id " + id + " is not a component id");
     407        }
     408    }
     409
     410    public CMDComponentSpec getUncachedMDComponent(String id) throws ComponentRegistryException {
     411        try {
     412            return this.getUncachedMDComponent(id, componentDao);
     413        } catch (DataAccessException ex) {
     414            throw new ComponentRegistryException("Database access error while trying to get component", ex);
     415        }
     416    }
     417
     418    @Override
     419    public int register(BaseDescription description, CMDComponentSpec spec) {
     420        enrichSpecHeader(spec, description);
     421        try {
     422            String xml = componentSpecToString(spec);
     423            // Convert principal name to user record id
     424            Number uid = convertUserInDescription(description);
     425            componentDao.insertDescription(description, xml, description.isPublic(), uid);
     426            invalidateCache(description);
     427            return 0;
     428        } catch (DataAccessException ex) {
     429            LOG.error("Database error while registering component", ex);
     430            return -1;
     431        } catch (JAXBException ex) {
     432            LOG.error("Error while registering component", ex);
     433            return -2;
     434        } catch (UnsupportedEncodingException ex) {
     435            LOG.error("Error while registering component", ex);
     436            return -3;
     437        }
     438    }
     439
     440    @Override
     441    public int registerComment(Comment comment, String principalName) throws ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException {
     442        try {
     443            if (comment.getComponentId() != null)  {
     444                if (this.canCurrentUserAccessDescription(comment.getComponentId()))
     445                {
     446                // Convert principal name to user record id
     447                Number uid = convertUserIdInComment(comment, principalName);
     448                // Set date to current date
     449                comment.setCommentDate(new Date());
     450                comment.setUserId(uid.longValue());
     451                commentsDao.saveAndFlush(comment);
     452           
     453            } else {
     454                throw new UserUnauthorizedException("The logged-in user cannot access the component/profile with id "+comment.getComponentId());
     455            }
     456            } else {
     457                throw new ComponentRegistryException("The component/profile id for this comment is null.");           
     458            }
     459            return 0;
     460        } catch (DataAccessException ex) {
     461            LOG.error("Database error while registering component", ex);
     462            return -1;
     463        }
     464    }
     465
     466    /**
     467     * Calling service sets user id to principle. Our task is to convert this to
     468     * an id for later reference. If none is set and this is a user's workspace,
     469     * set from that user's id.
     470     *
     471     * It also sets the name in the description according to the display name in
     472     * the database.
     473     *
     474     * @param description Description containing principle name as userId
     475     * @return Id (from database)
     476     * @throws DataAccessException
     477     */
     478    private Number convertUserInDescription(BaseDescription description) throws DataAccessException {
     479        Number uid = null;
     480        String name = null;
     481        if (description.getUserId() != null) {
     482            RegistryUser user = userDao.getByPrincipalName(description.getUserId());
     483            if (user != null) {
     484                uid = user.getId();
     485                name = user.getName();
     486            }
     487        } else {
     488            uid = getUserId(); // this can be null as well
     489        }
     490        if (uid != null) {
     491            description.setUserId(uid.toString());
     492        }
     493        if (name != null) {
     494            description.setCreatorName(name);
     495        }
     496        return uid;
     497    }
     498
     499    /**
     500     * Calling service sets user id to principle. Our task is to convert this to
     501     * an id for later reference. If none is set and this is a user's workspace,
     502     * set from that user's id.
     503     *
     504     * @param comment Comment containing principle name as userId
     505     * @return Id (from database)
     506     * @throws DataAccessException
     507     */
     508    private Number convertUserIdInComment(Comment comment, String principalName) throws DataAccessException,
     509            ComponentRegistryException {
     510        if (principalName != null) {
     511            RegistryUser user = userDao.getByPrincipalName(principalName);
     512            if (user != null) {
     513                Long id = user.getId();
     514                if (id != null) {
     515                    // Set user id in comment for convenience of calling method
     516                    comment.setUserId(id);
     517                    // Set name to user's preferred display name
     518                    comment.setUserName(user.getName());
     519                    return id;
     520                } else {
     521                    throw new ComponentRegistryException("Cannot find user with principal name: " + principalName);
     522                }
     523            }
     524        }
     525        return null;
     526    }
     527
     528    @Override
     529    public int update(BaseDescription description, CMDComponentSpec spec, boolean forceUpdate) throws UserUnauthorizedException, ItemNotFoundException {
     530        try {
     531            this.checkAuthorisation(description);
     532            this.checkAge(description);
     533            // For public components, check if used in other components or
     534            // profiles (unless forced)
     535            if (!forceUpdate && description.isPublic() && !description.isProfile()) {
     536                this.checkStillUsed(description.getId());
     537            }
     538            componentDao.updateDescription(getIdForDescription(description), description, componentSpecToString(spec));
     539            invalidateCache(description);
     540            return 0;
     541        } catch (JAXBException ex) {
     542            LOG.error("Error while updating component", ex);
     543            return -1;
     544        } catch (UnsupportedEncodingException ex) {
     545            LOG.error("Error while updating component", ex);
     546            return -1;
     547        } catch (IllegalArgumentException ex) {
     548            LOG.error("Error while updating component", ex);
     549            return -1;
     550        } catch (DeleteFailedException e) {
     551            LOG.error("Error while updating component", e);
     552            return -1;
     553        } catch (ComponentRegistryException e) {
     554            LOG.error("Error while updating component", e);
     555            return -1;
     556        }
     557    }
     558
     559    @Override
     560    public int publish(BaseDescription desc, CMDComponentSpec spec, Principal principal) throws UserUnauthorizedException, ItemNotFoundException {
     561        int result = 0;
     562        this.checkAuthorisation(desc);
     563        if (desc.isPublic()) { // if already in published
     564            // todo
     565            desc.setHref(ComponentUtils.createPublicHref(desc.getHref()));
     566            Number id = getIdForDescription(desc);
     567            try {
     568                // Update description & content
     569                componentDao.updateDescription(id, desc, componentSpecToString(spec));
     570                // Set to public
     571                componentDao.setPublished(id, true);
     572            } catch (DataAccessException ex) {
     573                LOG.error("Database error while updating component", ex);
     574                return -1;
     575            } catch (JAXBException ex) {
     576                LOG.error("Error while updating component", ex);
     577                return -2;
     578            } catch (UnsupportedEncodingException ex) {
     579                LOG.error("Error while updating component", ex);
     580                return -3;
     581            }
     582        }
     583        return result;
     584    }
     585
     586    @Override
     587    public void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException {
     588        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
     589        writeXml(expandedSpec, output);
     590    }
     591
     592    @Override
     593    public void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException {
     594        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
     595        writeXsd(expandedSpec, outputStream);
     596    }
     597
     598    @Override
     599    public void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException {
     600        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
     601        writeXml(expandedSpec, output);
     602    }
     603
     604    @Override
     605    public void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException {
     606        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
     607        writeXsd(expandedSpec, outputStream);
     608    }
     609
     610    @Override
     611    public void deleteMDProfile(String profileId) throws UserUnauthorizedException,
     612            DeleteFailedException, ComponentRegistryException, ItemNotFoundException {
     613        ProfileDescription desc = getProfileDescriptionAccessControlled(profileId);
     614        if (desc != null) {
     615            try {
     616                this.checkAuthorisation(desc);
     617                this.checkAge(desc);
     618                componentDao.setDeleted(desc, true);
     619                invalidateCache(desc);
     620            } catch (DataAccessException ex) {
     621                throw new DeleteFailedException("Database access error while trying to delete profile", ex);
     622            }
     623        }
     624    }
     625
     626    @Override
     627    public void deleteMDComponent(String componentId, boolean forceDelete)
     628            throws UserUnauthorizedException, DeleteFailedException, ComponentRegistryException, ItemNotFoundException {
     629        BaseDescription desc = componentDao.getByCmdId(componentId);
     630        if (desc != null) {
     631            try {
     632                this.checkAuthorisation(desc);
     633                this.checkAge(desc);
     634
     635                if (!forceDelete) {
     636                    checkStillUsed(componentId);
     637                }
     638                componentDao.setDeleted(desc, true);
     639                invalidateCache(desc);
     640            } catch (DataAccessException ex) {
     641                throw new DeleteFailedException("Database access error while trying to delete component", ex);
     642            }
     643        }
     644    }
     645
     646   
     647
     648    private void invalidateCache(BaseDescription description) {
     649        if (description.isProfile()) {
     650            profilesCache.remove(description.getId());
     651        } else {
     652            componentsCache.remove(description.getId());
     653        }
     654    }
     655
     656    /**
     657     * Looks up description on basis of CMD Id. This will also check if such a
     658     * record even exists.
     659     *
     660     * @param description Description to look up
     661     * @return Database id for description
     662     * @throws IllegalArgumentException If description with non-existing id is
     663     * passed
     664     */
     665    private Number getIdForDescription(BaseDescription description) throws IllegalArgumentException {
     666        Number dbId = null;
     667        try {
     668            dbId = componentDao.getDbId(description.getId());
     669        } catch (DataAccessException ex) {
     670            LOG.error("Error getting dbId for component with id " + description.getId(), ex);
     671        }
     672        if (dbId == null) {
     673            throw new IllegalArgumentException("Could not get database Id for description");
     674        } else {
     675            return dbId;
     676        }
     677    }
     678
     679    private String componentSpecToString(CMDComponentSpec spec) throws UnsupportedEncodingException, JAXBException {
     680        ByteArrayOutputStream os = new ByteArrayOutputStream();
     681        getMarshaller().marshal(spec, os);
     682        String xml = os.toString("UTF-8");
     683        return xml;
     684    }
     685
     686    private CMDComponentSpec getUncachedMDComponent(String id, ComponentDao dao) {
     687        String xml = dao.getContent(false, id);
     688        if (xml != null) {
     689            try {
     690                InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
     691                CMDComponentSpec result = getMarshaller().unmarshal(CMDComponentSpec.class, is, null);
     692                try {
     693                    is.close();
     694                    return result;
     695                } catch (IOException ex) {
     696                    LOG.error("Cannot close the stream", ex);
     697                    return result;
     698                }
     699
     700            } catch (JAXBException ex) {
     701                LOG.error("Error while unmarshalling", ex);
     702            } catch (UnsupportedEncodingException ex) {
     703                LOG.error("Exception while reading XML from database", ex);
     704            }
     705        }
     706        return null;
     707    }
     708
     709    private void checkAuthorisation(BaseDescription desc) throws UserUnauthorizedException, ItemNotFoundException {
     710        if (!this.canCurrentUserAccessDescription(desc.getId())) {           
     711            String principalName = (registryOwner != null) ? userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName() : "null";
     712            throw new UserUnauthorizedException("Unauthorized operation user '" + principalName
     713                    + "' is not the creator (nor a member of the group, nor an administrator) of the "
     714                    + (desc.isProfile() ? "profile" : "component") + "(" + desc + ").");
     715        }
     716    }
     717
     718    private void checkAuthorisationComment(Comment desc) throws UserUnauthorizedException {
     719        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
     720        if (!(this.isOwnerOfComment(desc, principalName) || configuration.isAdminUser(principalName))) {
     721            throw new UserUnauthorizedException("Unauthorized operation user '" + principalName
     722                    + "' is not the creator (nor a member of the group, nor an administrator) of the " + (desc.getId()) + "(" + desc + ").");
     723        }
     724    }
     725
     726//    private boolean isOwnerOfDescription(BaseDescription desc, String principalName) {
     727//        String owner = componentDao.getOwnerPrincipalName(getIdForDescription(desc));
     728//        return owner != null // If owner is null, no one can be owner
     729//                && principalName.equals(owner);
     730//    }
     731    private boolean isOwnerOfComment(Comment com, String principalName) {
     732        long id = Long.parseLong(com.getId());
     733        RegistryUser owner = commentsDao.getOwnerOfComment(id);
     734        return owner != null // If owner is null, no one can be owner
     735                && principalName.equals(owner.getPrincipalName());
     736    }
     737
     738    private void checkAge(BaseDescription desc) throws DeleteFailedException {
     739        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
     740        if (desc.isPublic() && !configuration.isAdminUser(principalName)) {
     741            Date regDate = desc.getRegistrationDate();
     742            Calendar calendar = Calendar.getInstance();
     743            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
     744            if (regDate.before(calendar.getTime())) { // More then month old
     745                throw new DeleteFailedException(
     746                        "The "
     747                        + (desc.isProfile() ? "Profile" : "Component")
     748                        + " 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.");
     749            }
     750        }
     751    }
     752
     753    @Override
     754    public String getName() {
     755        if (this.getRegistrySpace() != null) {
     756            if (this.getRegistrySpace().equals(RegistrySpace.PUBLISHED)) {
     757                return ComponentRegistry.PUBLIC_NAME;
     758            } else {
     759                if (this.getRegistrySpace().equals(RegistrySpace.GROUP)) {
     760                    if (groupId != null) {
     761                        return "Registry of group" + groupId.toString();
     762                    } else {
     763                        return "Error: Registry of group null.";
     764                    }
     765                }
     766            }
     767        };
     768        RegistryUser u = userDao.findOne(getUserId().longValue());
     769        return "Registry of " + u.getName();
     770    }
     771
     772    private boolean canCurrentUserAccessDescription(String cmdId) throws ItemNotFoundException{
     773        if (cmdId == null) {
     774            throw new ItemNotFoundException("Item with the null cmdIdentifier.");
     775        }
     776       
     777        BaseDescription description = componentDao.getByCmdId(cmdId);
     778        if (description == null) {
     779            throw new ItemNotFoundException("Item with the id "+cmdId+" is not found.");
     780        }
     781       
     782       
     783        Number userId = getUserId();
     784        if (userId == null) {
     785            return false;
     786        }
     787        RegistryUser user = userDao.findOne(userId.longValue());
     788        if (user == null) {
     789            return false;
     790        }
     791       
     792
     793        if (configuration.isAdminUser(user.getPrincipalName())) {
     794            return true;
     795        }
     796
     797        return groupService.canUserAccessComponentEitherOnHisOwnOrThroughGroupMembership(user, description);
     798    }
     799
     800    @Override
     801    public List<ProfileDescription> getDeletedProfileDescriptions() throws ComponentRegistryException {
     802        return ComponentUtils.toProfiles(componentDao.getDeletedDescriptions(getUserId()));
     803    }
     804
     805    @Override
     806    public List<ComponentDescription> getDeletedComponentDescriptions() throws ComponentRegistryException {
     807        return ComponentUtils.toComponents(componentDao.getDeletedDescriptions(getUserId()));
     808    }
     809
     810    @Override
     811    public void deleteComment(String commentId) throws IOException, ComponentRegistryException,
     812            UserUnauthorizedException, DeleteFailedException, ItemNotFoundException {
     813        try {
     814            Comment comment = commentsDao.findOne(Long.parseLong(commentId));
     815            if (comment != null
     816                    // Comment must have an existing (in this registry)
     817                    // componentId or profileId
     818                    && comment.getComponentId() != null
     819                    && this.canCurrentUserAccessDescription(comment.getComponentId())) {
     820                this.checkAuthorisationComment(comment);
     821                commentsDao.delete(comment);
     822            } else {
     823                // Comment exists in DB, but component is not in this registry
     824                throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
     825            }
     826        } catch (DataAccessException ex) {
     827            throw new DeleteFailedException("Database access error while trying to delete component", ex);
     828        } catch (NumberFormatException ex) {
     829            throw new DeleteFailedException("Illegal comment ID, cannot parse integer", ex);
     830        }
     831    }
     832   
     833 
     834
     835    @Override
     836    public CMDComponentSpecExpander getExpander() {
     837        return new CMDComponentSpecExpanderDbImpl(this);
     838    }
     839
     840    @Override
     841    protected MDMarshaller getMarshaller() {
     842        return marshaller;
     843    }
     844
     845    @Override
     846    public String toString() {
     847        return getName();
     848    }
     849
     850    private List<ComponentDescription> getComponentDescriptionsInGroup(Number groupId)
     851            throws ComponentRegistryException, UserUnauthorizedException {
     852
     853        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
     854
     855        if (!groupService.userGroupMember(principalName, groupId.toString())) {
     856            throw new UserUnauthorizedException("The user \'" + principalName + "\' does not have access to components of the group " + groupId);
     857        }
     858
     859        List<String> componentIds = componentDao.getAllItemIdsInGroup(ComponentDescription.COMPONENT_PREFIX, groupId.longValue());
     860        List<ComponentDescription> components = new ArrayList<ComponentDescription>();
     861        for (String id : componentIds) {
     862            BaseDescription description = componentDao.getByCmdId(id);
     863            components.add(ComponentUtils.toComponent(description));
     864        }
     865        return components;
     866    }
     867
     868    private List<ProfileDescription> getProfileDescriptionsInGroup(Number groupId) throws ComponentRegistryException, UserUnauthorizedException {
     869
     870        String principalName = userDao.getPrincipalNameById(registryOwner.getId()).getPrincipalName();
     871
     872        if (!groupService.userGroupMember(principalName, groupId.toString())) {
     873            throw new UserUnauthorizedException("The user \'" + principalName + "\' does not have access to profiles of the group " + groupId);
     874        }
     875
     876        List<String> profileIds = componentDao.getAllItemIdsInGroup(ProfileDescription.PROFILE_PREFIX, groupId.longValue());
     877        List<ProfileDescription> profiles = new ArrayList<ProfileDescription>();
     878        for (String id : profileIds) {
     879            BaseDescription description = componentDao.getByCmdId(id);
     880            if (description != null) {
     881                profiles.add(ComponentUtils.toProfile(description));
     882            }
     883        }
     884        return profiles;
     885    }
     886
     887    @Override
     888    public List<ProfileDescription> getProfileDescriptionsForMetadaEditor(Number groupId) throws UserUnauthorizedException,
     889            ComponentRegistryException {
     890        return this.getProfileDescriptionsInGroup(groupId.longValue());
     891    }
     892
     893    @Override
     894    public List<String> getAllNonDeletedProfileIds() {
     895        return componentDao.getAllNonDeletedProfileIds();
     896    }
     897
     898    @Override
     899    public List<String> getAllNonDeletedComponentIds() {
     900        return componentDao.getAllNonDeletedComponentIds();
     901    }
     902
     903    @Override
     904    public List<ComponentDescription> getUsageInComponents(String componentId) throws ComponentRegistryException {
     905        LOG.debug("Checking usage of component {} in components", componentId);
     906        List<ComponentDescription> result = new ArrayList<ComponentDescription>();
     907        List<String> ids = getAllNonDeletedComponentIds();
     908        for (String id : ids) {
     909            CMDComponentSpec spec = getMDComponent(id);
     910            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
     911                LOG.debug("Component {} used in component {}", componentId, spec.getHeader().getID());
     912                result.add(getComponentDescription(id));
     913            }
     914        }
     915        return result;
     916    }
     917
     918    @Override
     919    public List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException {
     920        LOG.debug("Checking usage of component {} in profiles", componentId);
     921        List<ProfileDescription> result = new ArrayList<ProfileDescription>();
     922        for (String id : getAllNonDeletedProfileIds()) {
     923            CMDComponentSpec profile = getMDProfile(id);
     924            if (profile != null && hasComponentId(componentId, profile.getCMDComponent())) {
     925                LOG.debug("Component {} used in profile {}", componentId, profile.getHeader().getID());
     926                result.add(getProfileDescription(id));
     927            }
     928        }
     929        return result;
     930    }
     931
     932    protected static boolean findComponentId(String componentId, List<CMDComponentType> componentReferences) {
     933        for (CMDComponentType cmdComponent : componentReferences) {
     934            if (hasComponentId(componentId, cmdComponent)) {
     935                return true;
     936            }
     937        }
     938        return false;
     939    }
     940
     941    private static boolean hasComponentId(String componentId, CMDComponentType cmdComponent) {
     942        if (componentId.equals(cmdComponent.getComponentId())) {
     943            return true;
     944        } else if (findComponentId(componentId, cmdComponent.getCMDComponent())) {
     945            return true;
     946        } else {
     947            return false;
     948        }
     949    }
     950
     951    protected void checkStillUsed(String componentId) throws DeleteFailedException, ComponentRegistryException {
     952        for (String id : getAllNonDeletedProfileIds()) {
     953            CMDComponentSpec spec = getMDProfile(id);
     954            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
     955                LOG.warn("Cannot delete component {}, still used in profile {} and possibly other profiles and/or components", componentId, spec.getHeader().getID());
     956                // Profile match - throw
     957                throw new DeleteFailedException("Component is still in use by other components or profiles. Request component usage for details.");
     958            }
     959        }
     960
     961        LOG.debug("Component {} is not used in any profiles", componentId);
     962
     963        for (String id : getAllNonDeletedComponentIds()) {
     964            CMDComponentSpec spec = getMDComponent(id);
     965            if (spec != null && hasComponentId(componentId, spec.getCMDComponent())) {
     966                LOG.warn("Cannot delete component {}, still used in component {} and possibly other components", componentId, spec.getHeader().getID());
     967                // Component match -> throw
     968                throw new DeleteFailedException("Component is still in use by one or more other components. Request component usage for details.");
     969            }
     970        }
     971    }
    805972}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java

    r4098 r5549  
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    44import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    5 import clarin.cmdi.componentregistry.ComponentStatus;
    65import clarin.cmdi.componentregistry.Configuration;
    76import clarin.cmdi.componentregistry.Owner;
    87import clarin.cmdi.componentregistry.OwnerUser;
     8import clarin.cmdi.componentregistry.RegistrySpace;
    99import clarin.cmdi.componentregistry.UserCredentials;
    1010import clarin.cmdi.componentregistry.UserUnauthorizedException;
     
    2525 * ComponentRegistryDbImpl implementation of ComponentRegistry for accessing the
    2626 * registry
    27  * 
     27 *
    2828 * @author Twan Goosen <twan.goosen@mpi.nl>
    2929 * @author George.Georgovassilis@mpi.nl
     
    3232
    3333    private final static Logger LOG = LoggerFactory
    34             .getLogger(ComponentRegistryFactoryDbImpl.class);
     34            .getLogger(ComponentRegistryFactoryDbImpl.class);
    3535    @Autowired
    3636    private Configuration configuration;
     
    4343    @Override
    4444    public List<ComponentRegistry> getAllUserRegistries() {
    45         // TODO: this probably could use some caching
    46         try {
    47             List<RegistryUser> users = userDao.getAllUsers();
    48             List<ComponentRegistry> registries = new ArrayList<ComponentRegistry>();
    49             for (RegistryUser user : users) {
    50                 registries.add(getNewComponentRegistryForUser(user.getId()));
    51             }
    52             return registries;
    53         } catch (DataAccessException ex) {
    54             LOG.error("Could not retrieve users", ex);
    55             throw ex;
    56         }
    57     }
    58 
    59     @Override
    60     public ComponentRegistry getComponentRegistry(ComponentStatus status,
    61             Owner owner, UserCredentials credentials)
    62             throws UserUnauthorizedException {
    63         switch (status) {
    64         case PRIVATE:
    65             return getPrivateRegistry(owner, credentials);
    66         case PUBLISHED:
    67             return getPublicRegistry();
    68         default:
    69             // TODO: Add support for other status types
    70             throw new UnsupportedOperationException(
    71                     "Unsupported component status" + status);
    72         }
     45        // TODO: this probably could use some caching
     46        try {
     47            List<RegistryUser> users = userDao.getAllUsers();
     48            List<ComponentRegistry> registries = new ArrayList<ComponentRegistry>();
     49            for (RegistryUser user : users) {
     50                registries.add(getNewComponentRegistryForUser(user.getId()));
     51            }
     52            return registries;
     53        } catch (DataAccessException ex) {
     54            LOG.error("Could not retrieve users", ex);
     55            throw ex;
     56        }
     57    }
     58
     59    @Override
     60    public ComponentRegistry getComponentRegistry(RegistrySpace space,
     61            Owner owner, UserCredentials credentials, Number groupId)
     62            throws UserUnauthorizedException {
     63
     64        switch (space) {
     65            case PRIVATE:
     66                return this.getPrivateRegistry(owner, credentials);
     67            case PUBLISHED:
     68                return this.getPublicRegistry();
     69            case GROUP:
     70                return this.getGroupRegistry(groupId, owner, credentials);
     71            default:
     72                // TODO: Add support for "review" types
     73                throw new UnsupportedOperationException(
     74                        "Unsupported component space" + space);
     75        }
     76    }
     77
     78    private ComponentRegistry getGroupRegistry(Number groupId, Owner owner, UserCredentials credentials) {
     79        if (owner == null || owner instanceof OwnerUser) {
     80            RegistryUser user = this.getOrCreateUser(credentials);
     81            owner = new OwnerUser(user.getId());
     82        }
     83        ComponentRegistryDbImpl cr = componentRegistryBeanFactory.getNewComponentRegistry();// default public registry
     84        cr.setRegistrySpace(RegistrySpace.PRIVATE);
     85        cr.setRegistryOwner(owner);
     86        cr.setGroupId(groupId);
     87        return cr;
    7388    }
    7489
    7590    private ComponentRegistry getPrivateRegistry(Owner owner,
    76             UserCredentials credentials) throws IllegalArgumentException,
    77             DataAccessException, UserUnauthorizedException {
    78         if (owner == null || owner instanceof OwnerUser) {
    79             RegistryUser user = getOrCreateUser(credentials);
    80             if (user != null) {
    81                 if (owner != null && !user.getId().equals(owner.getId())) {
    82                     throw new UserUnauthorizedException(
    83                             "User cannot access other user's private registry");
    84                 }
    85 
    86                 try {
    87                     return getNewComponentRegistryForUser(user.getId());
    88                 } catch (DataAccessException ex) {
    89                     LOG.error("Could not retrieve or create user", ex);
    90                     throw ex;
    91                 }
    92             } else {
    93                 throw new UserUnauthorizedException(
    94                         "No user credentials available cannot load userspace.");
    95             }
    96         } else {
    97             // TODO: Support group owners
    98             throw new UnsupportedOperationException(
    99                     "Group owners not supported");
    100         }
     91            UserCredentials credentials) throws IllegalArgumentException,
     92            DataAccessException, UserUnauthorizedException {
     93        if (owner == null || owner instanceof OwnerUser) {
     94            RegistryUser user = getOrCreateUser(credentials);
     95            if (user != null) {
     96                if (owner != null && !user.getId().equals(owner.getId())) {
     97                    throw new UserUnauthorizedException(
     98                            "User cannot access other user's private registry");
     99                }
     100
     101                try {
     102                    return this.getNewComponentRegistryForUser(user.getId());
     103                } catch (DataAccessException ex) {
     104                    LOG.error("Could not retrieve or create user", ex);
     105                    throw ex;
     106                }
     107            } else {
     108                throw new UserUnauthorizedException(
     109                        "No user credentials available cannot load userspace.");
     110            }
     111        } else {
     112            // TODO: Support group owners
     113            throw new UnsupportedOperationException(
     114                    "Group owners not supported");
     115        }
    101116    }
    102117
    103118    @Override
    104119    public ComponentRegistry getOtherUserComponentRegistry(
    105             Principal adminPrincipal, ComponentStatus status, Owner owner) {
    106         try {
    107             RegistryUser user;
    108             if (owner instanceof OwnerUser) {
    109                 user = userDao.findOne(owner.getId().longValue());
    110             } else {
    111                 // TODO: Implement for groups
    112                 throw new UnsupportedOperationException(
    113                         "Groups not implemented yet");
    114             }
    115             ComponentRegistry result = null;
    116             if (user != null) {
    117                 if (configuration.isAdminUser(adminPrincipal)) {
    118                     result = getNewComponentRegistryForUser(user.getId());
    119                 } else {
    120                     LOG.info("{} not found in list of {}",
    121                             adminPrincipal.getName(),
    122                             configuration.getAdminUsersArray().length);
    123                     throw new IllegalArgumentException("User "
    124                             + adminPrincipal.getName()
    125                             + " is not admin user cannot load userspace.");
    126                 }
    127             }
    128             return result;
    129         } catch (DataAccessException ex) {
    130             LOG.error("Could not retrieve user by id", ex);
    131             throw ex;
    132         }
     120            Principal adminPrincipal, Owner owner) {
     121        try {
     122            RegistryUser user;
     123            if (owner instanceof OwnerUser) {
     124                user = userDao.findOne(owner.getId().longValue());
     125            } else {
     126                // TODO: Implement for groups ??? Twan
     127                throw new UnsupportedOperationException(
     128                        "Groups not implemented yet");
     129            }
     130            ComponentRegistry result = null;
     131            if (user != null) {
     132                if (configuration.isAdminUser(adminPrincipal)) {
     133                    result = this.getNewComponentRegistryForUser(user.getId());
     134                } else {
     135                    LOG.info("{} not found in list of {}",
     136                            adminPrincipal.getName(),
     137                            configuration.getAdminUsersArray().length);
     138                    throw new IllegalArgumentException("User "
     139                            + adminPrincipal.getName()
     140                            + " is not admin user cannot load userspace.");
     141                }
     142            }
     143            return result;
     144        } catch (DataAccessException ex) {
     145            LOG.error("Could not retrieve user by id", ex);
     146            throw ex;
     147        }
    133148    }
    134149
    135150    @Override
    136151    public ComponentRegistry getPublicRegistry() {
    137         if (publicComponentRegistry == null) {
    138             publicComponentRegistry = getNewComponentRegistryForUser(null);
    139         }
    140         return publicComponentRegistry;
     152        if (publicComponentRegistry == null) {
     153            publicComponentRegistry = this.getNewComponentRegistryForUser(null);
     154        }
     155        return publicComponentRegistry;
    141156    }
    142157
    143158    private ComponentRegistry getNewComponentRegistryForUser(Number userId) {
    144         ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory
    145                 .getNewComponentRegistry();
    146         if (userId != null) {
    147             // Null means public registry
    148             // TODO: Make this more explicit
    149             componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(
    150                     userId));
    151         }
    152         return componentRegistry;
     159        ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
     160        if (userId != null) {
     161            OwnerUser ou = new OwnerUser(userId);
     162            componentRegistry.setRegistrySpace(RegistrySpace.PRIVATE);
     163            componentRegistry.setRegistryOwner(ou);
     164            componentRegistry.setGroupId(null);
     165        }
     166        return componentRegistry;
     167    }
     168
     169    @Override
     170    public ComponentRegistryDbImpl getBaseRegistry(UserCredentials credentials) {
     171        RegistryUser user = this.getOrCreateUser(credentials);
     172        ComponentRegistryDbImpl componentRegistryDbImpl = componentRegistryBeanFactory.getNewComponentRegistry();// default public registry
     173        if (user != null) {
     174            Number userId = user.getId();
     175            Owner owner = new OwnerUser(userId);
     176            componentRegistryDbImpl.setRegistrySpace(null);
     177            componentRegistryDbImpl.setRegistryOwner(owner);
     178            componentRegistryDbImpl.setGroupId(null);
     179        }
     180        return componentRegistryDbImpl;
    153181    }
    154182
    155183    @Override
    156184    public RegistryUser getOrCreateUser(UserCredentials credentials) {
    157         if (credentials != null
    158                 && !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
    159             String principalName = credentials.getPrincipalName();
    160             return getOrCreateUser(principalName, credentials.getDisplayName());
    161         }
    162         return null;
     185        if (credentials != null
     186                && !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
     187            String principalName = credentials.getPrincipalName();
     188            return this.getOrCreateUser(principalName, credentials.getDisplayName());
     189        }
     190        return null;
    163191    }
    164192
    165193    private synchronized RegistryUser getOrCreateUser(String principalName,
    166             String displayName) {
    167         // Try getting it from db
    168         RegistryUser user = userDao.getByPrincipalName(principalName);
    169         if (user == null) {
    170             LOG.info(
    171                     "Request to create user with principal name {} and display name {}",
    172                     new Object[] { principalName, displayName });
    173             // Create the new user
    174             user = new RegistryUser();
    175             user.setPrincipalName(principalName);
    176             user.setName(displayName);
    177             userDao.saveAndFlush(user);
    178             // Retrieve from db
    179             user = userDao.getByPrincipalName(principalName);
    180         }
    181         return user;
     194            String displayName) {
     195        // Try getting it from db
     196        RegistryUser user = userDao.getByPrincipalName(principalName);
     197        if (user == null) {
     198            LOG.info(
     199                    "Request to create user with principal name {} and display name {}",
     200                    new Object[]{principalName, displayName});
     201            // Create the new user
     202            user = new RegistryUser();
     203            user.setPrincipalName(principalName);
     204            user.setName(displayName);
     205            userDao.saveAndFlush(user);
     206            // Retrieve from db
     207            user = userDao.getByPrincipalName(principalName);
     208        }
     209        return user;
    182210    }
    183211}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupService.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.impl.database;
    22
     3import clarin.cmdi.componentregistry.UserUnauthorizedException;
    34import java.util.List;
    45
     
    9596     * @param componentId
    9697     */
    97     void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId);
     98    void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId) throws UserUnauthorizedException;
    9899
    99100    /**
     
    103104     * @param componentId
    104105     */
    105     void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId);
     106    void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException;
    106107
    107108    /**
     
    126127     */
    127128    List<String> getProfileIdsInGroup(long groupId);
    128 
     129   
     130    boolean userGroupMember(String principalName, String groupId);
     131   
    129132}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImpl.java

    r4169 r5549  
    11package clarin.cmdi.componentregistry.impl.database;
    22
     3import clarin.cmdi.componentregistry.UserUnauthorizedException;
    34import java.util.ArrayList;
    45import java.util.Collections;
     
    235236                ownerships.addAll(ownershipDao.findOwnershipByComponentId(itemId));
    236237                Set<Group> groups = new HashSet<Group>();
    237                 for (Ownership ownership : ownerships)
     238                for (Ownership ownership : ownerships) {
    238239                        groups.add(groupDao.findOne(ownership.getGroupId()));
     240                }
    239241                List<Group> groupList = new ArrayList<Group>(groups);
    240242                Collections.sort(groupList, new Comparator<Group>() {
     
    247249                return groupList;
    248250        }
     251       
     252       
    249253
    250254        @ManagedOperation(description = "Make a component owned by a group instead of a user")
     
    254258                        @ManagedOperationParameter(name = "componentId", description = "Id of component") })
    255259        @Override
    256         public void transferItemOwnershipFromUserToGroup(String principal, String groupName, String itemId) {
    257 
     260        public void transferItemOwnershipFromUserToGroup(String principal, String groupName, String itemId) throws UserUnauthorizedException{
     261               
     262                           
    258263                BaseDescription item = null;
    259264                item = componentDao.getByCmdId(itemId);
    260                 if (item == null)
     265                if (item == null) {
    261266                        throw new ValidationException("No profile or component found with ID " + itemId);
     267                }
    262268                Group group = groupDao.findGroupByName(groupName);
    263                 if (group == null)
     269                if (group == null) {
    264270                        throw new ValidationException("No group found with name " + groupName);
     271                }
     272               
     273                if (!this.userGroupMember(principal, String.valueOf(group.getId()))) {
     274                   throw new UserUnauthorizedException("User " + principal+ " is not a member of group "+groupName);
     275                }
     276               
     277                String creatorName = item.getCreatorName();
     278                if (!creatorName.equals(principal)) {
     279                   throw new UserUnauthorizedException("User " + principal+ " is not creator of the item  "+item.getName());
     280                }
     281               
     282               
    265283                Ownership ownership = null;
    266284                List<Ownership> oldOwnerships = ownershipDao.findOwnershipByComponentId(itemId);
     
    273291
    274292        @Override
    275         public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) {
     293        public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException{
    276294                Group group = groupDao.findOne(groupId);
    277                 if (group == null)
     295                if (group == null) {
    278296                        throw new ValidationException("No group found with id " + groupId);
    279                 transferItemOwnershipFromUserToGroup(principal, group.getName(), componentId);
    280         }
    281 
     297                }
     298                this.transferItemOwnershipFromUserToGroup(principal, group.getName(), componentId);
     299        }
     300
     301        @Override
     302        public boolean userGroupMember(String principalName, String groupId) {
     303            RegistryUser user = userDao.getByPrincipalName(principalName);
     304            GroupMembership gm = groupMembershipDao.findMembership(user.getId(), Long.parseLong(groupId));
     305            return gm != null;
     306        }
    282307}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/ComponentDao.java

    r4098 r5549  
    1616public interface ComponentDao {
    1717
    18     /**
    19      * Get all public components
    20      *
    21      * @return
    22      */
    23     List<BaseDescription> getPublicComponentDescriptions();
    24 
     18   
    2519    /**
    2620     * Get all public profiles
     
    2822     * @return
    2923     */
    30     List<BaseDescription> getPublicProfileDescriptions();
     24    List<BaseDescription> getPublicBaseDescriptions(String prefix);
    3125
    3226    /**
     
    5751     *         public)
    5852     */
    59     boolean isInRegistry(String cmdId, Number userId);
     53    //boolean isAccessible(String cmdId, Number userId);
    6054
    6155    /**
     
    117111     * @return The description, if it exists; null otherwise
    118112     */
    119     BaseDescription getByCmdId(String id, Number userId)
    120             throws DataAccessException;
     113//    BaseDescription getByCmdId(String id, Number userId)
     114//          throws DataAccessException;
     115 
    121116
    122117    /**
     
    146141     *         not part of any group
    147142     */
    148     List<BaseDescription> getUserspaceComponents(Number userId)
     143    List<BaseDescription> getPrivateBaseDescriptions(Number userId, String prefix)
    149144            throws DataAccessException;
    150 
    151     /**
    152      *
    153      * @return All the user's profiles not in the public space and are also
    154      *         not part of any group
    155      */
    156     List<BaseDescription> getUserspaceProfiles(Number userId)
    157             throws DataAccessException;
    158 
     145 
    159146    void setDeleted(BaseDescription desc, boolean isDeleted)
    160147            throws DataAccessException;
     
    182169    List<String> getAllNonDeletedComponentIds();
    183170
     171    public List<BaseDescription> getAllNonDeletedDescriptions();
     172           
     173    // Olha was here
     174    public List<String> getAllItemIdsInGroup(String prefix, Long groupId);
    184175
    185176}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java

    r4098 r5549  
    110110     */
    111111    private List<BaseDescription> augment(List<BaseDescription> baseDescription) {
    112         if (baseDescription.isEmpty())
     112        if (baseDescription.isEmpty()) {
    113113            return baseDescription;
     114        }
    114115        Map<String, BaseDescription> map = new HashMap<String, BaseDescription>();
    115116        List<String> idlist = new ArrayList<String>();
     
    165166     *         public)
    166167     */
    167     @Override
    168     public boolean isInRegistry(String cmdId, Number userId) {
    169         if (userId == null) {
    170             return isPublic(cmdId);
    171         } else {
    172             return isInUserSpace(cmdId, userId);
    173         }
    174     }
     168//    @Override
     169//    public boolean isAccessible(String cmdId, Number userId) {
     170//      if (userId == null) {
     171//          return this.isPublic(cmdId);
     172//      } else {
     173//          return this.isInUserSpace(cmdId, userId);
     174//      }
     175//    }
    175176
    176177    /**
     
    207208        copy.setPublic(isPublic);
    208209        copy.setUserId(toString(userId));
     210        copy.setCreatorName(description.getCreatorName());
    209211        copy = jpaComponentDao.saveAndFlush(copy);
    210212        jpaComponentDao.updateContent(copy.getId(), content);
     
    278280    }
    279281
    280     /**
    281      * Get by ComponentId / ProfileId
    282      *
    283      * @param id
    284      *            Full component id
    285      * @param userId
    286      *            Db id of user for workspace; null for public space
    287      * @return The description, if it exists; null otherwise
    288      */
    289     @Override
    290     public BaseDescription getByCmdId(String id, Number userId) {
    291         BaseDescription baseDescription = getByCmdId(id);
    292         if (baseDescription != null) {
    293             augment(baseDescription);
    294             if (userId == null) {
    295                 if (!baseDescription.isPublic())
    296                     baseDescription = null;
    297             } else {
    298                 if (baseDescription.isPublic()
    299                         || !compare(baseDescription.getUserId(), userId))
    300                     baseDescription = null;
    301             }
    302         }
    303         return baseDescription;
    304     }
    305 
     282 
    306283    /**
    307284     *
     
    352329     */
    353330    @Override
    354     public List<BaseDescription> getUserspaceComponents(Number userId) {
    355         return augment(jpaComponentDao
    356                 .findItemsForUserThatAreNotInGroups(userId.longValue(),
    357                         ComponentDescription.COMPONENT_PREFIX + "%"));
    358     }
    359 
    360     @Override
    361     public List<BaseDescription> getUserspaceProfiles(Number userId) {
    362         return augment(jpaComponentDao.findItemsForUserThatAreNotInGroups(
    363                 userId.longValue(), ProfileDescription.PROFILE_PREFIX + "%"));
    364     }
    365 
     331    public List<BaseDescription> getPrivateBaseDescriptions(Number userId, String prefix) {
     332        return augment(jpaComponentDao.findItemsForUserThatAreNotInGroups(userId.longValue(),prefix + "%"));
     333        //return augment(jpaComponentDao.findNotPublishedUserItems(userId.longValue(),prefix + "%"));
     334    }
     335
     336   
    366337    @Override
    367338    public void setDeleted(BaseDescription desc, boolean isDeleted) {
     
    399370
    400371    @Override
    401     public List<BaseDescription> getPublicComponentDescriptions() {
    402         return augment(jpaComponentDao
    403                 .findPublicItems(ComponentDescription.COMPONENT_PREFIX + "%"));
    404     }
    405 
    406     @Override
    407     public List<BaseDescription> getPublicProfileDescriptions() {
    408         return augment(jpaComponentDao
    409                 .findPublicItems(ProfileDescription.PROFILE_PREFIX + "%"));
    410     }
    411 
     372    public List<BaseDescription> getPublicBaseDescriptions(String prefix) {
     373        return augment(jpaComponentDao.findPublishedItems(prefix + "%"));
     374    }
     375
     376   
    412377    @Override
    413378    public List<String> getAllNonDeletedProfileIds() {
     
    419384        return jpaComponentDao.findNonDeletedItemIds(ComponentDescription.COMPONENT_PREFIX+"%");
    420385    }
    421 
     386   
     387    @Override
     388    public List<BaseDescription> getAllNonDeletedDescriptions() {
     389        return jpaComponentDao.findNonDeletedDescriptions();
     390    }
     391   
     392    // Olha was here
     393    @Override
     394    public List<String> getAllItemIdsInGroup(String prefix, Long groupId) {
     395        // we are ineterested only in non-published components in the group
     396        return jpaComponentDao.findAllItemIdsInGroup(false, prefix + "%", groupId);
     397    }
     398   
     399   
    422400}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/CommentsDao.java

    r4098 r5549  
    3535         */
    3636        @Query("select c from Comment c where c.componentId = ?1 order by c.commentDate, c.id")
    37         List<Comment> getCommentsFromComponent(String componentId)
     37        List<Comment> getCommentsFromItem(String componentId)
    3838                        throws DataAccessException;
    3939
     
    4444         * @return Principal name of description's owner, if any. Otherwise, null.
    4545         */
    46         @Query("select user from RegistryUser user, Comment comment, BaseDescription component where comment.id = ?1 and comment.componentId = component.componentId and component.dbUserId = user.id")
     46        //@Query("select user from RegistryUser user, Comment comment, BaseDescription component where comment.id = ?1 and comment.componentId = component.componentId and component.dbUserId = user.id")
     47        @Query("select user from RegistryUser user, Comment comment where comment.id = ?1 and user.id=comment.userId")
    4748        RegistryUser getOwnerOfComment(long id);
    4849
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/JpaComponentDao.java

    r4098 r5549  
    2525
    2626    @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")
    27     List<BaseDescription> findPublicItems(String idPrefix);
     27    List<BaseDescription> findPublishedItems(String idPrefix);
    2828
    2929    @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")
     
    3333    List<BaseDescription> findPublicDeletedItems();
    3434   
     35    //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")
    3536    @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")
    3637    List<BaseDescription> findItemsForUserThatAreNotInGroups(Long userId, String idPrefix);
     
    4849    @Query("select c.componentId from BaseDescription c where c.deleted = false and c.componentId like ?1 order by c.id asc")
    4950    List<String> findNonDeletedItemIds(String componentIdPrefix);
     51   
     52    @Query("select c from BaseDescription c where c.deleted = false order by c.id asc")
     53    List<BaseDescription> findNonDeletedDescriptions();
    5054
     55    @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")
     56    List<BaseDescription> findNotPublishedUserItems(Long userId, String idPrefix);   
     57   
     58    @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)")
     59    List<String> findAllItemIdsInGroup(boolean isPublished, String idPrefix, long groupId);
    5160}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/UserDao.java

    r4098 r5549  
    2828        RegistryUser getByPrincipalName(String principalName)
    2929                        throws DataAccessException;
     30       
     31        @Query("select u from RegistryUser u where u.id = ?1")
     32        RegistryUser getPrincipalNameById(Number id) throws DataAccessException;
    3033
    3134}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentClosure.java

    r1352 r5549  
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    44import clarin.cmdi.componentregistry.ComponentRegistryException;
     5import clarin.cmdi.componentregistry.ItemNotFoundException;
     6import clarin.cmdi.componentregistry.UserUnauthorizedException;
    57import clarin.cmdi.componentregistry.model.ComponentDescription;
    68
     
    810
    911    @Override
    10     public ComponentDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException {
    11         return registry.getComponentDescription(id);
     12    public ComponentDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     13        return registry.getComponentDescriptionAccessControlled(id);
    1214    }
    1315
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java

    r4681 r5549  
    22
    33import clarin.cmdi.componentregistry.AllowedAttributetypesXML;
     4import clarin.cmdi.componentregistry.AuthenticationFailException;
    45import clarin.cmdi.componentregistry.ComponentRegistry;
    56import clarin.cmdi.componentregistry.ComponentRegistryException;
    67import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    7 import clarin.cmdi.componentregistry.ComponentStatus;
    88import clarin.cmdi.componentregistry.DeleteFailedException;
     9import clarin.cmdi.componentregistry.ItemNotFoundException;
    910import clarin.cmdi.componentregistry.MDMarshaller;
    10 import clarin.cmdi.componentregistry.Owner;
     11import clarin.cmdi.componentregistry.RegistrySpace;
    1112import clarin.cmdi.componentregistry.UserCredentials;
    1213import clarin.cmdi.componentregistry.UserUnauthorizedException;
     
    4546import javax.servlet.ServletContext;
    4647import javax.servlet.http.HttpServletRequest;
     48import javax.servlet.http.HttpServletResponse;
    4749import javax.ws.rs.Consumes;
    4850import javax.ws.rs.DELETE;
     
    7274
    7375/**
    74  * Handles CRUD operations on {@link ComponentDescription}, {@link ProfileDescription} and {@link Comment}s
     76 * Handles CRUD operations on
     77 * {@link ComponentDescription}, {@link ProfileDescription} and {@link Comment}s
     78 *
    7579 * @author twago@mpi.nl
    7680 * @author olsha@mpi.nl
     
    8084@Path("/registry")
    8185@Service
    82 @Transactional(rollbackFor= {Exception.class, ValidationException.class})
     86@Transactional(rollbackFor = {Exception.class, ValidationException.class})
    8387public class ComponentRegistryRestService implements
    84                 IComponentRegistryRestService {
    85 
    86         private final static Logger LOG = LoggerFactory
    87                         .getLogger(IComponentRegistryRestService.class);
    88         @Context
    89         private UriInfo uriInfo;
    90         @Context
    91         private SecurityContext security;
    92         @Context
    93         private HttpServletRequest request;
    94         @Context
    95         private ServletContext servletContext;
    96         @InjectParam(value = "componentRegistryFactory")
    97         private ComponentRegistryFactory componentRegistryFactory;
    98         @InjectParam(value = "mdMarshaller")
    99         private MDMarshaller marshaller;
    100        
    101         @Autowired
    102         private GroupService groupService;
    103 
    104         /**
    105          * Converts userspace boolean to component status. Temporary solution!!!
    106          *
    107          * TODO: Replace all calls to getRegistry that use this by calls using
    108          * ComponentStatus
    109          *
    110          *
    111          *
    112          * @param userSpace
    113          * @return
    114          * @deprecated All calls should go directly to
    115          *             {@link #getRegistry(clarin.cmdi.componentregistry.ComponentStatus)}
    116          */
    117         @Deprecated
    118         private static ComponentStatus getStatus(boolean userSpace) {
    119                 if (userSpace) {
    120                         return ComponentStatus.PRIVATE;
    121                 } else {
    122                         return ComponentStatus.PUBLISHED;
    123                 }
    124         }
    125 
    126         private ComponentRegistry getRegistry(ComponentStatus status) {
    127                 Principal userPrincipal = security.getUserPrincipal();
    128                 UserCredentials userCredentials = getUserCredentials(userPrincipal);
    129                 return getRegistry(status, null, userCredentials);
    130         }
    131 
    132         private ComponentRegistry getRegistry(ComponentStatus status, Owner owner,
    133                         UserCredentials userCredentials) {
    134                 try {
    135                         return componentRegistryFactory.getComponentRegistry(status, owner,
    136                                         userCredentials);
    137                 } catch (UserUnauthorizedException uuEx) {
    138                         LOG.warn("Unauthorized access to {} registry by user {}", status,
    139                                         userCredentials);
    140                         LOG.debug("Details for unauthorized access", uuEx);
    141                         throw new WebApplicationException(uuEx, Status.UNAUTHORIZED);
    142                 }
    143         }
    144 
    145         /**
    146          *
    147          * @return Principal of current request
    148          * @throws IllegalArgumentException
    149          *             If no user principal found
    150          */
    151         private Principal checkAndGetUserPrincipal()
    152                         throws UserUnauthorizedException {
    153                 Principal principal = security.getUserPrincipal();
    154                 if (principal == null) {
    155                         throw new UserUnauthorizedException("no user principal found.");
    156                 }
    157                 return principal;
    158         }
    159 
    160         private UserCredentials getUserCredentials(Principal userPrincipal) {
    161                 UserCredentials userCredentials = null;
    162                 if (userPrincipal != null) {
    163                         userCredentials = new UserCredentials(userPrincipal);
    164                 }
    165                 return userCredentials;
    166         }
    167        
    168         @Override
    169         @GET
    170         @Path("/components")
    171         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    172                         MediaType.APPLICATION_JSON })
    173         public List<ComponentDescription> getRegisteredComponents(
    174                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    175                         @QueryParam(GROUPID_PARAM) String groupId)
    176                         throws ComponentRegistryException {
    177                 long start = System.currentTimeMillis();
    178                
    179                 List<ComponentDescription> components = null;
    180                 ComponentRegistry cr = getRegistry(getStatus(userspace));
    181                 if (groupId == null||groupId.isEmpty())
    182                     components = cr.getComponentDescriptions();
    183                 else {
    184                     Principal principal = security.getUserPrincipal();
    185                     UserCredentials credentials = getUserCredentials(principal);
    186                     components = cr.getComponentDescriptionsInGroup(principal.getName(), groupId);
    187 
    188                 }
    189                 LOG.debug(
    190                                 "Releasing {} registered components into the world ({} millisecs)",
    191                                 components.size(), (System.currentTimeMillis() - start));
    192                 return components;
    193         }
    194 
    195         @Override
    196         @GET
    197         @Path("/profiles")
    198         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    199                         MediaType.APPLICATION_JSON })
    200         public List<ProfileDescription> getRegisteredProfiles(
    201                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    202                         @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor,
    203                         @QueryParam(GROUPID_PARAM) String groupId
    204                         )
    205                         throws ComponentRegistryException {
    206                 long start = System.currentTimeMillis();
    207 
    208                 List<ProfileDescription> profiles;
    209                 ComponentRegistry cr = getRegistry(getStatus(userspace));
    210                 if (metadataEditor) {
    211                     if (groupId == null || groupId.isEmpty())
    212                         profiles = cr.getProfileDescriptionsForMetadaEditor();
    213                     else
    214                         profiles = cr.getProfileDescriptionsForMetadaEditor(groupId);
    215                 } else {
    216                     if (groupId == null || groupId.isEmpty())
    217                         profiles = cr.getProfileDescriptions();
    218                     else
    219                         profiles = cr.getProfileDescriptionsInGroup(groupId);
    220                 }
    221 
    222                 LOG.debug(
    223                                 "Releasing {} registered profiles into the world ({} millisecs)",
    224                                 profiles.size(), (System.currentTimeMillis() - start));
    225                 return profiles;
    226         }
    227 
    228         @Override
    229         @GET
    230         @Path("/components/{componentId}")
    231         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    232                         MediaType.APPLICATION_JSON })
    233         public Response getRegisteredComponent(
    234                         @PathParam("componentId") String componentId,
    235                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace
    236                         )
    237                         throws ComponentRegistryException {
    238                 LOG.debug("Component with id: {} is requested.", componentId);
    239                 CMDComponentSpec mdComponent = getRegistry(getStatus(userspace))
    240                                 .getMDComponent(componentId);
    241                 if (mdComponent == null) {
    242                         return Response.status(Status.NOT_FOUND).build();
    243                 } else {
    244                         return Response.ok(mdComponent).build();
    245                 }
    246         }
    247 
    248         @Override
    249         @GET
    250         @Path("/components/{componentId}/{rawType}")
    251         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
    252         public Response getRegisteredComponentRawType(
    253                         @PathParam("componentId") final String componentId,
    254                         @PathParam("rawType") String rawType) {
    255                 LOG.debug("Component with id: {} and rawType: {} is requested.",
    256                                 componentId, rawType);
    257                 StreamingOutput result = null;
    258                 try {
    259                         final ComponentRegistry registry = findRegistry(componentId,
    260                                         new ComponentClosure());
    261                         if (registry == null) {
    262                                 return Response
    263                                                 .status(Status.NOT_FOUND)
    264                                                 .entity("Id: " + componentId
    265                                                                 + " is not registered, cannot create data.")
    266                                                 .build();
    267                         }
    268                         ComponentDescription desc = registry
    269                                         .getComponentDescription(componentId);
    270                         checkAndThrowDescription(desc, componentId);
    271                         String fileName = desc.getName() + "." + rawType;
    272                         if ("xml".equalsIgnoreCase(rawType)) {
    273                                 result = new StreamingOutput() {
    274                                         @Override
    275                                         public void write(OutputStream output) throws IOException,
    276                                                         WebApplicationException {
    277                                                 try {
    278                                                         registry.getMDComponentAsXml(componentId, output);
    279                                                 } catch (ComponentRegistryException e) {
    280                                                         LOG.warn("Could not retrieve component {}",
    281                                                                         componentId);
    282                                                         LOG.debug("Details", e);
    283                                                         throw new WebApplicationException(e, Response
    284                                                                         .serverError()
    285                                                                         .status(Status.INTERNAL_SERVER_ERROR)
    286                                                                         .build());
    287                                                 }
    288                                         }
    289                                 };
    290                         } else if ("xsd".equalsIgnoreCase(rawType)) {
    291                                 result = new StreamingOutput() {
    292                                         @Override
    293                                         public void write(OutputStream output) throws IOException,
    294                                                         WebApplicationException {
    295                                                 try {
    296                                                         registry.getMDComponentAsXsd(componentId, output);
    297                                                 } catch (ComponentRegistryException e) {
    298                                                         LOG.warn("Could not retrieve component {}",
    299                                                                         componentId);
    300                                                         LOG.debug("Details", e);
    301                                                         throw new WebApplicationException(e, Response
    302                                                                         .serverError()
    303                                                                         .status(Status.INTERNAL_SERVER_ERROR)
    304                                                                         .build());
    305                                                 }
    306 
    307                                         }
    308                                 };
    309                         } else {
    310                                 throw new WebApplicationException(Response
    311                                                 .serverError()
    312                                                 .entity("unsupported rawType: " + rawType
    313                                                                 + " (only xml or xsd are supported)").build());
    314                         }
    315                         return createDownloadResponse(result, fileName);
    316                 } catch (ComponentRegistryException e) {
    317                         LOG.warn("Could not retrieve component {}", componentId);
    318                         LOG.debug("Details", e);
    319                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    320                                         .build();
    321                 }
    322         }
    323 
    324         @Override
    325         public ComponentRegistry findRegistry(String id,
    326                         RegistryClosure<? extends BaseDescription> clos)
    327                         throws ComponentRegistryException {
    328                 BaseDescription desc = null;
    329                 ComponentRegistry result = getRegistry(getStatus(false));
    330                 desc = clos.getDescription(result, id);
    331                 if (desc == null) {
    332                         List<ComponentRegistry> userRegs = componentRegistryFactory
    333                                         .getAllUserRegistries();
    334                         for (ComponentRegistry reg : userRegs) {
    335                                 desc = clos.getDescription(reg, id);
    336                                 if (desc != null) {
    337                                         result = reg;
    338                                         break;
    339                                 }
    340                         }
    341                 }
    342                 return result;
    343         }
    344 
    345         @Override
    346         @GET
    347         @Path("/profiles/{profileId}")
    348         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    349                         MediaType.APPLICATION_JSON })
    350         public Response getRegisteredProfile(
    351                         @PathParam("profileId") String profileId,
    352                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    353                         throws ComponentRegistryException {
    354                 LOG.debug("Profile with id {} is requested.", profileId);
    355                 CMDComponentSpec mdProfile = getRegistry(getStatus(userspace))
    356                                 .getMDProfile(profileId);
    357                 if (mdProfile == null) {
    358                         return Response.status(Status.NOT_FOUND).build();
    359                 } else {
    360                         return Response.ok(mdProfile).build();
    361                 }
    362         }
    363 
    364         @Override
    365         @GET
    366         @Path("/components/usage/{componentId}")
    367         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    368                         MediaType.APPLICATION_JSON })
    369         public List<BaseDescription> getComponentUsage(
    370                         @PathParam("componentId") String componentId,
    371                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    372                         throws ComponentRegistryException {
    373                 try {
    374                         final long start = System.currentTimeMillis();
    375                         ComponentRegistry registry = getRegistry(getStatus(userspace));
    376                         List<ComponentDescription> components = registry
    377                                         .getUsageInComponents(componentId);
    378                         List<ProfileDescription> profiles = registry
    379                                         .getUsageInProfiles(componentId);
    380 
    381                         LOG.debug(
    382                                         "Found {} components and {} profiles that use component {} ({} millisecs)",
    383                                         components.size(), profiles.size(), componentId,
    384                                         (System.currentTimeMillis() - start));
    385 
    386                         List<BaseDescription> usages = new ArrayList<BaseDescription>(
    387                                         components.size() + profiles.size());
    388                         usages.addAll(components);
    389                         usages.addAll(profiles);
    390 
    391                         return usages;
    392                 } catch (ComponentRegistryException e) {
    393                         LOG.warn("Could not retrieve profile usage {}", componentId);
    394                         LOG.debug("Details", e);
    395                         throw e;
    396                 }
    397         }
    398 
    399         @Override
    400         @GET
    401         @Path("/profiles/{profileId}/comments")
    402         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    403                         MediaType.APPLICATION_JSON })
    404         public List<Comment> getCommentsFromProfile(
    405                         @PathParam("profileId") String profileId,
    406                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    407                         throws ComponentRegistryException {
    408                 long start = System.currentTimeMillis();
    409                 final Principal principal = security.getUserPrincipal();
    410                 List<Comment> comments = getRegistry(getStatus(userspace))
    411                                 .getCommentsInProfile(profileId, principal);
    412                 LOG.debug(
    413                                 "Releasing {} registered comments in profile into the world ({} millisecs)",
    414                                 comments.size(), (System.currentTimeMillis() - start));
    415                 return comments;
    416         }
    417 
    418         @Override
    419         @GET
    420         @Path("/components/{componentId}/comments")
    421         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    422                         MediaType.APPLICATION_JSON })
    423         public List<Comment> getCommentsFromComponent(
    424                         @PathParam("componentId") String componentId,
    425                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    426                         throws ComponentRegistryException {
    427                 long start = System.currentTimeMillis();
    428                 final Principal principal = security.getUserPrincipal();
    429                 List<Comment> comments = getRegistry(getStatus(userspace))
    430                                 .getCommentsInComponent(componentId, principal);
    431                 LOG.debug(
    432                                 "Releasing {} registered comments in Component into the world ({} millisecs)",
    433                                 comments.size(), (System.currentTimeMillis() - start));
    434                 return comments;
    435         }
    436 
    437         @Override
    438         @GET
    439         @Path("/profiles/{profileId}/comments/{commentId}")
    440         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    441                         MediaType.APPLICATION_JSON })
    442         public Comment getSpecifiedCommentFromProfile(
    443                         @PathParam("profileId") String profileId,
    444                         @PathParam("commentId") String commentId,
    445                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    446                         throws ComponentRegistryException {
    447                 LOG.debug("Comments of profile with id {} are requested.", commentId);
    448                 final Principal principal = security.getUserPrincipal();
    449                 return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(
    450                                 profileId, commentId, principal);
    451         }
    452 
    453         @Override
    454         @GET
    455         @Path("/components/{componentId}/comments/{commentId}")
    456         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    457                         MediaType.APPLICATION_JSON })
    458         public Comment getSpecifiedCommentFromComponent(
    459                         @PathParam("componentId") String componentId,
    460                         @PathParam("commentId") String commentId,
    461                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    462                         throws ComponentRegistryException {
    463                 LOG.debug("Comments of component with id {} are requested.", commentId);
    464                 final Principal principal = security.getUserPrincipal();
    465                 return getRegistry(getStatus(userspace))
    466                                 .getSpecifiedCommentInComponent(componentId, commentId,
    467                                                 principal);
    468         }
    469 
    470         /**
    471          *
    472          * Purely helper method for my front-end (FLEX) which only does post/get
    473          * requests. The query param is checked and the "proper" method is called.
    474          *
    475          * @param profileId
    476          * @param method
    477          * @return
    478          */
    479         @Override
    480         @POST
    481         @Path("/profiles/{profileId}")
    482         public Response manipulateRegisteredProfile(
    483                         @PathParam("profileId") String profileId,
    484                         @FormParam("method") String method,
    485                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    486                 if ("delete".equalsIgnoreCase(method)) {
    487                         return deleteRegisteredProfile(profileId, userspace);
    488                 } else {
    489                         return Response.ok().build();
    490                 }
    491         }
    492 
    493         @Override
    494         @POST
    495         @Path("/profiles/{profileId}/comments/{commentId}")
    496         public Response manipulateCommentFromProfile(
    497                         @PathParam("profileId") String profileId,
    498                         @PathParam("commentId") String commentId,
    499                         @FormParam("method") String method,
    500                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    501                 if ("delete".equalsIgnoreCase(method)) {
    502                         return deleteCommentFromProfile(profileId, commentId, userspace);
    503                 } else {
    504                         return Response.ok().build();
    505                 }
    506         }
    507 
    508         @Override
    509         @POST
    510         @Path("/components/{componentId}/comments/{commentId}")
    511         public Response manipulateCommentFromComponent(
    512                         @PathParam("componentId") String componentId,
    513                         @PathParam("commentId") String commentId,
    514                         @FormParam("method") String method,
    515                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    516                 if ("delete".equalsIgnoreCase(method)) {
    517                         return deleteCommentFromComponent(componentId, commentId, userspace);
    518                 } else {
    519                         return Response.ok().build();
    520                 }
    521         }
    522 
    523         @Override
    524         @POST
    525         @Path("/profiles/{profileId}/publish")
    526         @Consumes("multipart/form-data")
    527         public Response publishRegisteredProfile(
    528                         @PathParam("profileId") String profileId,
    529                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    530                         @FormDataParam(NAME_FORM_FIELD) String name,
    531                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    532                         @FormDataParam(GROUP_FORM_FIELD) String group,
    533                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    534                 try {
    535                         Principal principal = checkAndGetUserPrincipal();
    536                         ProfileDescription desc = getRegistry(getStatus(true))
    537                                         .getProfileDescription(profileId);
    538                         if (desc != null) {
    539                                 updateDescription(desc, name, description, domainName, group);
    540                                 return register(input, desc, getUserCredentials(principal),
    541                                                 true, new PublishAction(principal));
    542                         } else {
    543                                 LOG.error("Update of nonexistent profile {} failed.", profileId);
    544                                 return Response
    545                                                 .serverError()
    546                                                 .entity("Invalid id, cannot update nonexistent profile")
    547                                                 .build();
    548                         }
    549                 } catch (ComponentRegistryException e) {
    550                         LOG.warn("Could not retrieve profile {}", profileId);
    551                         LOG.debug("Details", e);
    552                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    553                                         .build();
    554                 } catch (UserUnauthorizedException ex) {
    555                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    556                                         .build();
    557                 }
    558         }
    559 
    560         @Override
    561         @POST
    562         @Path("/profiles/{profileId}/update")
    563         @Consumes("multipart/form-data")
    564         public Response updateRegisteredProfile(
    565                         @PathParam("profileId") String profileId,
    566                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    567                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    568                         @FormDataParam(NAME_FORM_FIELD) String name,
    569                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    570                         @FormDataParam(GROUP_FORM_FIELD) String group,
    571                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    572                 try {
    573                         Principal principal = checkAndGetUserPrincipal();
    574                         UserCredentials userCredentials = getUserCredentials(principal);
    575                         ProfileDescription desc = getRegistry(getStatus(userspace))
    576                                         .getProfileDescription(profileId);
    577                         if (desc != null) {
    578                                 updateDescription(desc, name, description, domainName, group);
    579                                 return register(input, desc, userCredentials, userspace,
    580                                                 new UpdateAction(principal));
    581                         } else {
    582                                 LOG.error("Update of nonexistent id (" + profileId
    583                                                 + ") failed.");
    584                                 return Response
    585                                                 .serverError()
    586                                                 .entity("Invalid id, cannot update nonexistent profile")
    587                                                 .build();
    588                         }
    589                 } catch (ComponentRegistryException e) {
    590                         LOG.warn("Could not retrieve profile {}", profileId);
    591                         LOG.debug("Details", e);
    592                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    593                                         .build();
    594                 } catch (UserUnauthorizedException ex) {
    595                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    596                                         .build();
    597                 }
    598 
    599         }
    600 
    601         /**
    602          *
    603          * Purely helper method for my front-end (FLEX) which van only do post/get
    604          * requests. The query param is checked and the "proper" method is called.
    605          *
    606          * @param componentId
    607          * @param method
    608          * @return
    609          */
    610         @Override
    611         @POST
    612         @Path("/components/{componentId}")
    613         public Response manipulateRegisteredComponent(
    614                         @PathParam("componentId") String componentId,
    615                         @FormParam("method") String method,
    616                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    617                 if ("delete".equalsIgnoreCase(method)) {
    618                         return deleteRegisteredComponent(componentId, userspace);
    619                 } else {
    620                         return Response.ok().build();
    621                 }
    622         }
    623 
    624         @Override
    625         @POST
    626         @Path("/components/{componentId}/publish")
    627         @Consumes("multipart/form-data")
    628         public Response publishRegisteredComponent(
    629                         @PathParam("componentId") String componentId,
    630                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    631                         @FormDataParam(NAME_FORM_FIELD) String name,
    632                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    633                         @FormDataParam(GROUP_FORM_FIELD) String group,
    634                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    635                 try {
    636                         Principal principal = checkAndGetUserPrincipal();
    637                         // TODO: Get status from parameter
    638                         ComponentDescription desc = getRegistry(getStatus(true))
    639                                         .getComponentDescription(componentId);
    640                         if (desc != null) {
    641                                 updateDescription(desc, name, description, domainName, group);
    642                                 return register(input, desc, getUserCredentials(principal),
    643                                                 true, new PublishAction(principal));
    644                         } else {
    645                                 LOG.error("Update of nonexistent id (" + componentId
    646                                                 + ") failed.");
    647                                 return Response
    648                                                 .serverError()
    649                                                 .entity("Invalid id, cannot update nonexistent profile")
    650                                                 .build();
    651                         }
    652                 } catch (ComponentRegistryException e) {
    653                         LOG.warn("Could not retrieve component {}", componentId);
    654                         LOG.debug("Details", e);
    655                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    656                                         .build();
    657                 } catch (UserUnauthorizedException ex) {
    658                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    659                                         .build();
    660                 }
    661         }
    662 
    663         @Override
    664         @POST
    665         @Path("/components/{componentId}/update")
    666         @Consumes("multipart/form-data")
    667         public Response updateRegisteredComponent(
    668                         @PathParam("componentId") String componentId,
    669                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    670                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    671                         @FormDataParam(NAME_FORM_FIELD) String name,
    672                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    673                         @FormDataParam(GROUP_FORM_FIELD) String group,
    674                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    675                 try {
    676                         Principal principal = checkAndGetUserPrincipal();
    677                         ComponentDescription desc = getRegistry(getStatus(userspace))
    678                                         .getComponentDescription(componentId);
    679                         if (desc != null) {
    680                                 updateDescription(desc, name, description, domainName, group);
    681                                 return register(input, desc, getUserCredentials(principal),
    682                                                 userspace, new UpdateAction(principal));
    683                         } else {
    684                                 LOG.error("Update of nonexistent id (" + componentId
    685                                                 + ") failed.");
    686                                 return Response
    687                                                 .serverError()
    688                                                 .entity("Invalid id, cannot update nonexistent component")
    689                                                 .build();
    690                         }
    691                 } catch (ComponentRegistryException e) {
    692                         LOG.warn("Could not retrieve component {}", componentId);
    693                         LOG.debug("Details", e);
    694                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    695                                         .build();
    696                 } catch (UserUnauthorizedException ex) {
    697                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    698                                         .build();
    699                 }
    700         }
    701 
    702         private void updateDescription(BaseDescription desc, String name,
    703                         String description, String domainName, String group) {
    704                 desc.setName(name);
    705                 desc.setDescription(description);
    706                 desc.setDomainName(domainName);
    707                 desc.setGroupName(group);
    708                 desc.setRegistrationDate(new Date());
    709         }
    710 
    711         @Override
    712         @DELETE
    713         @Path("/components/{componentId}")
    714         public Response deleteRegisteredComponent(
    715                         @PathParam("componentId") String componentId,
    716                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    717                 try {
    718                         Principal principal = checkAndGetUserPrincipal();
    719                         ComponentRegistry registry = getRegistry(getStatus(userspace));
    720                         LOG.debug("Component with id {} set for deletion.", componentId);
    721                         registry.deleteMDComponent(componentId, principal, false);
    722                 } catch (DeleteFailedException e) {
    723                         LOG.info("Component with id {} deletion failed. Reason: {}",
    724                                         componentId, e.getMessage());
    725                         LOG.debug("Deletion failure details:", e);
    726                         return Response.status(Status.FORBIDDEN)
    727                                         .entity("" + e.getMessage()).build();
    728                 } catch (ComponentRegistryException e) {
    729                         LOG.warn("Component with id " + componentId + " deletion failed.",
    730                                         e);
    731                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    732                                         .build();
    733                 } catch (IOException e) {
    734                         LOG.error("Component with id " + componentId + " deletion failed.",
    735                                         e);
    736                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    737                                         .build();
    738                 } catch (UserUnauthorizedException e) {
    739                         LOG.info("Component with id {} deletion failed: {}", componentId,
    740                                         e.getMessage());
    741                         LOG.debug("Deletion failure details:", e);
    742                         return Response.serverError().status(Status.UNAUTHORIZED)
    743                                         .entity("" + e.getMessage()).build();
    744                 }
    745                 LOG.info("Component with id: {} deleted.", componentId);
    746                 return Response.ok().build();
    747         }
    748 
    749         @Override
    750         @DELETE
    751         @Path("/profiles/{profileId}")
    752         public Response deleteRegisteredProfile(
    753                         @PathParam("profileId") String profileId,
    754                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    755                 try {
    756                         Principal principal = checkAndGetUserPrincipal();
    757                         LOG.debug("Profile with id: {} set for deletion.", profileId);
    758                         getRegistry(getStatus(userspace)).deleteMDProfile(profileId,
    759                                         principal);
    760                 } catch (DeleteFailedException e) {
    761                         LOG.info("Profile with id: {} deletion failed: {}", profileId,
    762                                         e.getMessage());
    763                         LOG.debug("Deletion failure details:", e);
    764                         return Response.serverError().status(Status.FORBIDDEN)
    765                                         .entity("" + e.getMessage()).build();
    766                 } catch (ComponentRegistryException e) {
    767                         LOG.warn("Could not retrieve component", e);
    768                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    769                                         .build();
    770                 } catch (IOException e) {
    771                         LOG.error("Profile with id: " + profileId + " deletion failed.", e);
    772                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    773                                         .build();
    774                 } catch (UserUnauthorizedException e) {
    775                         LOG.info("Profile with id: {} deletion failed: {}", profileId,
    776                                         e.getMessage());
    777                         LOG.debug("Deletion failure details:", e);
    778                         return Response.serverError().status(Status.UNAUTHORIZED)
    779                                         .entity("" + e.getMessage()).build();
    780                 }
    781                 LOG.info("Profile with id: {} deleted.", profileId);
    782                 return Response.ok().build();
    783         }
    784 
    785         @Override
    786         @DELETE
    787         @Path("/profiles/{profileId}/comments/{commentId}")
    788         public Response deleteCommentFromProfile(
    789                         @PathParam("profileId") String profileId,
    790                         @PathParam("commentId") String commentId,
    791                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    792                 try {
    793                         final Principal principal = checkAndGetUserPrincipal();
    794                         final ComponentRegistry registry = getRegistry(getStatus(userspace));
    795                         final Comment comment = registry.getSpecifiedCommentInProfile(
    796                                         profileId, commentId, principal);
    797                         if (comment != null
    798                                         && profileId.equals(comment.getComponentId())) {
    799                                 LOG.debug("Comment with id: {} set for deletion.", commentId);
    800                                 registry.deleteComment(commentId, principal);
    801                         } else {
    802                                 throw new ComponentRegistryException(
    803                                                 "Comment not found for specified profile");
    804                         }
    805                 } catch (DeleteFailedException e) {
    806                         LOG.info("Comment with id: {} deletion failed: {}", commentId,
    807                                         e.getMessage());
    808                         LOG.debug("Deletion failure details:", e);
    809                         return Response.serverError().status(Status.FORBIDDEN)
    810                                         .entity("" + e.getMessage()).build();
    811                 } catch (ComponentRegistryException e) {
    812                         LOG.info("Could not retrieve component", e);
    813                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    814                                         .build();
    815                 } catch (IOException e) {
    816                         LOG.error("Comment with id: " + commentId + " deletion failed.", e);
    817                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    818                                         .build();
    819                 } catch (UserUnauthorizedException e) {
    820                         LOG.info("Comment with id: {} deletion failed: {}", commentId,
    821                                         e.getMessage());
    822                         LOG.debug("Deletion failure details:", e);
    823                         return Response.serverError().status(Status.UNAUTHORIZED)
    824                                         .entity("" + e.getMessage()).build();
    825                 }
    826                 LOG.info("Comment with id: {} deleted.", commentId);
    827                 return Response.ok().build();
    828         }
    829 
    830         @Override
    831         @DELETE
    832         @Path("/components/{componentId}/comments/{commentId}")
    833         public Response deleteCommentFromComponent(
    834                         @PathParam("componentId") String componentId,
    835                         @PathParam("commentId") String commentId,
    836                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    837                 try {
    838                         final Principal principal = checkAndGetUserPrincipal();
    839                         final ComponentRegistry registry = getRegistry(getStatus(userspace));
    840                         final Comment comment = registry.getSpecifiedCommentInComponent(
    841                                         componentId, commentId, principal);
    842                         if (comment != null
    843                                         && componentId.equals(comment.getComponentId())) {
    844                                 LOG.debug("Comment with id: {} set for deletion.", commentId);
    845                                 registry.deleteComment(commentId, principal);
    846                         } else {
    847                                 throw new ComponentRegistryException(
    848                                                 "Comment not found for specified component");
    849                         }
    850                 } catch (DeleteFailedException e) {
    851                         LOG.info("Comment with id: {} deletion failed: {}", commentId,
    852                                         e.getMessage());
    853                         LOG.debug("Deletion failure details:", e);
    854                         return Response.serverError().status(Status.FORBIDDEN)
    855                                         .entity("" + e.getMessage()).build();
    856                 } catch (ComponentRegistryException e) {
    857                         LOG.info("Could not retrieve component", e);
    858                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    859                                         .build();
    860                 } catch (IOException e) {
    861                         LOG.error("Comment with id: " + commentId + " deletion failed.", e);
    862                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    863                                         .build();
    864                 } catch (UserUnauthorizedException e) {
    865                         LOG.info("Comment with id: {} deletion failed: {}", commentId,
    866                                         e.getMessage());
    867                         LOG.debug("Deletion failure details:", e);
    868                         return Response.serverError().status(Status.UNAUTHORIZED)
    869                                         .entity("" + e.getMessage()).build();
    870                 }
    871                 LOG.info("Comment with id: {} deleted.", commentId);
    872                 return Response.ok().build();
    873         }
    874 
    875         @Override
    876         @GET
    877         @Path("/profiles/{profileId}/{rawType}")
    878         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
    879         public Response getRegisteredProfileRawType(
    880                         @PathParam("profileId") final String profileId,
    881                         @PathParam("rawType") String rawType) {
    882                 LOG.debug("Profile with id {} and rawType {} is requested.", profileId,
    883                                 rawType);
    884                 StreamingOutput result = null;
    885                 try {
    886                         final ComponentRegistry registry = findRegistry(profileId,
    887                                         new ProfileClosure());
    888                         if (registry == null) {
    889                                 return Response
    890                                                 .status(Status.NOT_FOUND)
    891                                                 .entity("Id: " + profileId
    892                                                                 + " is not registered, cannot create data.")
    893                                                 .build();
    894                         }
    895                         ProfileDescription desc = registry.getProfileDescription(profileId);
    896                         checkAndThrowDescription(desc, profileId);
    897                         String fileName = desc.getName() + "." + rawType;
    898 
    899                         if ("xml".equalsIgnoreCase(rawType)) {
    900                                 result = new StreamingOutput() {
    901                                         @Override
    902                                         public void write(OutputStream output) throws IOException,
    903                                                         WebApplicationException {
    904                                                 try {
    905                                                         registry.getMDProfileAsXml(profileId, output);
    906                                                 } catch (ComponentRegistryException e) {
    907                                                         LOG.warn("Could not retrieve component {}",
    908                                                                         profileId);
    909                                                         LOG.debug("Details", e);
    910                                                         throw new WebApplicationException(e, Response
    911                                                                         .serverError()
    912                                                                         .status(Status.INTERNAL_SERVER_ERROR)
    913                                                                         .build());
    914                                                 }
    915                                         }
    916                                 };
    917                         } else if ("xsd".equalsIgnoreCase(rawType)) {
    918                                 result = new StreamingOutput() {
    919                                         @Override
    920                                         public void write(OutputStream output) throws IOException,
    921                                                         WebApplicationException {
    922                                                 try {
    923                                                         registry.getMDProfileAsXsd(profileId, output);
    924                                                 } catch (ComponentRegistryException e) {
    925                                                         LOG.warn("Could not retrieve component {}",
    926                                                                         profileId);
    927                                                         LOG.debug("Details", e);
    928                                                         throw new WebApplicationException(e, Response
    929                                                                         .serverError()
    930                                                                         .status(Status.INTERNAL_SERVER_ERROR)
    931                                                                         .build());
    932                                                 }
    933                                         }
    934                                 };
    935                         } else {
    936                                 throw new WebApplicationException(Response
    937                                                 .serverError()
    938                                                 .entity("unsupported rawType: " + rawType
    939                                                                 + " (only xml or xsd are supported)").build());
    940                         }
    941                         return createDownloadResponse(result, fileName);
    942                 } catch (ComponentRegistryException e) {
    943                         LOG.warn("Could not retrieve component {}", profileId);
    944                         LOG.debug("Details", e);
    945                         return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
    946                                         .build();
    947                 }
    948         }
    949 
    950         private void checkAndThrowDescription(BaseDescription desc, String id) {
    951                 if (desc == null) {
    952                         throw new WebApplicationException(Response.serverError()
    953                                         .entity("Incorrect id:" + id + "cannot handle request")
    954                                         .build());
    955                 }
    956         }
    957 
    958         private Response createDownloadResponse(StreamingOutput result,
    959                         String fileName) {
    960                 // Making response so it triggers browsers native save as dialog.
    961                 Response response = Response
    962                                 .ok()
    963                                 .type("application/x-download")
    964                                 .header("Content-Disposition",
    965                                                 "attachment; filename=\"" + fileName + "\"")
    966                                 .entity(result).build();
    967                 return response;
    968 
    969         }
    970 
    971         @Override
    972         @POST
    973         @Path("/profiles")
    974         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    975                         MediaType.APPLICATION_JSON })
    976         @Consumes("multipart/form-data")
    977         public Response registerProfile(
    978                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    979                         @FormDataParam(NAME_FORM_FIELD) String name,
    980                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    981                         @FormDataParam(GROUP_FORM_FIELD) String group,
    982                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
    983                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    984                 try {
    985                         Principal principal = checkAndGetUserPrincipal();
    986                         UserCredentials userCredentials = getUserCredentials(principal);
    987                         ProfileDescription desc = createNewProfileDescription();
    988                         desc.setCreatorName(userCredentials.getDisplayName());
    989                         desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
    990                                                                                                                                 // be created
    991                                                                                                                                 // here, now Id
    992                                                                                                                                 // is
    993                                                                                                                                 // constructed
    994                                                                                                                                 // by impl
    995                         desc.setName(name);
    996                         desc.setDescription(description);
    997                         desc.setGroupName(group);
    998                         desc.setDomainName(domainName);
    999                         LOG.debug("Trying to register Profile: {}", desc);
    1000                         return register(input, desc, userCredentials, userspace,
    1001                                         new NewAction());
    1002                 } catch (UserUnauthorizedException ex) {
    1003                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    1004                                         .build();
    1005                 }
    1006         }
    1007 
    1008         @Override
    1009         @POST
    1010         @Path("/components")
    1011         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1012                         MediaType.APPLICATION_JSON })
    1013         @Consumes("multipart/form-data")
    1014         public Response registerComponent(
    1015                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    1016                         @FormDataParam(NAME_FORM_FIELD) String name,
    1017                         @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    1018                         @FormDataParam(GROUP_FORM_FIELD) String group,
    1019                         @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
    1020                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    1021                 try {
    1022                         Principal principal = checkAndGetUserPrincipal();
    1023                         UserCredentials userCredentials = getUserCredentials(principal);
    1024                         ComponentDescription desc = createNewComponentDescription();
    1025                         desc.setCreatorName(userCredentials.getDisplayName());
    1026                         desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
    1027                                                                                                                                 // be created
    1028                                                                                                                                 // here, now Id
    1029                                                                                                                                 // is
    1030                                                                                                                                 // constructed
    1031                                                                                                                                 // by impl
    1032                         desc.setName(name);
    1033                         desc.setDescription(description);
    1034                         desc.setGroupName(group);
    1035                         desc.setDomainName(domainName);
    1036                         LOG.debug("Trying to register Component: {}", desc);
    1037                         return register(input, desc, userCredentials, userspace,
    1038                                         new NewAction());
    1039                 } catch (UserUnauthorizedException ex) {
    1040                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    1041                                         .build();
    1042                 }
    1043         }
    1044 
    1045         @Override
    1046         @POST
    1047         @Path("/components/{componentId}/comments")
    1048         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1049                         MediaType.APPLICATION_JSON })
    1050         @Consumes("multipart/form-data")
    1051         public Response registerCommentInComponent(
    1052                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    1053                         @PathParam("componentId") String componentId,
    1054                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    1055                         throws ComponentRegistryException {
    1056                 try {
    1057                         Principal principal = checkAndGetUserPrincipal();
    1058                         UserCredentials userCredentials = getUserCredentials(principal);
    1059                         if (null == componentRegistryFactory
    1060                                         .getOrCreateUser(userCredentials)) {
    1061                                 throw new UserUnauthorizedException(
    1062                                                 "Cannot materialize authenticated user");
    1063                         }
    1064                         // TODO: Add user/group param
    1065                         ComponentRegistry registry = getRegistry(getStatus(userspace),
    1066                                         null, userCredentials);
    1067                         ComponentDescription description = registry
    1068                                         .getComponentDescription(componentId);
    1069                         if (description != null) {
    1070                                 LOG.debug("Trying to register comment to {}", componentId);
    1071                                 return registerComment(input, registry, userspace, description,
    1072                                                 principal, userCredentials);
    1073                         } else {
    1074                                 LOG.warn(
    1075                                                 "Attempt to post comment on nonexistent component id {} failed.",
    1076                                                 componentId);
    1077                                 return Response
    1078                                                 .serverError()
    1079                                                 .entity("Invalid id, cannot comment on nonexistent component")
    1080                                                 .build();
    1081                         }
    1082                 } catch (UserUnauthorizedException ex) {
    1083                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    1084                                         .build();
    1085                 }
    1086         }
    1087 
    1088         @Override
    1089         @POST
    1090         @Path("/profiles/{profileId}/comments")
    1091         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1092                         MediaType.APPLICATION_JSON })
    1093         @Consumes("multipart/form-data")
    1094         public Response registerCommentInProfile(
    1095                         @FormDataParam(DATA_FORM_FIELD) InputStream input,
    1096                         @PathParam("profileId") String profileId,
    1097                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace)
    1098                         throws ComponentRegistryException {
    1099                 try {
    1100                         Principal principal = checkAndGetUserPrincipal();
    1101                         UserCredentials userCredentials = getUserCredentials(principal);
    1102                         if (null == componentRegistryFactory
    1103                                         .getOrCreateUser(userCredentials)) {
    1104                                 throw new UserUnauthorizedException(
    1105                                                 "Cannot materialize authenticated user");
    1106                         }
    1107                         // TODO: Add user/group param
    1108                         ComponentRegistry registry = getRegistry(getStatus(userspace),
    1109                                         null, userCredentials);
    1110                         ProfileDescription description = registry
    1111                                         .getProfileDescription(profileId);
    1112                         if (description != null) {
    1113                                 LOG.debug("Trying to register comment to {}", profileId);
    1114                                 return registerComment(input, registry, userspace, description,
    1115                                                 principal, userCredentials);
    1116                         } else {
    1117                                 LOG.warn(
    1118                                                 "Attempt to post comment on nonexistent profile id {} failed.",
    1119                                                 profileId);
    1120                                 return Response
    1121                                                 .serverError()
    1122                                                 .entity("Invalid id, cannot comment on nonexistent profile")
    1123                                                 .build();
    1124                         }
    1125                 } catch (UserUnauthorizedException ex) {
    1126                         return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage())
    1127                                         .build();
    1128                 }
    1129         }
    1130 
    1131         @Override
    1132         @GET
    1133         @Path("/pingSession")
    1134         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1135                         MediaType.APPLICATION_JSON })
    1136         public Response pingSession() {
    1137                 boolean stillActive = false;
    1138                 Principal userPrincipal = security.getUserPrincipal();
    1139                 if (LOG.isInfoEnabled()) {
    1140                         LOG.debug("ping by <{}>",
    1141                                         (userPrincipal == null ? "unauthorized user"
    1142                                                         : userPrincipal.getName()));
    1143                 }
    1144                 if (request != null) {
    1145                         if (userPrincipal != null
    1146                                         && !ComponentRegistryFactory.ANONYMOUS_USER
    1147                                                         .equals(userPrincipal.getName())) {
    1148                                 stillActive = !((HttpServletRequest) request).getSession()
    1149                                                 .isNew();
    1150                         }
    1151                 }
    1152                 return Response
    1153                                 .ok()
    1154                                 .entity(String.format("<session stillActive=\"%s\"/>",
    1155                                                 stillActive)).build();
    1156         }
    1157 
    1158         private Response register(InputStream input, BaseDescription desc,
    1159                         UserCredentials userCredentials, boolean userspace,
    1160                         RegisterAction action) {
    1161                 try {
    1162                         // TODO: Add user/group param
    1163                         ComponentRegistry registry = getRegistry(getStatus(userspace),
    1164                                         null, userCredentials);
    1165                         DescriptionValidator descriptionValidator = new DescriptionValidator(
    1166                                         desc);
    1167                         MDValidator validator = new MDValidator(input, desc, registry,
    1168                                         getRegistry(getStatus(true)),
    1169                                         componentRegistryFactory.getPublicRegistry(), marshaller);
    1170                         RegisterResponse response = new RegisterResponse();
    1171                         response.setIsInUserSpace(userspace);
    1172                         validate(response, descriptionValidator, validator);
    1173                         if (response.getErrors().isEmpty()) {
    1174 
    1175                                 CMDComponentSpec spec = validator.getCMDComponentSpec();
    1176 
    1177                                 // removing filename from spec before it gets extended.
    1178                                 // recursion over all the components
    1179                                 setFileNamesFromListToNull(Collections.singletonList(spec.getCMDComponent()));
    1180 
    1181                                 try {
    1182                                         checkForRecursion(validator, registry, desc);
    1183 
    1184                                         // Add profile
    1185                                         int returnCode = action.execute(desc, spec, response,
    1186                                                         registry);
    1187                                         if (returnCode == 0) {
    1188                                                 response.setRegistered(true);
    1189                                                 response.setDescription(desc);
    1190                                         } else {
    1191                                                 response.setRegistered(false);
    1192                                                 response.addError("Unable to register at this moment. Internal server error.");
    1193                                         }
    1194                                 } catch (ComponentRegistryException ex) {
    1195                                         // Recursion detected
    1196                                         response.setRegistered(false);
    1197                                         response.addError("Error while expanding specification. "
    1198                                                         + ex.getMessage());
    1199                                 }
    1200                         } else {
    1201                                 LOG.warn("Registration failed with validation errors: {}",
    1202                                                 Arrays.toString(response.getErrors().toArray()));
    1203                                 response.setRegistered(false);
    1204                         }
    1205                         LOG.info("Registered new {} {}", desc.isProfile() ? "profile"
    1206                                         : "component", desc);
    1207                         response.setIsProfile(desc.isProfile());
    1208                         return Response.ok(response).build();
    1209                 } finally {
    1210                         try {
    1211                                 input.close();// either we read the input or there was an
    1212                                                                 // exception, we need to close it.
    1213                         } catch (IOException e) {
    1214                                 LOG.error("Error when closing inputstream: ", e);
    1215                         }
    1216                 }
    1217         }
    1218 
    1219         /**
    1220          *
    1221          * @param validator
    1222          * @param registry
    1223          * @param desc
    1224          * @throws ComponentRegistryException
    1225          *             if recursion is detected or something goes wrong while trying
    1226          *             to detect recursion
    1227          */
    1228         private void checkForRecursion(MDValidator validator,
    1229                         ComponentRegistry registry, BaseDescription desc)
    1230                         throws ComponentRegistryException {
    1231                 try {
    1232                         // Expand to check for recursion. Operate on copy so that original
    1233                         // does not get expanded.
    1234                         final CMDComponentSpec specCopy = validator
    1235                                         .getCopyOfCMDComponentSpec();
    1236                         // In case of recursion, the following will throw a
    1237                         // ComponentRegistryException
    1238                         registry.getExpander().expandNestedComponent(
    1239                                         Lists.newArrayList(specCopy.getCMDComponent()), desc.getId());
    1240                 } catch (JAXBException ex) {
    1241                         throw new ComponentRegistryException(
    1242                                         "Unmarshalling failed while preparing recursion detection",
    1243                                         ex);
    1244                 }
    1245         }
    1246 
    1247         private Response registerComment(InputStream input,
    1248                         ComponentRegistry registry, boolean userspace,
    1249                         BaseDescription description, Principal principal,
    1250                         UserCredentials userCredentials) {
    1251                 try {
    1252                         CommentValidator validator = new CommentValidator(input,
    1253                                         description, marshaller);
    1254                         CommentResponse response = new CommentResponse();
    1255                         response.setIsInUserSpace(userspace);
    1256                         validateComment(response, validator);
    1257                         if (response.getErrors().isEmpty()) {
    1258                                 Comment com = validator.getCommentSpec();
    1259                                 // int returnCode = action.executeComment(com, response,
    1260                                 // registry, principal.getName());
    1261 
    1262                                 // If user name is left empty, fill it using the user's display
    1263                                 // name
    1264                                 if (null == com.getUserName() || "".equals(com.getUserName())) {
    1265                                         if (userCredentials != null) {
    1266                                                 com.setUserName(userCredentials.getDisplayName());
    1267                                         } else {
    1268                                                 com.setUserName(principal.getName());
    1269                                         }
    1270                                 }
    1271 
    1272                                 int returnCode = registry.registerComment(com,
    1273                                                 principal.getName());
    1274                                 if (returnCode == 0) {
    1275                                         response.setRegistered(true);
    1276                                         response.setComment(com);
    1277                                 } else {
    1278                                         response.setRegistered(false);
    1279                                         response.addError("Unable to post at this moment. Internal server error.");
    1280                                 }
    1281                                 if (com.getComponentId() != null) {
    1282                                         LOG.info("Posted new comment on component {}",
    1283                                                         com.getComponentId());
    1284                                 } else {
    1285                                         LOG.info("Posted new comment on profile {}",
    1286                                                         com.getComponentId());
    1287                                 }
    1288                         } else {
    1289                                 LOG.warn(
    1290                                                 "Posting of comment failed with validation errors: {}",
    1291                                                 Arrays.toString(response.getErrors().toArray()));
    1292                                 response.setRegistered(false);
    1293                         }
    1294                         return Response.ok(response).build();
    1295                 } catch (ComponentRegistryException ex) {
    1296                         LOG.error("Error while inserting comment: ", ex);
    1297                         return Response.serverError().entity(ex.getMessage()).build();
    1298                 } finally {
    1299                         try {
    1300                                 input.close();// either we read the input or there was an
    1301                                                                 // exception, we need to close it.
    1302                         } catch (IOException e) {
    1303                                 LOG.error("Error when closing inputstream: ", e);
    1304                                 return Response.serverError().build();
    1305                         }
    1306                 }
    1307         }
    1308 
    1309         private ComponentDescription createNewComponentDescription() {
    1310                 ComponentDescription desc = ComponentDescription.createNewDescription();
    1311                 desc.setHref(createXlink(desc.getId()));
    1312                 return desc;
    1313         }
    1314 
    1315         private ProfileDescription createNewProfileDescription() {
    1316                 ProfileDescription desc = ProfileDescription.createNewDescription();
    1317                 desc.setHref(createXlink(desc.getId()));
    1318                 return desc;
    1319         }
    1320 
    1321         private String createXlink(String id) {
    1322                 URI uri = uriInfo.getRequestUriBuilder().path(id).build();
    1323                 return uri.toString();
    1324         }
    1325 
    1326         /**
    1327          *
    1328          * @return The application's base URI as configured in the
    1329          *         {@link #APPLICATION_BASE_URL_PARAM} context parameter. If
    1330          *         correctly configured, it should look something like
    1331          *         "http://catalog.clarin.eu/ds/ComponentRegistry".
    1332          *         <em>Be aware that this
    1333          * can also be null if configured incorrectly!</em>
    1334          *
    1335          * @see #APPLICATION_BASE_URL_PARAM
    1336          */
    1337         private String getApplicationBaseURI() {
    1338                 return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
    1339         }
    1340 
    1341         private void validate(RegisterResponse response, Validator... validators) {
    1342                 for (Validator validator : validators) {
    1343                         if (!validator.validate()) {
    1344                                 for (String error : validator.getErrorMessages()) {
    1345                                         response.addError(error);
    1346                                 }
    1347                         }
    1348                 }
    1349         }
    1350 
    1351         private void validateComment(CommentResponse response,
    1352                         Validator... validators) {
    1353                 for (Validator validator : validators) {
    1354                         if (!validator.validate()) {
    1355                                 for (String error : validator.getErrorMessages()) {
    1356                                         response.addError(error);
    1357                                 }
    1358                         }
    1359                 }
    1360         }
    1361 
    1362         /**
    1363          * @param componentRegistryFactory
    1364          *            the componentRegistryFactory to set
    1365          */
    1366         @Override
    1367         public void setComponentRegistryFactory(
    1368                         ComponentRegistryFactory componentRegistryFactory) {
    1369                 this.componentRegistryFactory = componentRegistryFactory;
    1370         }
    1371 
    1372         /**
    1373          *
    1374          * @param listofcomponents
    1375          *            a list of components whose file-names and whose childrens'
    1376          *            filenames are to be set to null
    1377          */
    1378         @Override
    1379         public void setFileNamesFromListToNull(
    1380                         List<CMDComponentType> listofcomponents) {
    1381 
    1382                 for (CMDComponentType currentcomponent : listofcomponents) {
    1383                         setFileNamesToNullCurrent(currentcomponent);
    1384                 }
    1385 
    1386         }
    1387 
    1388         /**
    1389          *
    1390          * @param currentcomponent
    1391          *            a component whose file-name and whose children filenames are
    1392          *            to be set to null
    1393          */
    1394         protected void setFileNamesToNullCurrent(CMDComponentType currentcomponent) {
    1395                 currentcomponent.setFilename(null);
    1396                 setFileNamesFromListToNull(currentcomponent.getCMDComponent());
    1397         }
    1398 
    1399         /**
    1400          *
    1401          * @param userspace
    1402          *            if "true" then profiles and components from the user's
    1403          *            workspace, otherwise -- public
    1404          * @param limit
    1405          *            the number of items to be displayed
    1406          * @return rss for the components in the database to which we are currently
    1407          *         connected
    1408          * @throws ComponentRegistryException
    1409          * @throws ParseException
    1410          */
    1411         @Override
    1412         @GET
    1413         @Path("/components/rss")
    1414         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1415                         MediaType.APPLICATION_JSON })
    1416         public Rss getRssComponent(
    1417                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    1418                         @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
    1419                         throws ComponentRegistryException, ParseException {
    1420                 final List<ComponentDescription> components = getRegistry(
    1421                                 getStatus(userspace)).getComponentDescriptions();
    1422                 final RssCreatorDescriptions instance = new RssCreatorDescriptions(
    1423                                 userspace, getApplicationBaseURI(), "components",
    1424                                 Integer.parseInt(limit), components,
    1425                                 ComponentUtils.COMPARE_ON_DATE);
    1426                 final Rss rss = instance.getRss();
    1427                 LOG.debug("Releasing RSS of {} most recently registered components",
    1428                                 limit);
    1429                 return rss;
    1430         }
    1431 
    1432         /**
    1433          *
    1434          * @param userspace
    1435          *            if "true" then profiles and components from the user's
    1436          *            workspace, otherwise -- public
    1437          * @param limit
    1438          *            the number of items to be displayed
    1439          * @return rss for the profiles in the database to which we are currently
    1440          *         connected
    1441          * @throws ComponentRegistryException
    1442          * @throws ParseException
    1443          */
    1444         @Override
    1445         @GET
    1446         @Path("/profiles/rss")
    1447         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1448                         MediaType.APPLICATION_JSON })
    1449         public Rss getRssProfile(
    1450                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    1451                         @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
    1452                         throws ComponentRegistryException, ParseException {
    1453                 final List<ProfileDescription> profiles = getRegistry(
    1454                                 getStatus(userspace)).getProfileDescriptions();
    1455                 final RssCreatorDescriptions instance = new RssCreatorDescriptions(
    1456                                 userspace, getApplicationBaseURI(), "profiles",
    1457                                 Integer.parseInt(limit), profiles,
    1458                                 ComponentUtils.COMPARE_ON_DATE);
    1459                 final Rss rss = instance.getRss();
    1460                 LOG.debug("Releasing RSS of {} most recently registered profiles",
    1461                                 limit);
    1462                 return rss;
    1463         }
    1464 
    1465         /**
    1466          *
    1467          * @param profileId
    1468          *            the Id of a profile whose comments are to be rss-ed
    1469          * @param userspace
    1470          *            if "true" then profiles and components from the user's
    1471          *            workspace, otherwise -- public
    1472          * @param limit
    1473          *            the number of items to be displayed
    1474          * @return rss of the comments for a chosen profile
    1475          * @throws ComponentRegistryException
    1476          * @throws IOException
    1477          * @throws JAXBException
    1478          * @throws ParseException
    1479          */
    1480         @Override
    1481         @GET
    1482         @Path("/profiles/{profileId}/comments/rss")
    1483         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1484                         MediaType.APPLICATION_JSON })
    1485         public Rss getRssOfCommentsFromProfile(
    1486                         @PathParam("profileId") String profileId,
    1487                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    1488                         @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
    1489                         throws ComponentRegistryException, IOException, JAXBException,
    1490                         ParseException {
    1491                 final Principal principal = security.getUserPrincipal();
    1492                 final List<Comment> comments = getRegistry(getStatus(userspace))
    1493                                 .getCommentsInProfile(profileId, principal);
    1494                 final String profileName = getRegistry(getStatus(userspace))
    1495                                 .getProfileDescription(profileId).getName();
    1496                 final RssCreatorComments instance = new RssCreatorComments(userspace,
    1497                                 getApplicationBaseURI(), Integer.parseInt(limit), profileId,
    1498                                 profileName, "profile", comments, Comment.COMPARE_ON_DATE);
    1499                 final Rss rss = instance.getRss();
    1500                 LOG.debug("Releasing RSS of {} most recent post on profile {}", limit,
    1501                                 profileId);
    1502                 return rss;
    1503         }
    1504 
    1505         /**
    1506          *
    1507          * @param componentId
    1508          *            the Id of a component whose comments are to be rss-ed
    1509          * @param userspace
    1510          *            if "true" then profiles and components from the user's
    1511          *            workspace, otherwise -- public
    1512          * @param limit
    1513          *            the number of items to be displayed
    1514          * @return rss of the comments for a chosen component
    1515          * @throws ComponentRegistryException
    1516          * @throws IOException
    1517          * @throws JAXBException
    1518          * @throws ParseException
    1519          */
    1520         @Override
    1521         @GET
    1522         @Path("/components/{componentId}/comments/rss")
    1523         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1524                         MediaType.APPLICATION_JSON })
    1525         public Rss getRssOfCommentsFromComponent(
    1526                         @PathParam("componentId") String componentId,
    1527                         @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    1528                         @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
    1529                         throws ComponentRegistryException, IOException, JAXBException,
    1530                         ParseException {
    1531                 final Principal principal = security.getUserPrincipal();
    1532                 final List<Comment> comments = getRegistry(getStatus(userspace))
    1533                                 .getCommentsInComponent(componentId, principal);
    1534                 final String componentName = getRegistry(getStatus(userspace))
    1535                                 .getComponentDescription(componentId).getName();
    1536                 final RssCreatorComments instance = new RssCreatorComments(userspace,
    1537                                 getApplicationBaseURI(), Integer.parseInt(limit), componentId,
    1538                                 componentName, "component", comments, Comment.COMPARE_ON_DATE);
    1539                 final Rss rss = instance.getRss();
    1540                 LOG.debug("Releasing RSS of {} most recent post on component {}",
    1541                                 limit, componentId);
    1542                 return rss;
    1543         }
    1544 
    1545         @Override
    1546         @GET
    1547         @Path("/AllowedTypes")
    1548         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1549                         MediaType.APPLICATION_JSON })
    1550         public AllowedAttributetypesXML getAllowedAttributeTypes()
    1551                         throws ComponentRegistryException, IOException, JAXBException,
    1552                         ParseException {
    1553                 return (new AllowedAttributetypesXML());
    1554         }
    1555 
    1556         @Override
    1557         @GET
    1558         @Path("/groups/usermembership")
    1559         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1560                         MediaType.APPLICATION_JSON })
    1561         public List<Group> getGroupsTheCurrentUserIsAMemberOf() {
    1562             Principal principal = security.getUserPrincipal();
    1563             if (principal == null)
    1564                 return new ArrayList<Group>();
    1565             List<Group> groups = groupService.getGroupsOfWhichUserIsAMember(principal.getName());
    1566             return groups;
    1567         }
    1568 
    1569         @Override
    1570         @GET
    1571         @Path("/items/{itemId}/groups")
    1572         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1573                         MediaType.APPLICATION_JSON })
    1574         public List<Group> getGroupsTheItemIsAMemberOf(@PathParam("itemId") String itemId) {
    1575             return groupService.getGroupsTheItemIsAMemberOf(itemId);
    1576         }
    1577        
    1578         @Override
    1579         @POST
    1580         @Path("/items/{itemId}/transferownership")
    1581         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1582                         MediaType.APPLICATION_JSON })
    1583         public void transferItemOwnershipToGroup(@PathParam("itemId") String itemId, @QueryParam("groupId") long groupId) {
    1584             Principal principal = security.getUserPrincipal();
    1585             groupService.transferItemOwnershipFromUserToGroupId(principal.getName(), groupId, itemId);
    1586         }
    1587 
    1588         @Override
    1589         @GET
    1590         @Path("/items/{itemId}")
    1591         @Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML,
    1592                         MediaType.APPLICATION_JSON })
    1593         public BaseDescription getComponentDescription(@PathParam("itemId") String itemId) throws ComponentRegistryException{
    1594                         LOG.debug("Item with id: {} is requested.", itemId);
    1595                         BaseDescription description = getRegistry(getStatus(false)).getComponentDescription(itemId);
    1596                         if (description == null)
    1597                                 description = getRegistry(getStatus(true)).getComponentDescription(itemId);
    1598                         if (description == null)
    1599                                 description = getRegistry(getStatus(false)).getProfileDescription(itemId);
    1600                         if (description == null)
    1601                                 description = getRegistry(getStatus(true)).getProfileDescription(itemId);
    1602                         return description;
    1603         }
    1604 
     88        IComponentRegistryRestService {
     89
     90    private final static Logger LOG = LoggerFactory
     91            .getLogger(IComponentRegistryRestService.class);
     92    @Context
     93    private UriInfo uriInfo;
     94    @Context
     95    private SecurityContext security;
     96    @Context
     97    private HttpServletRequest request;
     98    @Context
     99    private HttpServletResponse response;
     100    @Context
     101    private ServletContext servletContext;
     102    @InjectParam(value = "componentRegistryFactory")
     103    private ComponentRegistryFactory componentRegistryFactory;
     104    @InjectParam(value = "mdMarshaller")
     105    private MDMarshaller marshaller;
     106    @Autowired
     107    private GroupService groupService;
     108
     109    private ComponentRegistry getBaseRegistry() throws AuthenticationFailException {
     110        Principal userPrincipal = this.checkAndGetUserPrincipal();
     111        UserCredentials userCredentials = this.getUserCredentials(userPrincipal);
     112        return componentRegistryFactory.getBaseRegistry(userCredentials);
     113    }
     114
     115    private ComponentRegistry getRegistry(RegistrySpace space, Number groupId) {
     116        Principal userPrincipal = security.getUserPrincipal();
     117        UserCredentials userCredentials = this.getUserCredentials(userPrincipal);
     118        try {
     119            return componentRegistryFactory.getComponentRegistry(space, null, userCredentials, groupId);
     120        } catch (UserUnauthorizedException uuEx) {
     121            LOG.warn("Unauthorized access to {} registry by user {}", space,
     122                    userCredentials);
     123            LOG.debug("Details for unauthorized access", uuEx);
     124            throw new WebApplicationException(uuEx, Status.FORBIDDEN);
     125        }
     126    }
     127
     128    /**
     129     *
     130     * @return Principal of current request
     131     * @throws IllegalArgumentException If no user principal found
     132     */
     133    private Principal checkAndGetUserPrincipal()
     134            throws AuthenticationFailException {
     135        Principal principal = security.getUserPrincipal();
     136        if (principal == null) {
     137            throw new AuthenticationFailException("No user principal found.");
     138        }
     139        return principal;
     140    }
     141
     142    private UserCredentials getUserCredentials(Principal userPrincipal) {
     143        UserCredentials userCredentials = null;
     144        if (userPrincipal != null) {
     145            userCredentials = new UserCredentials(userPrincipal);
     146        }
     147        return userCredentials;
     148    }
     149
     150    private ComponentRegistry initialiseRegistry(String space, String groupId) throws AuthenticationFailException {
     151        //checking credentials
     152        RegistrySpace regSpace = RegistrySpace.valueOf(space.toUpperCase());
     153        UserCredentials user = this.getUserCredentials(this.checkAndGetUserPrincipal());
     154        // initializing the registry
     155        Number groupIdNumber = null;
     156        if (groupId != null && !groupId.isEmpty()) {
     157            groupIdNumber = Integer.parseInt(groupId);
     158        }
     159
     160        return this.getRegistry(regSpace, groupIdNumber);
     161    }
     162
     163    @Override
     164    @GET
     165    @Path("/components")
     166    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     167        MediaType.APPLICATION_JSON})
     168    public List<ComponentDescription> getRegisteredComponents(
     169            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
     170            @QueryParam(GROUPID_PARAM) String groupId)
     171            throws ComponentRegistryException, IOException {
     172        long start = System.currentTimeMillis();
     173
     174        try {
     175            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
     176            List<ComponentDescription> result = cr.getComponentDescriptions();
     177            LOG.debug(
     178                    "Releasing {} registered components into the world ({} millisecs)",
     179                    result.size(), (System.currentTimeMillis() - start));
     180            return result;
     181        } catch (AuthenticationFailException e) {
     182            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     183            return new ArrayList<ComponentDescription>();
     184
     185        } catch (UserUnauthorizedException e) {
     186            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
     187            return new ArrayList<ComponentDescription>();
     188
     189        }
     190
     191    }
     192
     193    @Override
     194    @GET
     195    @Path("/profiles")
     196    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     197        MediaType.APPLICATION_JSON})
     198    public List<ProfileDescription> getRegisteredProfiles(
     199            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
     200            @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor,
     201            @QueryParam(GROUPID_PARAM) String groupId)
     202            throws ComponentRegistryException, IOException {
     203
     204        long start = System.currentTimeMillis();
     205        try {
     206            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
     207            List<ProfileDescription> result = (metadataEditor) ? cr.getProfileDescriptionsForMetadaEditor() : cr.getProfileDescriptions();
     208            LOG.debug(
     209                    "Releasing {} registered components into the world ({} millisecs)",
     210                    result.size(), (System.currentTimeMillis() - start));
     211            return result;
     212        } catch (AuthenticationFailException e) {
     213            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     214            return new ArrayList<ProfileDescription>();
     215
     216        } catch (UserUnauthorizedException e) {
     217            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
     218            return new ArrayList<ProfileDescription>();
     219        }
     220    }
     221
     222    @Override
     223    @GET
     224    @Path("/components/{componentId}")
     225    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     226        MediaType.APPLICATION_JSON})
     227    public Response getRegisteredComponent(
     228            @PathParam("componentId") String componentId) throws IOException {
     229        LOG.debug("Component with id: {} is requested.", componentId);
     230        try {
     231            CMDComponentSpec mdComponent = this.getBaseRegistry().getMDComponentAccessControlled(componentId);
     232            return Response.ok(mdComponent).build();
     233        } catch (ItemNotFoundException e) {
     234            return Response.status(Status.NOT_FOUND).build();
     235        } catch (ComponentRegistryException e1) {
     236            return Response.serverError().status(Status.CONFLICT).build();
     237        } catch (AuthenticationFailException e) {
     238            return Response.serverError().status(Status.UNAUTHORIZED).build();
     239        } catch (UserUnauthorizedException e) {
     240            return Response.serverError().status(Status.FORBIDDEN).build();
     241        }
     242    }
     243
     244    @Override
     245    @GET
     246    @Path("/profiles/{profileId}")
     247    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     248        MediaType.APPLICATION_JSON})
     249    public Response getRegisteredProfile(
     250            @PathParam("profileId") String profileId) throws IOException {
     251        LOG.debug("Profile with id {} is requested.", profileId);
     252        try {
     253            CMDComponentSpec mdProfile = this.getBaseRegistry().getMDProfileAccessControled(profileId);
     254            return Response.ok(mdProfile).build();
     255        } catch (ItemNotFoundException e) {
     256            return Response.status(Status.NOT_FOUND).build();
     257        } catch (ComponentRegistryException e1) {
     258            return Response.serverError().status(Status.CONFLICT).build();
     259        } catch (UserUnauthorizedException e) {
     260            return Response.serverError().status(Status.FORBIDDEN).build();
     261        } catch (AuthenticationFailException e) {
     262            return Response.serverError().status(Status.UNAUTHORIZED).build();
     263        }
     264    }
     265
     266    @Override
     267    @GET
     268    @Path("/components/{componentId}/{rawType}")
     269    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
     270    public Response getRegisteredComponentRawType(
     271            @PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) throws ComponentRegistryException {
     272
     273        LOG.debug("Component with id: {} and rawType: {} is requested.", componentId, rawType);
     274        try {
     275            final ComponentRegistry registry = this.getBaseRegistry();
     276            try {
     277                ComponentDescription desc = registry.getComponentDescriptionAccessControlled(componentId);
     278                StreamingOutput result = null;
     279                String fileName = desc.getName() + "." + rawType;
     280                if ("xml".equalsIgnoreCase(rawType)) {
     281                    result = new StreamingOutput() {
     282                        @Override
     283                        public void write(OutputStream output) throws IOException,
     284                                WebApplicationException {
     285                            try {
     286                                try {
     287                                    try {
     288                                        registry.getMDComponentAsXml(componentId, output);
     289                                    } catch (ItemNotFoundException e1) {
     290                                        LOG.warn("Could not retrieve component {}",
     291                                                componentId);
     292                                        LOG.debug("Details", e1);
     293                                        throw new WebApplicationException(e1, Response
     294                                                .serverError()
     295                                                .status(Status.INTERNAL_SERVER_ERROR)
     296                                                .build());
     297                                    }
     298                                } catch (ComponentRegistryException e) {
     299                                    LOG.warn("Could not retrieve component {}",
     300                                            componentId);
     301                                    LOG.debug("Details", e);
     302                                    throw new WebApplicationException(e, Response
     303                                            .serverError()
     304                                            .status(Status.INTERNAL_SERVER_ERROR)
     305                                            .build());
     306                                }
     307
     308                            } catch (UserUnauthorizedException e2) {
     309                                LOG.error(e2.toString());
     310                            }
     311                        }
     312                    };
     313                } else if ("xsd".equalsIgnoreCase(rawType)) {
     314                    result = new StreamingOutput() {
     315                        @Override
     316                        public void write(OutputStream output) throws IOException,
     317                                WebApplicationException {
     318                            try {
     319                                try {
     320                                    try {
     321                                        registry.getMDComponentAsXsd(componentId, output);
     322                                    } catch (ItemNotFoundException e1) {
     323                                        LOG.warn("Could not retrieve component {}",
     324                                                componentId);
     325                                        LOG.debug("Details", e1);
     326                                        throw new WebApplicationException(e1, Response
     327                                                .serverError()
     328                                                .status(Status.INTERNAL_SERVER_ERROR)
     329                                                .build());
     330                                    }
     331                                } catch (ComponentRegistryException e) {
     332                                    LOG.warn("Could not retrieve component {}",
     333                                            componentId);
     334                                    LOG.debug("Details", e);
     335                                    throw new WebApplicationException(e, Response
     336                                            .serverError()
     337                                            .status(Status.INTERNAL_SERVER_ERROR)
     338                                            .build());
     339                                }
     340                            } catch (UserUnauthorizedException e2) {
     341                                LOG.error(e2.toString());
     342                            }
     343
     344                        }
     345                    };
     346                } else {
     347                    throw new WebApplicationException(Response
     348                            .serverError()
     349                            .entity("unsupported rawType: " + rawType
     350                            + " (only xml or xsd are supported)").build());
     351                }
     352                return createDownloadResponse(result, fileName);
     353
     354            } catch (UserUnauthorizedException e2) {
     355                return Response.status(Status.FORBIDDEN).build();
     356            }
     357        } catch (ItemNotFoundException e3) {
     358            return Response.status(Status.NOT_FOUND).build();
     359        } catch (AuthenticationFailException e) {
     360            return Response.serverError().status(Status.UNAUTHORIZED).build();
     361        }
     362    }
     363
     364    @Override
     365    @GET
     366    @Path("/components/usage/{componentId}")
     367    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     368        MediaType.APPLICATION_JSON})
     369    public List<BaseDescription> getComponentUsage(
     370            @PathParam("componentId") String componentId) throws ComponentRegistryException, IOException {
     371
     372        final long start = System.currentTimeMillis();
     373        try {
     374            ComponentRegistry registry = this.getBaseRegistry();
     375            List<ComponentDescription> components = registry.getUsageInComponents(componentId);
     376            List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
     377
     378            LOG.debug(
     379                    "Found {} components and {} profiles that use component {} ({} millisecs)",
     380                    components.size(), profiles.size(), componentId,
     381                    (System.currentTimeMillis() - start));
     382
     383            List<BaseDescription> usages = new ArrayList<BaseDescription>(components.size() + profiles.size());
     384            usages.addAll(components);
     385            usages.addAll(profiles);
     386
     387            return usages;
     388        } catch (ComponentRegistryException e) {
     389            LOG.warn("Could not retrieve profile usage {}", componentId);
     390            LOG.debug("Details", e);
     391            return new ArrayList<BaseDescription>();
     392        } catch (AuthenticationFailException e1) {
     393            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     394            return new ArrayList<BaseDescription>();
     395        }
     396    }
     397
     398    @Override
     399    @GET
     400    @Path("/profiles/{profileId}/comments")
     401    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     402        MediaType.APPLICATION_JSON})
     403    public List<Comment> getCommentsFromProfile(
     404            @PathParam("profileId") String profileId)
     405            throws ComponentRegistryException, IOException {
     406        long start = System.currentTimeMillis();
     407        try {
     408            List<Comment> comments = this.getBaseRegistry().getCommentsInProfile(profileId);
     409            LOG.debug(
     410                    "Releasing {} registered comments in profile into the world ({} millisecs)",
     411                    comments.size(), (System.currentTimeMillis() - start));
     412            return comments;
     413        } catch (ItemNotFoundException e) {
     414            response.sendError(Status.NOT_FOUND.getStatusCode());
     415            return new ArrayList<Comment>();
     416
     417        } catch (UserUnauthorizedException e) {
     418            response.sendError(Status.FORBIDDEN.getStatusCode());
     419            return new ArrayList<Comment>();
     420        } catch (AuthenticationFailException e1) {
     421            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     422            return new ArrayList<Comment>();
     423        }
     424    }
     425
     426    @Override
     427    @GET
     428    @Path("/components/{componentId}/comments")
     429    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     430        MediaType.APPLICATION_JSON})
     431    public List<Comment> getCommentsFromComponent(
     432            @PathParam("componentId") String componentId)
     433            throws ComponentRegistryException, IOException {
     434        long start = System.currentTimeMillis();
     435        try {
     436            List<Comment> comments = this.getBaseRegistry().getCommentsInComponent(componentId);
     437            LOG.debug(
     438                    "Releasing {} registered comments in Component into the world ({} millisecs)",
     439                    comments.size(), (System.currentTimeMillis() - start));
     440            return comments;
     441        } catch (ItemNotFoundException e) {
     442            response.sendError(Status.NOT_FOUND.getStatusCode());
     443            return new ArrayList<Comment>();
     444        } catch (UserUnauthorizedException e1) {
     445            response.sendError(Status.FORBIDDEN.getStatusCode());
     446            return new ArrayList<Comment>();
     447        } catch (AuthenticationFailException e1) {
     448            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     449            return new ArrayList<Comment>();
     450        }
     451    }
     452
     453    @Override
     454    @GET
     455    @Path("/profiles/{profileId}/comments/{commentId}")
     456    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     457        MediaType.APPLICATION_JSON})
     458    public Comment getSpecifiedCommentFromProfile(
     459            @PathParam("profileId") String profileId,
     460            @PathParam("commentId") String commentId)
     461            throws ComponentRegistryException, IOException {
     462
     463        LOG.debug("Comments of profile with id {} are requested.", commentId);
     464        try {
     465
     466            return this.getBaseRegistry().getSpecifiedCommentInProfile(profileId, commentId);
     467        } catch (ItemNotFoundException e) {
     468            response.sendError(Status.NOT_FOUND.getStatusCode());
     469            return new Comment();
     470        } catch (UserUnauthorizedException e1) {
     471            response.sendError(Status.FORBIDDEN.getStatusCode());
     472            return new Comment();
     473        } catch (AuthenticationFailException e1) {
     474            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     475            return new Comment();
     476        }
     477    }
     478
     479    @Override
     480    @GET
     481    @Path("/components/{componentId}/comments/{commentId}")
     482    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     483        MediaType.APPLICATION_JSON})
     484    public Comment getSpecifiedCommentFromComponent(
     485            @PathParam("componentId") String componentId,
     486            @PathParam("commentId") String commentId)
     487            throws ComponentRegistryException, IOException {
     488        LOG.debug("Comments of component with id {} are requested.", commentId);
     489        try {
     490
     491            return this.getBaseRegistry().getSpecifiedCommentInComponent(componentId, commentId);
     492        } catch (ItemNotFoundException e) {
     493            response.sendError(Status.NOT_FOUND.getStatusCode());
     494            return new Comment();
     495        } catch (UserUnauthorizedException e1) {
     496            response.sendError(Status.FORBIDDEN.getStatusCode());
     497            return new Comment();
     498        } catch (AuthenticationFailException e1) {
     499            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     500            return new Comment();
     501        }
     502    }
     503
     504    /**
     505     *
     506     * Purely helper method for my front-end (FLEX) which only does post/get
     507     * requests. The query param is checked and the "proper" method is called.
     508     *
     509     * @param profileId
     510     * @param method
     511     * @return
     512     */
     513    // TODO: test via POSTMAN
     514    @Override
     515    @POST
     516    @Path("/profiles/{profileId}")
     517    public Response manipulateRegisteredProfile(
     518            @PathParam("profileId") String profileId,
     519            @FormParam("method") String method) {
     520        if ("delete".equalsIgnoreCase(method)) {
     521            return this.deleteRegisteredProfile(profileId);
     522        } else {
     523            return Response.ok().build();
     524        }
     525    }
     526
     527    // TODO: test via POSTMAN
     528    @Override
     529    @POST
     530    @Path("/profiles/{profileId}/comments/{commentId}")
     531    public Response manipulateCommentFromProfile(
     532            @PathParam("profileId") String profileId,
     533            @PathParam("commentId") String commentId,
     534            @FormParam("method") String method) {
     535        if ("delete".equalsIgnoreCase(method)) {
     536            return this.deleteCommentFromProfile(profileId, commentId);
     537        } else {
     538            return Response.ok().build();
     539        }
     540    }
     541
     542    // TODO: test via POSTMAN
     543    @Override
     544    @POST
     545    @Path("/components/{componentId}/comments/{commentId}")
     546    public Response manipulateCommentFromComponent(
     547            @PathParam("componentId") String componentId,
     548            @PathParam("commentId") String commentId,
     549            @FormParam("method") String method) {
     550        if ("delete".equalsIgnoreCase(method)) {
     551            return this.deleteCommentFromComponent(componentId, commentId);
     552        } else {
     553            return Response.ok().build();
     554        }
     555    }
     556
     557    // TODO: test via POSTMAN
     558    @Override
     559    @POST
     560    @Path("/profiles/{profileId}/publish")
     561    @Consumes("multipart/form-data")
     562    public Response publishRegisteredProfile(
     563            @PathParam("profileId") String profileId,
     564            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     565            @FormDataParam(NAME_FORM_FIELD) String name,
     566            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     567            @FormDataParam(GROUP_FORM_FIELD) String group,
     568            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     569
     570        try {
     571            Principal principal = checkAndGetUserPrincipal();
     572            ComponentRegistry registry = this.getBaseRegistry();
     573            ProfileDescription desc = registry.getProfileDescriptionAccessControlled(profileId);
     574            if (desc != null) {
     575                if (desc.isPublic()) {
     576                    return Response.status(Status.CONFLICT).entity("Cannot publish already published profile.")
     577                            .build();
     578                }
     579                desc.setPublic(true);
     580                this.updateDescription(desc, name, description, domainName, group);
     581                return this.register(input, desc, new PublishAction(principal), registry);
     582            } else {
     583                LOG.error("Update of nonexistent profile {} failed.", profileId);
     584                return Response
     585                        .serverError()
     586                        .entity("Invalid id, cannot update nonexistent profile")
     587                        .build();
     588            }
     589
     590        } catch (AuthenticationFailException e) {
     591            return Response.serverError().status(Status.UNAUTHORIZED)
     592                    .build();
     593        } catch (ItemNotFoundException e1) {
     594            return Response.status(Status.NOT_FOUND).entity(e1.getMessage()).build();
     595        } catch (ComponentRegistryException e) {
     596            LOG.warn("Could not retrieve profile {}", profileId);
     597            LOG.debug("Details", e);
     598            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     599                    .build();
     600        } catch (UserUnauthorizedException ex) {
     601            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     602                    .build();
     603        }
     604    }
     605
     606    @Override
     607    @POST
     608    @Path("/profiles/{profileId}/update")
     609    @Consumes("multipart/form-data")
     610    public Response updateRegisteredProfile(
     611            @PathParam("profileId") String profileId,
     612            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     613            @FormDataParam(NAME_FORM_FIELD) String name,
     614            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     615            @FormDataParam(GROUP_FORM_FIELD) String group,
     616            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     617        try {
     618            ComponentRegistry br = this.getBaseRegistry();
     619            ProfileDescription desc = br.getProfileDescriptionAccessControlled(profileId);
     620            if (desc != null) {
     621                if (desc.isPublic()) {
     622                    return Response.status(Status.CONFLICT).entity("Cannot update already published profile.")
     623                            .build();
     624
     625                }
     626                Number groupId;
     627                RegistrySpace space;
     628                List<Number> groupIds = br.getItemGroups(profileId);
     629                if (groupIds == null || groupIds.isEmpty()) {
     630                    groupId = null;
     631                    space = RegistrySpace.PRIVATE;
     632                } else {
     633                    groupId = groupIds.get(0);
     634                    space = RegistrySpace.GROUP;
     635                }
     636
     637                updateDescription(desc, name, description, domainName, group);
     638                ComponentRegistry cr = this.getRegistry(space, groupId);
     639                return register(input, desc, new UpdateAction(), cr);
     640            } else {
     641                LOG.error("Update of nonexistent id (" + profileId
     642                        + ") failed.");
     643                return Response
     644                        .serverError()
     645                        .entity("Invalid id, cannot update nonexistent profile")
     646                        .build();
     647            }
     648        } catch (ComponentRegistryException e) {
     649            LOG.warn("Could not retrieve profile {}", profileId);
     650            LOG.debug("Details", e);
     651            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     652                    .build();
     653
     654        } catch (UserUnauthorizedException ex) {
     655            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     656                    .build();
     657
     658        } catch (ItemNotFoundException ex2) {
     659            return Response.status(Status.NOT_FOUND).entity(ex2.getMessage())
     660                    .build();
     661        } catch (AuthenticationFailException e1) {
     662            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     663                    .build();
     664        }
     665
     666    }
     667
     668    /**
     669     *
     670     * Purely helper method for my front-end (FLEX) which van only do post/get
     671     * requests. The query param is checked and the "proper" method is called.
     672     *
     673     * @param componentId
     674     * @param method
     675     * @return
     676     */
     677    // twan: why do we need it?
     678    // TODO: test via POSTMAN
     679    @Override
     680    @POST
     681    @Path("/components/{componentId}")
     682    public Response manipulateRegisteredComponent(
     683            @PathParam("componentId") String componentId,
     684            @FormParam("method") String method) {
     685        if ("delete".equalsIgnoreCase(method)) {
     686            return this.deleteRegisteredComponent(componentId);
     687        } else {
     688            return Response.ok("Nothing to do, not 'delete' method").build();
     689        }
     690    }
     691
     692    // TODO: test via POSTMAN
     693    @Override
     694    @POST
     695    @Path("/components/{componentId}/publish")
     696    @Consumes("multipart/form-data")
     697    public Response publishRegisteredComponent(
     698            @PathParam("componentId") String componentId,
     699            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     700            @FormDataParam(NAME_FORM_FIELD) String name,
     701            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     702            @FormDataParam(GROUP_FORM_FIELD) String group,
     703            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     704
     705        try {
     706            Principal principal = checkAndGetUserPrincipal();
     707            ComponentRegistry registry = this.getBaseRegistry();
     708            ComponentDescription desc = registry.getComponentDescriptionAccessControlled(componentId);
     709            if (desc != null) {
     710                if (desc.isPublic()) {
     711                    return Response.status(Status.CONFLICT).entity("Cannot publish already published omponent.")
     712                            .build();
     713                }
     714                desc.setPublic(true);
     715                this.updateDescription(desc, name, description, domainName, group);
     716                return this.register(input, desc, new PublishAction(principal), registry);
     717            } else {
     718                LOG.error("Update of nonexistent id (" + componentId
     719                        + ") failed.");
     720                return Response
     721                        .serverError()
     722                        .entity("Invalid id, cannot update nonexistent profile")
     723                        .build();
     724            }
     725        } catch (AuthenticationFailException e) {
     726            LOG.warn("Could not retrieve component {}", componentId);
     727            LOG.debug("Details", e);
     728            return Response.serverError().status(Status.UNAUTHORIZED)
     729                    .build();
     730        } catch (ComponentRegistryException e) {
     731            LOG.warn("Could not retrieve component {}", componentId);
     732            LOG.debug("Details", e);
     733            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     734                    .build();
     735        } catch (ItemNotFoundException e) {
     736            LOG.warn("Could not retrieve component {}", componentId);
     737            LOG.debug("Details", e);
     738            return Response.serverError().status(Status.NOT_FOUND)
     739                    .build();
     740        } catch (UserUnauthorizedException ex) {
     741            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     742                    .build();
     743        }
     744    }
     745
     746    @Override
     747    @POST
     748    @Path("/components/{componentId}/update")
     749    @Consumes("multipart/form-data")
     750    public Response updateRegisteredComponent(
     751            @PathParam("componentId") String componentId,
     752            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     753            @FormDataParam(NAME_FORM_FIELD) String name,
     754            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     755            @FormDataParam(GROUP_FORM_FIELD) String group,
     756            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     757        try {
     758            ComponentRegistry br = this.getBaseRegistry();
     759            ComponentDescription desc =br.getComponentDescriptionAccessControlled(componentId);
     760            if (desc != null) {
     761                if (desc.isPublic()) {
     762                    return Response.status(Status.CONFLICT).entity("Cannot update already published component.")
     763                            .build();
     764                }
     765                Number groupId;
     766                RegistrySpace space;
     767                List<Number> groupIds = br.getItemGroups(componentId);
     768                if (groupIds == null || groupIds.isEmpty()) {
     769                    groupId = null;
     770                    space = RegistrySpace.PRIVATE;
     771                } else {
     772                    groupId = groupIds.get(0);
     773                    space = RegistrySpace.GROUP;
     774                }
     775
     776                this.updateDescription(desc, name, description, domainName, group);
     777                ComponentRegistry cr = this.getRegistry(space, groupId);
     778                return this.register(input, desc, new UpdateAction(), cr);
     779            } else {
     780                LOG.error("Update of nonexistent id (" + componentId
     781                        + ") failed.");
     782                return Response
     783                        .serverError()
     784                        .entity("Invalid id, cannot update nonexistent component")
     785                        .build();
     786            }
     787        } catch (ComponentRegistryException e) {
     788            LOG.warn("Could not retrieve component {}", componentId);
     789            LOG.debug("Details", e);
     790            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     791                    .build();
     792        } catch (UserUnauthorizedException ex) {
     793            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     794                    .build();
     795        } catch (ItemNotFoundException ex2) {
     796            return Response.status(Status.FORBIDDEN).entity(ex2.getMessage())
     797                    .build();
     798        } catch (AuthenticationFailException e1) {
     799            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     800                    .build();
     801        }
     802
     803    }
     804
     805    private void updateDescription(BaseDescription desc, String name,
     806            String description, String domainName, String group) {
     807        desc.setName(name);
     808        desc.setDescription(description);
     809        desc.setDomainName(domainName);
     810        desc.setGroupName(group);
     811        desc.setRegistrationDate(new Date());
     812    }
     813
     814    @Override
     815    @DELETE
     816    @Path("/components/{componentId}")
     817    public Response deleteRegisteredComponent(
     818            @PathParam("componentId") String componentId) {
     819        try {
     820            ComponentRegistry registry = this.getBaseRegistry();
     821            LOG.debug("Component with id {} set for deletion.", componentId);
     822            registry.deleteMDComponent(componentId, false);
     823        } catch (DeleteFailedException e) {
     824            LOG.info("Component with id {} deletion failed. Reason: {}",
     825                    componentId, e.getMessage());
     826            LOG.debug("Deletion failure details:", e);
     827            return Response.status(Status.FORBIDDEN)
     828                    .entity("" + e.getMessage()).build();
     829        } catch (ComponentRegistryException e) {
     830            LOG.warn("Component with id " + componentId + " deletion failed.",
     831                    e);
     832            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     833                    .build();
     834        } catch (ItemNotFoundException e) {
     835            LOG.warn("Component with id " + componentId + " is not found.",
     836                    e);
     837            return Response.serverError().status(Status.NOT_FOUND)
     838                    .build();
     839        } catch (IOException e) {
     840            LOG.error("Component with id " + componentId + " deletion failed.",
     841                    e);
     842            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     843                    .build();
     844        } catch (UserUnauthorizedException e) {
     845            LOG.info("Component with id {} deletion failed: {}", componentId,
     846                    e.getMessage());
     847            LOG.debug("Deletion failure details:", e);
     848            return Response.serverError().status(Status.FORBIDDEN)
     849                    .entity("" + e.getMessage()).build();
     850        } catch (AuthenticationFailException e1) {
     851            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     852                    .build();
     853        }
     854
     855        LOG.info("Component with id: {} deleted.", componentId);
     856        return Response.ok().build();
     857    }
     858
     859    @Override
     860    @DELETE
     861    @Path("/profiles/{profileId}")
     862    public Response deleteRegisteredProfile(
     863            @PathParam("profileId") String profileId) {
     864        try {
     865            LOG.debug("Profile with id: {} set for deletion.", profileId);
     866            this.getBaseRegistry().deleteMDProfile(profileId);
     867        } catch (DeleteFailedException e) {
     868            LOG.info("Profile with id: {} deletion failed: {}", profileId,
     869                    e.getMessage());
     870            LOG.debug("Deletion failure details:", e);
     871            return Response.serverError().status(Status.FORBIDDEN)
     872                    .entity("" + e.getMessage()).build();
     873        } catch (ComponentRegistryException e) {
     874            LOG.warn("Could not retrieve component", e);
     875            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     876                    .build();
     877        } catch (ItemNotFoundException e) {
     878            LOG.warn("Profile with id " + profileId + " is not found.",
     879                    e);
     880            return Response.serverError().status(Status.NOT_FOUND)
     881                    .build();
     882        } catch (IOException e) {
     883            LOG.error("Profile with id: " + profileId + " deletion failed.", e);
     884            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     885                    .build();
     886        } catch (UserUnauthorizedException e) {
     887            LOG.info("Profile with id: {} deletion failed: {}", profileId,
     888                    e.getMessage());
     889            LOG.debug("Deletion failure details:", e);
     890            return Response.serverError().status(Status.FORBIDDEN)
     891                    .entity("" + e.getMessage()).build();
     892        } catch (AuthenticationFailException e1) {
     893            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     894                    .build();
     895        }
     896
     897        LOG.info("Profile with id: {} deleted.", profileId);
     898        return Response.ok().build();
     899    }
     900
     901    @Override
     902    @DELETE
     903    @Path("/profiles/{profileId}/comments/{commentId}")
     904    public Response deleteCommentFromProfile(
     905            @PathParam("profileId") String profileId,
     906            @PathParam("commentId") String commentId) {
     907        try {
     908            final ComponentRegistry registry = this.getBaseRegistry();
     909            try {
     910                final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId);
     911                if (comment != null
     912                        && profileId.equals(comment.getComponentId())) {
     913                    LOG.debug("Comment with id: {} set for deletion.", commentId);
     914                    registry.deleteComment(commentId);
     915                } else {
     916                    throw new ComponentRegistryException(
     917                            "Comment not found for specified profile");
     918                }
     919            } catch (ItemNotFoundException e1) {
     920                LOG.info("Comment with id: {} deletion failed: {}", commentId,
     921                        e1.getMessage());
     922                LOG.debug("Deletion failure details:", e1);
     923                return Response.serverError().status(Status.NOT_FOUND)
     924                        .entity("" + e1.getMessage()).build();
     925            }
     926
     927        } catch (DeleteFailedException e) {
     928            LOG.info("Comment with id: {} deletion failed: {}", commentId,
     929                    e.getMessage());
     930            LOG.debug("Deletion failure details:", e);
     931            return Response.serverError().status(Status.FORBIDDEN)
     932                    .entity("" + e.getMessage()).build();
     933        } catch (ComponentRegistryException e) {
     934            LOG.info("Could not retrieve component", e);
     935            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     936                    .build();
     937        } catch (IOException e) {
     938            LOG.error("Comment with id: " + commentId + " deletion failed.", e);
     939            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     940                    .build();
     941        } catch (UserUnauthorizedException e) {
     942            LOG.info("Comment with id: {} deletion failed: {}", commentId,
     943                    e.getMessage());
     944            LOG.debug("Deletion failure details:", e);
     945            return Response.serverError().status(Status.FORBIDDEN)
     946                    .entity("" + e.getMessage()).build();
     947        } catch (AuthenticationFailException e1) {
     948            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     949                    .build();
     950        }
     951
     952        LOG.info("Comment with id: {} deleted.", commentId);
     953        return Response.ok("Comment with id " + commentId + " deleted.").build();
     954    }
     955
     956    @Override
     957    @DELETE
     958    @Path("/components/{componentId}/comments/{commentId}")
     959    public Response deleteCommentFromComponent(
     960            @PathParam("componentId") String componentId,
     961            @PathParam("commentId") String commentId) {
     962        try {
     963            final ComponentRegistry registry = this.getBaseRegistry();
     964            final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId);
     965            if (comment != null
     966                    && componentId.equals(comment.getComponentId())) {
     967                LOG.debug("Comment with id: {} set for deletion.", commentId);
     968                registry.deleteComment(commentId);
     969            } else {
     970                throw new ComponentRegistryException(
     971                        "Comment not found for specified component");
     972            }
     973        } catch (ItemNotFoundException e) {
     974            LOG.info("Comment with id: {} deletion failed: {}", commentId,
     975                    e.getMessage());
     976            LOG.debug("Deletion failure details:", e);
     977            return Response.serverError().status(Status.NOT_FOUND)
     978                    .entity("" + e.getMessage()).build();
     979        } catch (DeleteFailedException e) {
     980            LOG.info("Comment with id: {} deletion failed: {}", commentId,
     981                    e.getMessage());
     982            LOG.debug("Deletion failure details:", e);
     983            return Response.serverError().status(Status.FORBIDDEN)
     984                    .entity("" + e.getMessage()).build();
     985        } catch (ComponentRegistryException e) {
     986            LOG.info("Could not retrieve component", e);
     987            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     988                    .build();
     989        } catch (IOException e) {
     990            LOG.error("Comment with id: " + commentId + " deletion failed.", e);
     991            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR)
     992                    .build();
     993        } catch (UserUnauthorizedException e) {
     994            LOG.info("Comment with id: {} deletion failed: {}", commentId,
     995                    e.getMessage());
     996            LOG.debug("Deletion failure details:", e);
     997            return Response.serverError().status(Status.FORBIDDEN)
     998                    .entity("" + e.getMessage()).build();
     999        } catch (AuthenticationFailException e1) {
     1000            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     1001                    .build();
     1002        }
     1003
     1004        LOG.info("Comment with id: {} deleted.", commentId);
     1005        return Response.ok("Comment with id " + commentId + " deleted.").build();
     1006    }
     1007
     1008    @Override
     1009    @GET
     1010    @Path("/profiles/{profileId}/{rawType}")
     1011    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
     1012    public Response getRegisteredProfileRawType(
     1013            @PathParam("profileId") final String profileId,
     1014            @PathParam("rawType") String rawType) throws ComponentRegistryException {
     1015
     1016
     1017        LOG.debug("Profile with id {} and rawType {} is requested.", profileId,
     1018                rawType);
     1019        try {
     1020            final ComponentRegistry registry = this.getBaseRegistry();
     1021
     1022            ProfileDescription desc = registry.getProfileDescriptionAccessControlled(profileId);
     1023            if (desc == null) {
     1024                return Response.status(Status.NOT_FOUND).build();
     1025            }
     1026
     1027            StreamingOutput result = null;
     1028            String fileName = desc.getName() + "." + rawType;
     1029            if ("xml".equalsIgnoreCase(rawType)) {
     1030                result = new StreamingOutput() {
     1031                    @Override
     1032                    public void write(OutputStream output) throws IOException,
     1033                            WebApplicationException {
     1034                        try {
     1035                            registry.getMDProfileAsXml(profileId, output);
     1036                        } catch (Exception e) {
     1037                            LOG.warn("Could not retrieve component {}",
     1038                                    profileId);
     1039                            LOG.debug("Details", e);
     1040                            throw new WebApplicationException(e, Response
     1041                                    .serverError()
     1042                                    .status(Status.INTERNAL_SERVER_ERROR)
     1043                                    .build());
     1044                        }
     1045                    }
     1046                };
     1047            } else if ("xsd".equalsIgnoreCase(rawType)) {
     1048                result = new StreamingOutput() {
     1049                    @Override
     1050                    public void write(OutputStream output) throws IOException,
     1051                            WebApplicationException {
     1052                        try {
     1053                            registry.getMDProfileAsXsd(profileId, output);
     1054                        } catch (Exception e) {
     1055                            LOG.warn("Could not retrieve component {}",
     1056                                    profileId);
     1057                            LOG.debug("Details", e);
     1058                            throw new WebApplicationException(e, Response
     1059                                    .serverError()
     1060                                    .status(Status.INTERNAL_SERVER_ERROR)
     1061                                    .build());
     1062                        }
     1063                    }
     1064                };
     1065            } else {
     1066                throw new WebApplicationException(Response
     1067                        .serverError()
     1068                        .entity("unsupported rawType: " + rawType
     1069                        + " (only xml or xsd are supported)").build());
     1070            }
     1071            return createDownloadResponse(result, fileName);
     1072        } catch (UserUnauthorizedException ex) {
     1073            return Response.status(Status.FORBIDDEN).build();
     1074        } catch (ItemNotFoundException e) {
     1075            return Response.serverError().status(Status.NOT_FOUND)
     1076                    .entity("" + e.getMessage()).build();
     1077        } catch (AuthenticationFailException e1) {
     1078            return Response.status(Status.UNAUTHORIZED).entity(e1.getMessage())
     1079                    .build();
     1080        }
     1081
     1082    }
     1083
     1084    private Response createDownloadResponse(StreamingOutput result,
     1085            String fileName) {
     1086        // Making response so it triggers browsers native save as dialog.
     1087        Response response = Response
     1088                .ok()
     1089                .type("application/x-download")
     1090                .header("Content-Disposition",
     1091                "attachment; filename=\"" + fileName + "\"")
     1092                .entity(result).build();
     1093        return response;
     1094
     1095    }
     1096
     1097    @Override
     1098    @POST
     1099    @Path("/profiles")
     1100    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1101        MediaType.APPLICATION_JSON})
     1102    @Consumes("multipart/form-data")
     1103    public Response registerProfile(
     1104            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     1105            @FormDataParam(NAME_FORM_FIELD) String name,
     1106            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     1107            @FormDataParam(GROUP_FORM_FIELD) String group,
     1108            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     1109        try {
     1110            Principal principal = checkAndGetUserPrincipal();
     1111            UserCredentials userCredentials = getUserCredentials(principal);
     1112            ProfileDescription desc = this.createNewProfileDescription();
     1113            desc.setCreatorName(userCredentials.getDisplayName());
     1114            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
     1115            // be created
     1116            // here, now Id
     1117            // is
     1118            // constructed
     1119            // by impl
     1120            desc.setName(name);
     1121            desc.setDescription(description);
     1122            desc.setGroupName(group);
     1123            desc.setDomainName(domainName);
     1124            desc.setPublic(false);
     1125            LOG.debug("Trying to register Profile: {}", desc);
     1126            ComponentRegistry cr = this.getRegistry(RegistrySpace.PRIVATE, null);
     1127            return this.register(input, desc, new NewAction(), cr);
     1128        } catch (AuthenticationFailException e) {
     1129            LOG.debug("Details", e);
     1130            return Response.serverError().status(Status.UNAUTHORIZED)
     1131                    .build();
     1132        } catch (UserUnauthorizedException ex) {
     1133            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     1134                    .build();
     1135        }
     1136    }
     1137
     1138    @Override
     1139    @POST
     1140    @Path("/components")
     1141    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1142        MediaType.APPLICATION_JSON})
     1143    @Consumes("multipart/form-data")
     1144    public Response registerComponent(
     1145            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     1146            @FormDataParam(NAME_FORM_FIELD) String name,
     1147            @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     1148            @FormDataParam(GROUP_FORM_FIELD) String group,
     1149            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     1150        try {
     1151            Principal principal = checkAndGetUserPrincipal();
     1152            UserCredentials userCredentials = getUserCredentials(principal);
     1153            ComponentDescription desc = createNewComponentDescription();
     1154            desc.setCreatorName(userCredentials.getDisplayName());
     1155            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to
     1156            // be created
     1157            // here, now Id
     1158            // is
     1159            // constructed
     1160            // by impl
     1161            desc.setName(name);
     1162            desc.setDescription(description);
     1163            desc.setGroupName(group);
     1164            desc.setDomainName(domainName);
     1165            desc.setPublic(false);
     1166            LOG.debug("Trying to register Component: {}", desc);
     1167            ComponentRegistry cr = this.getRegistry(RegistrySpace.PRIVATE, null);
     1168            return this.register(input, desc, new NewAction(), cr);
     1169        } catch (AuthenticationFailException e) {
     1170            LOG.debug("Details", e);
     1171            return Response.serverError().status(Status.UNAUTHORIZED)
     1172                    .build();
     1173        } catch (UserUnauthorizedException ex) {
     1174            return Response.status(Status.FORBIDDEN).entity(ex.getMessage())
     1175                    .build();
     1176        }
     1177    }
     1178
     1179    @Override
     1180    @POST
     1181    @Path("/components/{componentId}/comments")
     1182    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1183        MediaType.APPLICATION_JSON})
     1184    @Consumes("multipart/form-data")
     1185    public Response registerCommentInComponent(
     1186            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     1187            @PathParam("componentId") String componentId) throws ComponentRegistryException {
     1188        try {
     1189            ComponentRegistry registry = this.getBaseRegistry();
     1190            ComponentDescription description = registry.getComponentDescriptionAccessControlled(componentId);
     1191
     1192            LOG.debug("Trying to register comment to {}", componentId);
     1193
     1194            return this.registerComment(input, description, registry);
     1195        } catch (AuthenticationFailException e) {
     1196            LOG.debug("Details", e);
     1197            return Response.serverError().status(Status.UNAUTHORIZED)
     1198                    .build();
     1199        } catch (UserUnauthorizedException ex) {
     1200            return Response.status(Status.FORBIDDEN)
     1201                    .build();
     1202        } catch (ItemNotFoundException e) {
     1203            return Response.serverError().status(Status.NOT_FOUND)
     1204                    .entity("" + e.getMessage()).build();
     1205        }
     1206    }
     1207
     1208    // TODO test with the POSTMAN
     1209    @Override
     1210    @POST
     1211    @Path("/profiles/{profileId}/comments")
     1212    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1213        MediaType.APPLICATION_JSON})
     1214    @Consumes("multipart/form-data")
     1215    public Response registerCommentInProfile(
     1216            @FormDataParam(DATA_FORM_FIELD) InputStream input,
     1217            @PathParam("profileId") String profileId)
     1218            throws ComponentRegistryException {
     1219        try {
     1220            ComponentRegistry registry = this.getBaseRegistry();
     1221            ProfileDescription description = registry
     1222                    .getProfileDescriptionAccessControlled(profileId);
     1223
     1224            LOG.debug("Trying to register comment to {}", profileId);
     1225
     1226            return this.registerComment(input, description, registry);
     1227        } catch (AuthenticationFailException e) {
     1228            LOG.debug("Details", e);
     1229            return Response.serverError().status(Status.UNAUTHORIZED)
     1230                    .build();
     1231        } catch (UserUnauthorizedException ex) {
     1232            return Response.status(Status.FORBIDDEN)
     1233                    .build();
     1234        } catch (ItemNotFoundException e1) {
     1235            return Response.serverError().status(Status.NOT_FOUND)
     1236                    .entity("" + e1.getMessage()).build();
     1237        }
     1238    }
     1239
     1240    @Override
     1241    @GET
     1242    @Path("/pingSession")
     1243    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1244        MediaType.APPLICATION_JSON})
     1245    public Response pingSession() {
     1246        boolean stillActive = false;
     1247        Principal userPrincipal = security.getUserPrincipal();
     1248        if (LOG.isInfoEnabled()) {
     1249            LOG.debug("ping by <{}>",
     1250                    (userPrincipal == null ? "unauthorized user"
     1251                    : userPrincipal.getName()));
     1252        }
     1253        if (request != null) {
     1254            if (userPrincipal != null
     1255                    && !ComponentRegistryFactory.ANONYMOUS_USER
     1256                    .equals(userPrincipal.getName())) {
     1257                stillActive = !((HttpServletRequest) request).getSession()
     1258                        .isNew();
     1259            }
     1260        }
     1261        return Response
     1262                .ok()
     1263                .entity(String.format("<session stillActive=\"%s\"/>",
     1264                stillActive)).build();
     1265    }
     1266
     1267    private Response register(InputStream input, BaseDescription desc, RegisterAction action, ComponentRegistry registry) throws UserUnauthorizedException {
     1268        try {
     1269
     1270
     1271            DescriptionValidator descriptionValidator = new DescriptionValidator(
     1272                    desc);
     1273            MDValidator validator = new MDValidator(input, desc, registry, marshaller);
     1274            RegisterResponse response = new RegisterResponse();
     1275            //obsolete. Make it setstatus
     1276            response.setIsInUserSpace(!desc.isPublic());
     1277            this.validate(response, descriptionValidator, validator);
     1278            if (response.getErrors().isEmpty()) {
     1279
     1280                CMDComponentSpec spec = validator.getCMDComponentSpec();
     1281
     1282                // removing filename from spec before it gets extended.
     1283                // recursion over all the components
     1284                setFileNamesFromListToNull(Collections.singletonList(spec.getCMDComponent()));
     1285
     1286                try {
     1287                    checkForRecursion(validator, registry, desc);
     1288
     1289                    // Add profile
     1290                    int returnCode = action.execute(desc, spec, response,
     1291                            registry);
     1292                    if (returnCode == 0) {
     1293                        response.setRegistered(true);
     1294                        response.setDescription(desc);
     1295                    } else {
     1296                        response.setRegistered(false);
     1297                        response.addError("Unable to register at this moment. Internal server error.");
     1298                    }
     1299                } catch (ComponentRegistryException ex) {
     1300                    // Recursion detected
     1301                    response.setRegistered(false);
     1302                    response.addError("Error while expanding specification. "
     1303                            + ex.getMessage());
     1304                } catch (ItemNotFoundException ex) {
     1305                    // Recursion detected
     1306                    response.setRegistered(false);
     1307                    response.addError("Error while expanding specification. "
     1308                            + ex.getMessage());
     1309                }
     1310            } else {
     1311                LOG.warn("Registration failed with validation errors: {}",
     1312                        Arrays.toString(response.getErrors().toArray()));
     1313                response.setRegistered(false);
     1314            }
     1315            LOG.info("Registered new {} {}", desc.isProfile() ? "profile"
     1316                    : "component", desc);
     1317            response.setIsProfile(desc.isProfile());
     1318            return Response.ok(response).build();
     1319        } finally {
     1320            try {
     1321                input.close();// either we read the input or there was an
     1322                // exception, we need to close it.
     1323            } catch (IOException e) {
     1324                LOG.error("Error when closing inputstream: ", e);
     1325            }
     1326        }
     1327    }
     1328
     1329    /**
     1330     *
     1331     * @param validator
     1332     * @param registry
     1333     * @param desc
     1334     * @throws ComponentRegistryException if recursion is detected or something
     1335     * goes wrong while trying to detect recursion
     1336     */
     1337    private void checkForRecursion(MDValidator validator,
     1338            ComponentRegistry registry, BaseDescription desc)
     1339            throws ComponentRegistryException {
     1340        try {
     1341            // Expand to check for recursion. Operate on copy so that original
     1342            // does not get expanded.
     1343            final CMDComponentSpec specCopy = validator
     1344                    .getCopyOfCMDComponentSpec();
     1345            // In case of recursion, the following will throw a
     1346            // ComponentRegistryException
     1347            registry.getExpander().expandNestedComponent(
     1348                    Lists.newArrayList(specCopy.getCMDComponent()), desc.getId());
     1349        } catch (JAXBException ex) {
     1350            throw new ComponentRegistryException(
     1351                    "Unmarshalling failed while preparing recursion detection",
     1352                    ex);
     1353        }
     1354    }
     1355
     1356    private Response registerComment(InputStream input, BaseDescription description, ComponentRegistry registry) throws UserUnauthorizedException, AuthenticationFailException {
     1357        try {
     1358            CommentValidator validator = new CommentValidator(input, description, marshaller);
     1359            CommentResponse responseLocal = new CommentResponse();
     1360
     1361            responseLocal.setIsInUserSpace(!description.isPublic());
     1362            this.validateComment(responseLocal, validator);
     1363            if (responseLocal.getErrors().isEmpty()) {
     1364                Comment com = validator.getCommentSpec();
     1365                // int returnCode = action.executeComment(com, response,
     1366                // registry, principal.getName());
     1367
     1368                // If user name is left empty, fill it using the user's display
     1369                // name
     1370
     1371                Principal principal = this.checkAndGetUserPrincipal();
     1372                UserCredentials userCredentials = this.getUserCredentials(principal);
     1373                if (null == com.getUserName() || "".equals(com.getUserName())) {
     1374                    if (userCredentials != null) {
     1375                        com.setUserName(userCredentials.getDisplayName());
     1376                    } else {
     1377                        com.setUserName(principal.getName());
     1378                    }
     1379                }
     1380                try {
     1381                    int returnCode = registry.registerComment(com,
     1382                            principal.getName());
     1383                    if (returnCode == 0) {
     1384                        responseLocal.setRegistered(true);
     1385                        responseLocal.setComment(com);
     1386                    } else {
     1387                        responseLocal.setRegistered(false);
     1388                        responseLocal.addError("Unable to post at this moment. Internal server error.");
     1389                    }
     1390                    if (com.getComponentId() != null) {
     1391                        LOG.info("Posted new comment on component {}",
     1392                                com.getComponentId());
     1393                    } else {
     1394                        LOG.info("Posted new comment on profile {}",
     1395                                com.getComponentId());
     1396                    }
     1397                } catch (ItemNotFoundException e) {
     1398                    return Response.serverError().status(Status.NOT_FOUND)
     1399                            .entity("" + e.getMessage()).build();
     1400                }
     1401            } else {
     1402                LOG.warn(
     1403                        "Posting of comment failed with validation errors: {}",
     1404                        Arrays.toString(responseLocal.getErrors().toArray()));
     1405                responseLocal.setRegistered(false);
     1406            }
     1407            return Response.ok(responseLocal).build();
     1408        } catch (ComponentRegistryException ex) {
     1409            LOG.error("Error while inserting comment: ", ex);
     1410            return Response.serverError().entity(ex.getMessage()).build();
     1411        } finally {
     1412            try {
     1413                input.close();// either we read the input or there was an
     1414                // exception, we need to close it.
     1415            } catch (IOException e) {
     1416                LOG.error("Error when closing inputstream: ", e);
     1417                return Response.serverError().build();
     1418            }
     1419        }
     1420    }
     1421
     1422    private ComponentDescription createNewComponentDescription() {
     1423        ComponentDescription desc = ComponentDescription.createNewDescription();
     1424        desc.setHref(createXlink(desc.getId()));
     1425        return desc;
     1426    }
     1427
     1428    private ProfileDescription createNewProfileDescription() {
     1429        ProfileDescription desc = ProfileDescription.createNewDescription();
     1430        desc.setHref(createXlink(desc.getId()));
     1431        return desc;
     1432    }
     1433
     1434    private String createXlink(String id) {
     1435        URI uri = uriInfo.getRequestUriBuilder().path(id).build();
     1436        return uri.toString();
     1437    }
     1438
     1439    /**
     1440     *
     1441     * @return The application's base URI as configured in the
     1442     * {@link #APPLICATION_BASE_URL_PARAM} context parameter. If correctly
     1443     * configured, it should look something like
     1444     * "http://catalog.clarin.eu/ds/ComponentRegistry". <em>Be aware that this
     1445     * can also be null if configured incorrectly!</em>
     1446     *
     1447     * @see #APPLICATION_BASE_URL_PARAM
     1448     */
     1449    private String getApplicationBaseURI() {
     1450        return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
     1451    }
     1452
     1453    private void validate(RegisterResponse response, Validator... validators) throws UserUnauthorizedException {
     1454        for (Validator validator : validators) {
     1455            if (!validator.validate()) {
     1456                for (String error : validator.getErrorMessages()) {
     1457                    response.addError(error);
     1458                }
     1459            }
     1460        }
     1461    }
     1462
     1463    private void validateComment(CommentResponse response,
     1464            Validator... validators) throws UserUnauthorizedException {
     1465        for (Validator validator : validators) {
     1466            if (!validator.validate()) {
     1467                for (String error : validator.getErrorMessages()) {
     1468                    response.addError(error);
     1469                }
     1470            }
     1471        }
     1472    }
     1473
     1474    /**
     1475     * @param componentRegistryFactory the componentRegistryFactory to set
     1476     */
     1477    @Override
     1478    public void setComponentRegistryFactory(
     1479            ComponentRegistryFactory componentRegistryFactory) {
     1480        this.componentRegistryFactory = componentRegistryFactory;
     1481    }
     1482
     1483    /**
     1484     *
     1485     * @param listofcomponents a list of components whose file-names and whose
     1486     * childrens' filenames are to be set to null
     1487     */
     1488    @Override
     1489    public void setFileNamesFromListToNull(
     1490            List<CMDComponentType> listofcomponents) {
     1491
     1492        for (CMDComponentType currentcomponent : listofcomponents) {
     1493            setFileNamesToNullCurrent(currentcomponent);
     1494        }
     1495
     1496    }
     1497
     1498    /**
     1499     *
     1500     * @param currentcomponent a component whose file-name and whose children
     1501     * filenames are to be set to null
     1502     */
     1503    protected void setFileNamesToNullCurrent(CMDComponentType currentcomponent) {
     1504        currentcomponent.setFilename(null);
     1505        setFileNamesFromListToNull(currentcomponent.getCMDComponent());
     1506    }
     1507
     1508    /**
     1509     *
     1510     * @param isPublished if "true" then profiles and components from the user's
     1511     * workspace, otherwise -- public
     1512     * @param limit the number of items to be displayed
     1513     * @return rss for the components in the database to which we are currently
     1514     * connected
     1515     * @throws ComponentRegistryException
     1516     * @throws ParseException
     1517     */
     1518    @Override
     1519    @GET
     1520    @Path("/components/rss")
     1521    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1522        MediaType.APPLICATION_JSON})
     1523    public Rss getRssComponent(@QueryParam(GROUPID_PARAM) String groupId,
     1524            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
     1525            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
     1526            throws ComponentRegistryException, ParseException, IOException {
     1527        List<ComponentDescription> components = null;
     1528        try {
     1529            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
     1530            components = cr.getComponentDescriptions();
     1531        } catch (AuthenticationFailException e) {
     1532            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     1533            return new Rss();
     1534        } catch (UserUnauthorizedException e) {
     1535            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
     1536            return new Rss();
     1537        }
     1538        // obsolete, add group Id
     1539        final RssCreatorDescriptions instance = new RssCreatorDescriptions(!registrySpace.equalsIgnoreCase("published"), getApplicationBaseURI(), "components",
     1540                Integer.parseInt(limit), components,
     1541                ComponentUtils.COMPARE_ON_DATE);
     1542        final Rss rss = instance.getRss();
     1543        LOG.debug("Releasing RSS of {} most recently registered components",
     1544                limit);
     1545        return rss;
     1546    }
     1547
     1548    /**
     1549     *
     1550     * @param isPublished if "true" then profiles and components from the user's
     1551     * workspace, otherwise -- public
     1552     * @param limit the number of items to be displayed
     1553     * @return rss for the profiles in the database to which we are currently
     1554     * connected
     1555     * @throws ComponentRegistryException
     1556     * @throws ParseException
     1557     */
     1558    @Override
     1559    @GET
     1560    @Path("/profiles/rss")
     1561    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1562        MediaType.APPLICATION_JSON})
     1563    public Rss getRssProfile(@QueryParam(GROUPID_PARAM) String groupId,
     1564            @QueryParam(REGISTRY_SPACE_PARAM) @DefaultValue("published") String registrySpace,
     1565            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
     1566            throws ComponentRegistryException, ParseException, IOException {
     1567        List<ProfileDescription> profiles = null;
     1568        try {
     1569            ComponentRegistry cr = this.initialiseRegistry(registrySpace, groupId);
     1570            profiles = cr.getProfileDescriptions();
     1571        } catch (AuthenticationFailException e) {
     1572            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     1573            return new Rss();
     1574        } catch (UserUnauthorizedException e) {
     1575            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
     1576            return new Rss();
     1577        }
     1578        final RssCreatorDescriptions instance = new RssCreatorDescriptions(
     1579                !registrySpace.equalsIgnoreCase("published"), getApplicationBaseURI(), "profiles",
     1580                Integer.parseInt(limit), profiles,
     1581                ComponentUtils.COMPARE_ON_DATE);
     1582        final Rss rss = instance.getRss();
     1583        LOG.debug("Releasing RSS of {} most recently registered profiles",
     1584                limit);
     1585        return rss;
     1586    }
     1587
     1588    /**
     1589     *
     1590     * @param profileId the Id of a profile whose comments are to be rss-ed
     1591     * @param isPublished if "true" then profiles and components from the user's
     1592     * workspace, otherwise -- public
     1593     * @param limit the number of items to be displayed
     1594     * @return rss of the comments for a chosen profile
     1595     * @throws ComponentRegistryException
     1596     * @throws IOException
     1597     * @throws JAXBException
     1598     * @throws ParseException
     1599     */
     1600    @Override
     1601    @GET
     1602    @Path("/profiles/{profileId}/comments/rss")
     1603    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1604        MediaType.APPLICATION_JSON})
     1605    public Rss getRssOfCommentsFromProfile(
     1606            @PathParam("profileId") String profileId,
     1607            @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit)
     1608            throws ComponentRegistryException, IOException, JAXBException,
     1609            ParseException {
     1610        try {
     1611
     1612            ComponentRegistry cr = this.getBaseRegistry();
     1613
     1614            final List<Comment> comments = cr.getCommentsInProfile(profileId);
     1615            final ProfileDescription pd = cr.getProfileDescriptionAccessControlled(profileId);
     1616            final String profileName = pd.getName();
     1617            boolean profileIsPrivate = !pd.isPublic();
     1618            // obsolete, status must be involved, not boolean profileIsPrivate
     1619            final RssCreatorComments instance = new RssCreatorComments(profileIsPrivate,
     1620                    getApplicationBaseURI(), Integer.parseInt(limit), profileId,
     1621                    profileName, "profile", comments, Comment.COMPARE_ON_DATE);
     1622            final Rss rss = instance.getRss();
     1623            LOG.debug("Releasing RSS of {} most recent post on profile {}", limit,
     1624                    profileId);
     1625            return rss;
     1626        } catch (UserUnauthorizedException ex) {
     1627            response.sendError(Status.FORBIDDEN.getStatusCode());
     1628            return new Rss();
     1629        } catch (ItemNotFoundException e) {
     1630            response.sendError(Status.NOT_FOUND.getStatusCode());
     1631            return new Rss();
     1632        } catch (AuthenticationFailException e) {
     1633            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     1634            return new Rss();
     1635        }
     1636    }
     1637
     1638    /**
     1639     *
     1640     * @param componentId the Id of a component whose comments are to be rss-ed
     1641     * @param isPublished if "true" then profiles and components from the user's
     1642     * workspace, otherwise -- public
     1643     * @param limit the number of items to be displayed
     1644     * @return rss of the comments for a chosen component
     1645     * @throws ComponentRegistryException
     1646     * @throws IOException
     1647     * @throws JAXBException
     1648     * @throws ParseException
     1649     */
     1650    @Override
     1651    @GET
     1652    @Path("/components/{componentId}/comments/rss")
     1653    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1654        MediaType.APPLICATION_JSON})
     1655    public Rss getRssOfCommentsFromComponent(
     1656            @PathParam("componentId") String componentId,
     1657            @QueryParam(NUMBER_OF_RSSITEMS)
     1658            @DefaultValue("20") String limit)
     1659            throws ComponentRegistryException, IOException, JAXBException,
     1660            ParseException {
     1661        try {
     1662            ComponentRegistry cr = this.getBaseRegistry();
     1663            final List<Comment> comments = cr.getCommentsInComponent(componentId);
     1664            final ComponentDescription cd = cr.getComponentDescriptionAccessControlled(componentId);
     1665            final String componentName = cd.getName();
     1666            final boolean isPrivate = !cd.isPublic();
     1667            //oboslete. status must be involved, not boolean isPrivate
     1668            final RssCreatorComments instance = new RssCreatorComments(isPrivate,
     1669                    getApplicationBaseURI(), Integer.parseInt(limit), componentId,
     1670                    componentName, "component", comments, Comment.COMPARE_ON_DATE);
     1671            final Rss rss = instance.getRss();
     1672            LOG.debug("Releasing RSS of {} most recent post on component {}",
     1673                    limit, componentId);
     1674            return rss;
     1675        } catch (UserUnauthorizedException e) {
     1676            response.sendError(Status.FORBIDDEN.getStatusCode());
     1677            return new Rss();
     1678        } catch (ItemNotFoundException e) {
     1679            response.sendError(Status.NOT_FOUND.getStatusCode());
     1680            return new Rss();
     1681        } catch (AuthenticationFailException e1) {
     1682            response.sendError(Status.UNAUTHORIZED.getStatusCode());
     1683            return new Rss();
     1684        }
     1685
     1686    }
     1687
     1688    @Override
     1689    @GET
     1690    @Path("/AllowedTypes")
     1691    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1692        MediaType.APPLICATION_JSON})
     1693    public AllowedAttributetypesXML getAllowedAttributeTypes()
     1694            throws ComponentRegistryException, IOException, JAXBException,
     1695            ParseException {
     1696        return (new AllowedAttributetypesXML());
     1697    }
     1698
     1699    @Override
     1700    @GET
     1701    @Path("/groups/usermembership")
     1702    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1703        MediaType.APPLICATION_JSON})
     1704    public List<Group> getGroupsTheCurrentUserIsAMemberOf() {
     1705        Principal principal = security.getUserPrincipal();
     1706        if (principal == null) {
     1707            return new ArrayList<Group>();
     1708        }
     1709        List<Group> groups = groupService.getGroupsOfWhichUserIsAMember(principal.getName());
     1710        return groups;
     1711    }
     1712
     1713    @Override
     1714    @GET
     1715    @Path("/items/{itemId}/groups")
     1716    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1717        MediaType.APPLICATION_JSON})
     1718    public List<Group> getGroupsTheItemIsAMemberOf(@PathParam("itemId") String itemId) {
     1719        return groupService.getGroupsTheItemIsAMemberOf(itemId);
     1720    }
     1721
     1722    @Override
     1723    @POST
     1724    @Path("/items/{itemId}/transferownership")
     1725    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1726        MediaType.APPLICATION_JSON})
     1727    public String transferItemOwnershipToGroup(@PathParam("itemId") String itemId,
     1728            @QueryParam("groupId") long groupId) throws IOException {
     1729        Principal principal = security.getUserPrincipal();
     1730        try {
     1731            groupService.transferItemOwnershipFromUserToGroupId(principal.getName(), groupId, itemId);
     1732            return "No exceptions happen, the item shoul be transferred";
     1733        } catch (UserUnauthorizedException e) {
     1734            response.sendError(Status.FORBIDDEN.getStatusCode(), e.toString());
     1735            return e.toString();
     1736        }
     1737    }
     1738
     1739    @Override
     1740    @GET
     1741    @Path("/items/{itemId}")
     1742    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML,
     1743        MediaType.APPLICATION_JSON})
     1744    public BaseDescription getBaseDescription(@PathParam("itemId") String itemId) throws ComponentRegistryException, IOException {
     1745        LOG.debug("Item with id: {} is requested.", itemId);
     1746        try {
     1747            ComponentRegistry cr = this.getBaseRegistry();
     1748            try {
     1749                BaseDescription description = cr.getComponentDescriptionAccessControlled(itemId);
     1750                return description;
     1751            } catch (UserUnauthorizedException ex1) {
     1752                try {
     1753                    BaseDescription description = cr.getProfileDescriptionAccessControlled(itemId);
     1754                    return description;
     1755                } catch (UserUnauthorizedException ex2) {
     1756                    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.");
     1757                    return new BaseDescription();
     1758                }
     1759            }
     1760        } catch (ItemNotFoundException e) {
     1761            response.sendError(Status.NOT_FOUND.getStatusCode());
     1762            return new BaseDescription();
     1763        } catch (AuthenticationFailException e) {
     1764            response.sendError(Status.UNAUTHORIZED.getStatusCode(), e.toString());
     1765            return new BaseDescription();
     1766        }
     1767    }
    16051768}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/IComponentRegistryRestService.java

    r4135 r5549  
    11package clarin.cmdi.componentregistry.rest;
    22
     3import clarin.cmdi.componentregistry.UserUnauthorizedException;
    34import java.io.IOException;
    45import java.io.InputStream;
     
    1314
    1415import clarin.cmdi.componentregistry.AllowedAttributetypesXML;
    15 import clarin.cmdi.componentregistry.ComponentRegistry;
    1616import clarin.cmdi.componentregistry.ComponentRegistryException;
    1717import clarin.cmdi.componentregistry.ComponentRegistryFactory;
     
    4444        public static final String GROUP_FORM_FIELD = "group";
    4545        public static final String DOMAIN_FORM_FIELD = "domainName";
    46         public static final String USERSPACE_PARAM = "userspace";
     46        public static final String REGISTRY_SPACE_PARAM = "registrySpace";
    4747        public static final String GROUPID_PARAM = "groupid";
    4848        public static final String METADATA_EDITOR_PARAM = "mdEditor";
    4949        public static final String NUMBER_OF_RSSITEMS = "limit";
    5050
    51         List<ComponentDescription> getRegisteredComponents(boolean userspace, String groupId)
    52                         throws ComponentRegistryException;
    53 
    54         List<ProfileDescription> getRegisteredProfiles(boolean userspace,
    55                         boolean metadataEditor, String groupId) throws ComponentRegistryException;
    56 
    57         Response getRegisteredComponent(String componentId, boolean userspace)
    58                         throws ComponentRegistryException;
    59 
    60         Response getRegisteredComponentRawType(String componentId, String rawType);
    61 
    62         ComponentRegistry findRegistry(String id,
    63                         RegistryClosure<? extends BaseDescription> clos)
    64                         throws ComponentRegistryException;
    65 
    66         Response getRegisteredProfile(String profileId, boolean userspace)
    67                         throws ComponentRegistryException;
    68 
    69         List<BaseDescription> getComponentUsage(String componentId,
    70                         boolean userspace) throws ComponentRegistryException;
    71 
    72         List<Comment> getCommentsFromProfile(String profileId, boolean userspace)
    73                         throws ComponentRegistryException;
    74 
    75         List<Comment> getCommentsFromComponent(String componentId, boolean userspace)
    76                         throws ComponentRegistryException;
    77 
    78         Comment getSpecifiedCommentFromProfile(String profileId, String commentId,
    79                         boolean userspace) throws ComponentRegistryException;
    80 
    81         Comment getSpecifiedCommentFromComponent(String componentId,
    82                         String commentId, boolean userspace)
    83                         throws ComponentRegistryException;
     51        List<ComponentDescription> getRegisteredComponents(String registrySpace, String groupId)
     52                        throws ComponentRegistryException, IOException, UserUnauthorizedException;
     53
     54        List<ProfileDescription> getRegisteredProfiles(String registrySpace, boolean metadataEditor, String groupId) throws ComponentRegistryException, IOException, UserUnauthorizedException;
     55
     56        Response getRegisteredComponent(String componentId) throws IOException;
     57
     58        Response getRegisteredProfile(String profileId) throws IOException;
     59       
     60        Response getRegisteredComponentRawType(String componentId, String rawType) throws ComponentRegistryException;
     61
     62       
     63//      ComponentRegistry findRegistry(String id,
     64//                      RegistryClosure<? extends BaseDescription> clos)
     65//                      throws ComponentRegistryException;
     66//
     67//     
     68
     69        List<BaseDescription> getComponentUsage(String componentId) throws ComponentRegistryException, IOException;
     70
     71        List<Comment> getCommentsFromProfile(String profileId) throws ComponentRegistryException, IOException;
     72
     73        List<Comment> getCommentsFromComponent(String componentId) throws ComponentRegistryException, IOException;
     74
     75        Comment getSpecifiedCommentFromProfile(String profileId, String commentId) throws ComponentRegistryException, IOException ;
     76
     77        Comment getSpecifiedCommentFromComponent(String componentId, String commentId) throws ComponentRegistryException, IOException ;
    8478
    8579        /**
     
    9286         * @return
    9387         */
    94         Response manipulateRegisteredProfile(String profileId, String method,
    95                         boolean userspace);
     88        Response manipulateRegisteredProfile(String profileId, String method);
    9689
    9790        Response manipulateCommentFromProfile(String profileId, String commentId,
    98                         String method, boolean userspace);
     91                        String method);
    9992
    10093        Response manipulateCommentFromComponent(String componentId,
    101                         String commentId, String method, boolean userspace);
     94                        String commentId, String method);
    10295
    10396        Response publishRegisteredProfile(String profileId, InputStream input,
    10497                        String name, String description, String group, String domainName);
    10598
    106         Response updateRegisteredProfile(String profileId, boolean userspace,
    107                         InputStream input, String name, String description, String group,
     99        Response updateRegisteredProfile(String profileId,
     100                        InputStream input, String name, String description, String groupId,
    108101                        String domainName);
    109102
     
    117110         * @return
    118111         */
    119         Response manipulateRegisteredComponent(String componentId, String method,
    120                         boolean userspace);
     112        Response manipulateRegisteredComponent(String componentId, String method);
    121113
    122114        Response publishRegisteredComponent(String componentId, InputStream input,
    123                         String name, String description, String group, String domainName);
    124 
    125         Response updateRegisteredComponent(String componentId, boolean userspace,
    126                         InputStream input, String name, String description, String group,
     115                        String name, String description, String groupId, String domainName);
     116
     117        Response updateRegisteredComponent(String componentId,
     118                        InputStream input, String name, String description, String groupId,
    127119                        String domainName);
    128120
    129         Response deleteRegisteredComponent(String componentId, boolean userspace);
    130 
    131         Response deleteRegisteredProfile(String profileId, boolean userspace);
    132 
    133         Response deleteCommentFromProfile(String profileId, String commentId,
    134                         boolean userspace);
    135 
    136         Response deleteCommentFromComponent(String componentId, String commentId,
    137                         boolean userspace);
    138 
    139         Response getRegisteredProfileRawType(String profileId, String rawType);
     121        Response deleteRegisteredComponent(String componentId);
     122
     123        Response deleteRegisteredProfile(String profileId);
     124
     125        Response deleteCommentFromProfile(String profileId, String commentId);
     126
     127        Response deleteCommentFromComponent(String componentId, String commentId);
     128
     129        Response getRegisteredProfileRawType(String profileId, String rawType) throws ComponentRegistryException;
    140130
    141131        Response registerProfile(InputStream input, String name,
    142                         String description, String group, String domainName,
    143                         boolean userspace);
     132                        String description, String groupId, String domainName);
    144133
    145134        Response registerComponent(InputStream input, String name,
    146                         String description, String group, String domainName,
    147                         boolean userspace);
    148 
    149         Response registerCommentInComponent(InputStream input, String componentId,
    150                         boolean userspace) throws ComponentRegistryException;
    151 
    152         Response registerCommentInProfile(InputStream input, String profileId,
    153                         boolean userspace) throws ComponentRegistryException;
     135                        String description, String groupId, String domainName);
     136
     137        Response registerCommentInComponent(InputStream input, String componentId) throws ComponentRegistryException;
     138
     139        Response registerCommentInProfile(InputStream input, String profileId) throws ComponentRegistryException;
    154140
    155141        Response pingSession();
     
    158144         * @param componentRegistryFactory the componentRegistryFactory to set
    159145         */
    160         void setComponentRegistryFactory(
    161                         ComponentRegistryFactory componentRegistryFactory);
     146        void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory);
    162147
    163148        /**
     
    169154         * @throws ParseException
    170155         */
    171         Rss getRssComponent(boolean userspace, String limit)
    172                         throws ComponentRegistryException, ParseException;
     156        Rss getRssComponent(String groupId, String registrySpace, String limit)
     157                        throws ComponentRegistryException, ParseException, IOException;
    173158
    174159        /**
     
    180165         * @throws ParseException
    181166         */
    182         Rss getRssProfile(boolean userspace, String limit)
    183                         throws ComponentRegistryException, ParseException;
     167        Rss getRssProfile(String groupId, String registrySpace, String limit)
     168                        throws ComponentRegistryException, ParseException, IOException;
    184169
    185170        /**
     
    194179         * @throws ParseException
    195180         */
    196         Rss getRssOfCommentsFromProfile(String profileId, boolean userspace,
    197                         String limit) throws ComponentRegistryException, IOException,
    198                         JAXBException, ParseException;
     181        Rss getRssOfCommentsFromProfile(String profileId, String limit) throws ComponentRegistryException,
     182                        JAXBException, ParseException, IOException;
    199183
    200184        /**
     
    209193         * @throws ParseException
    210194         */
    211         Rss getRssOfCommentsFromComponent(String componentId, boolean userspace,
     195        Rss getRssOfCommentsFromComponent(String componentId,
    212196                        String limit) throws ComponentRegistryException, IOException,
    213197                        JAXBException, ParseException;
     
    237221         * @param groupId
    238222         */
    239         void transferItemOwnershipToGroup(String itemId, long groupId);
     223        String transferItemOwnershipToGroup(String itemId, long groupId) throws IOException;
    240224       
    241225        /**
     
    244228         * @return
    245229         */
    246         BaseDescription getComponentDescription(String componentId) throws ComponentRegistryException;
     230        BaseDescription getBaseDescription(String componentId) throws ComponentRegistryException, IOException;
    247231
    248232}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/MDValidator.java

    r4550 r5549  
    55import clarin.cmdi.componentregistry.ComponentRegistryResourceResolver;
    66import clarin.cmdi.componentregistry.Configuration;
     7import clarin.cmdi.componentregistry.ItemNotFoundException;
    78import clarin.cmdi.componentregistry.MDMarshaller;
     9import clarin.cmdi.componentregistry.NullIdException;
     10import clarin.cmdi.componentregistry.RegistrySpace;
     11import clarin.cmdi.componentregistry.UserUnauthorizedException;
    812import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    913import clarin.cmdi.componentregistry.components.CMDComponentType;
    1014import clarin.cmdi.componentregistry.model.BaseDescription;
    11 import clarin.cmdi.componentregistry.model.ComponentDescription;
    1215import clarin.cmdi.schema.cmd.Validator.Message;
    1316import clarin.cmdi.schema.cmd.ValidatorException;
     
    2932
    3033public class MDValidator implements Validator {
    31    
     34
    3235    private final static Logger LOG = LoggerFactory.getLogger(MDValidator.class);
    3336    static final String MISMATCH_ERROR = "Cannot register component as a profile or vica versa.";
     
    3639    static final String SCHEMA_ERROR = "Error in reading general component schema: ";
    3740    static final String IO_ERROR = "Error while reading specification or general component schema: ";
    38     static final String COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR = "referenced component cannot be found in the published components: ";
     41    static final String COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR = "referenced component cannot be found in the appropriate registry components: ";
    3942    static final String COMPONENT_REGISTRY_EXCEPTION_ERROR = "An exception occurred while accessing the component registry: ";
    4043    static final String ILLEGAL_ATTRIBUTE_NAME_ERROR = "Illegal attribute name: ";
     
    4750    private final BaseDescription description;
    4851    private final ComponentRegistry registry;
    49     private final ComponentRegistry userRegistry;
    50     private final ComponentRegistry publicRegistry;
    5152    private final MDMarshaller marshaller;
    5253
     
    6162     * @param registry
    6263     */
    63     public MDValidator(InputStream input, BaseDescription description, ComponentRegistry registry, ComponentRegistry userRegistry, ComponentRegistry publicRegistry, MDMarshaller marshaller) {
     64    public MDValidator(InputStream input, BaseDescription description, ComponentRegistry registry, MDMarshaller marshaller) {
    6465        this.input = input;
    6566        this.description = description;
    6667        this.registry = registry;
    67         this.userRegistry = userRegistry;
    68         this.publicRegistry = publicRegistry;
    6968        this.marshaller = marshaller;
    7069    }
    71    
     70
    7271    @Override
    7372    public List<String> getErrorMessages() {
    7473        return errorMessages;
    7574    }
    76    
     75
    7776    @Override
    78     public boolean validate() {
     77    public boolean validate() throws UserUnauthorizedException {
    7978        try {
    8079            clarin.cmdi.schema.cmd.Validator validator = new clarin.cmdi.schema.cmd.Validator(new URL(Configuration.getInstance().getGeneralComponentSchema()));
     
    116115            } catch (ComponentRegistryException e) {
    117116                errorMessages.add(COMPONENT_REGISTRY_EXCEPTION_ERROR + e);
     117            } catch (ItemNotFoundException e2) {
     118                errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + e2);
     119            } catch (NullIdException e3) {
     120                errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + e3);
    118121            }
    119122        }
    120123        return errorMessages.isEmpty();
    121124    }
    122    
     125
    123126    private byte[] getBytesFromInputStream() throws IOException {
    124127        int len;
    125128        byte[] b = new byte[4096];
    126129        final ByteArrayOutputStream bOS = new ByteArrayOutputStream();
    127        
     130
    128131        while ((len = input.read(b)) > 0) {
    129132            bOS.write(b, 0, len);
    130133        }
    131        
     134
    132135        return bOS.toByteArray();
    133136    }
    134137
    135     private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException {
     138    private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
    136139        validateComponents(Collections.singletonList(componentSpec.getCMDComponent()));
    137140    }
    138    
    139     private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException {
     141
     142    private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
    140143        for (CMDComponentType cmdComponentType : cmdComponents) {
    141             validateDescribedComponents(cmdComponentType);
    142             validateComponents(cmdComponentType.getCMDComponent());//Recursion
    143         }
    144     }
    145    
    146     private void validateDescribedComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException {
    147         checkPublicComponents(cmdComponentType);
    148     }
    149    
    150     private void checkPublicComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException {
     144            this.validateDescribedComponents(cmdComponentType);
     145            this.validateComponents(cmdComponentType.getCMDComponent());//Recursion
     146        }
     147    }
     148
     149    private void validateDescribedComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
     150        this.checkComponentInSpace(cmdComponentType);
     151    }
     152
     153    private void checkComponentInSpace(CMDComponentType cmdComponentType) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException {
    151154        if (isDefinedInSeparateFile(cmdComponentType)) {
    152155            String id = cmdComponentType.getComponentId();
    153             CMDComponentSpec registeredComponent;
    154             if (registry.isPublic()) { // public registry requires only published components
    155                 registeredComponent = registry.getMDComponent(id);
    156                 if (registeredComponent == null) {
    157                     String error = cmdComponentType.getComponentId();
    158                     if (userRegistry != null) {
    159                         ComponentDescription desc = userRegistry.getComponentDescription(id);
    160                         if (desc != null) {
    161                             error = desc.getName() + " (" + cmdComponentType.getComponentId() + ")";
     156            if (id == null) {
     157                String name = (cmdComponentType.getName() == null) ? "null" : cmdComponentType.getName();
     158                throw new NullIdException("The component with the name " + name + " has a null id. :(");
     159            }
     160            CMDComponentSpec registeredComponent = registry.getMDComponent(id);
     161            if (registeredComponent != null) {
     162                String componentId = cmdComponentType.getComponentId();
     163                Boolean isPublicB = registry.isItemPublic(id);// throws ItemNotFoundException
     164                boolean isPublic = isPublicB.booleanValue();
     165                if (isPublic) {  // if  a component is public, it is available for any registry
     166                    return;
     167                };
     168                // a private component for a private registry is available only if its owner is the owner of the resgitry
     169                if (registry.getRegistrySpace().equals(RegistrySpace.PRIVATE)) {
     170                    Number registryOwnerId = registry.getRegistryOwner().getId();
     171                    Number componentOwnerId = registry.getBaseDescriptionOwnerId(cmdComponentType.getComponentId());
     172                    if (registryOwnerId.equals(componentOwnerId)) {
     173                        return;
     174                    };
     175                    errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (private registry)");
     176                    return;
     177
     178                } else { // a private component in a group registry is availabe only if it belongs to the group
     179                    if (registry.getRegistrySpace().equals(RegistrySpace.GROUP)) {
     180                        if (registry.getGroupId() == null) {
     181                            errorMessages.add(COMPONENT_REGISTRY_EXCEPTION_ERROR + "in the group space, the group id is null");
     182                            return;
    162183                        }
     184                        List<Number> componentGroupIds = registry.getItemGroups(cmdComponentType.getComponentId());
     185                        if (componentGroupIds.contains(registry.getGroupId())) {
     186                            return;
     187                        }
     188                        errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (group registry) " + registry.getGroupId());
     189                        return;
    163190                    }
    164                     errorMessages.add(COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR + error);
     191                    errorMessages.add(COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR + componentId + " (private component in public registry).");
     192                    return;
    165193                }
    166             } else { //User registry, can link to components from public registry and the user's registry
    167                 registeredComponent = registry.getMDComponent(id);
    168                 if (registeredComponent == null) {
    169                     registeredComponent = publicRegistry.getMDComponent(id);
    170                     if (registeredComponent == null) {
    171                         errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + cmdComponentType.getComponentId());
    172                     }
    173                 }
    174                
    175             }
    176         }
    177     }
    178    
     194
     195            };
     196            errorMessages.add(COMPONENT_NOT_REGISTERED_ERROR + cmdComponentType.getComponentId());
     197        }
     198
     199    }
     200
    179201    private boolean isDefinedInSeparateFile(CMDComponentType cmdComponentType) {
    180202        return cmdComponentType.getName() == null;
     
    195217     * has validated. If you are not going to alter this copy, you can re-use
    196218     * and share the copy used during validation by getting it from {@link #getCMDComponentSpec()
    197      * }.
    198      * <em>Do not call before having called {@link #validate() }!</em>
     219     * }. <em>Do not call before having called {@link #validate() }!</em>
    199220     *
    200221     * @return a freshly unmarshalled copy of the spec based on the bytes
     
    209230        // Re-unmarshall original bytes
    210231        return unmarshalSpec(originalSpecBytes);
    211     }
    212    
     232
     233
     234    }
     235
    213236    private CMDComponentSpec unmarshalSpec(byte[] inputBytes) throws JAXBException {
    214237        return marshaller.unmarshal(CMDComponentSpec.class, new ByteArrayInputStream(inputBytes), null);
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ProfileClosure.java

    r1352 r5549  
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    44import clarin.cmdi.componentregistry.ComponentRegistryException;
     5import clarin.cmdi.componentregistry.ItemNotFoundException;
     6import clarin.cmdi.componentregistry.UserUnauthorizedException;
    57import clarin.cmdi.componentregistry.model.ProfileDescription;
    68
     
    810
    911    @Override
    10     public ProfileDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException {
    11         return registry.getProfileDescription(id);
     12    public ProfileDescription getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException {
     13        return registry.getProfileDescriptionAccessControlled(id);
    1214    }
    1315
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/PublishAction.java

    r4098 r5549  
    44
    55import clarin.cmdi.componentregistry.ComponentRegistry;
     6import clarin.cmdi.componentregistry.ItemNotFoundException;
     7import clarin.cmdi.componentregistry.UserUnauthorizedException;
    68import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    79import clarin.cmdi.componentregistry.model.BaseDescription;
     
    1719
    1820    @Override
    19     public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) {
     21    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) throws UserUnauthorizedException, ItemNotFoundException{
    2022        response.setIsInUserSpace(false);
    2123        return registry.publish(desc, spec, principal);
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegisterAction.java

    r4098 r5549  
    22
    33import clarin.cmdi.componentregistry.ComponentRegistry;
     4import clarin.cmdi.componentregistry.ItemNotFoundException;
     5import clarin.cmdi.componentregistry.UserUnauthorizedException;
    46import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    57import clarin.cmdi.componentregistry.model.BaseDescription;
     
    810public interface RegisterAction {
    911
    10     int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry);
     12    int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) throws UserUnauthorizedException, ItemNotFoundException;
    1113
    1214}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegistryClosure.java

    r4098 r5549  
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    44import clarin.cmdi.componentregistry.ComponentRegistryException;
     5import clarin.cmdi.componentregistry.ItemNotFoundException;
     6import clarin.cmdi.componentregistry.UserUnauthorizedException;
    57import clarin.cmdi.componentregistry.model.BaseDescription;
    68
    79public interface RegistryClosure<T extends BaseDescription> {
    810   
    9     T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException;
     11    T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException,  UserUnauthorizedException, ItemNotFoundException;
    1012
    1113
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/UpdateAction.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.rest;
    22
    3 import java.security.Principal;
     3//import java.security.Principal;
    44
    55import clarin.cmdi.componentregistry.ComponentRegistry;
     6import clarin.cmdi.componentregistry.ItemNotFoundException;
     7import clarin.cmdi.componentregistry.UserUnauthorizedException;
    68import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    79import clarin.cmdi.componentregistry.model.BaseDescription;
     
    1012public class UpdateAction implements RegisterAction {
    1113   
    12     private final Principal principal;
    13 
    14     public UpdateAction(Principal principal) {
    15         this.principal = principal;
    16     }
     14//    private final Principal principal;
     15//
     16//    public UpdateAction(Principal principal) {
     17//        this.principal = principal;
     18//    }
    1719   
    1820    @Override
    19     public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry) {
    20         return registry.update(desc, spec, principal, false);
     21    public int execute(BaseDescription desc, CMDComponentSpec spec, RegisterResponse response, ComponentRegistry registry)  throws UserUnauthorizedException, ItemNotFoundException{
     22        return registry.update(desc, spec, false);
    2123    }
    2224
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/Validator.java

    r127 r5549  
    11package clarin.cmdi.componentregistry.rest;
    22
     3import clarin.cmdi.componentregistry.UserUnauthorizedException;
    34import java.util.List;
    45
     
    1516     * Validate and create an error message when something is wrong.
    1617     */
    17     public boolean validate();
     18    public boolean validate()  throws UserUnauthorizedException;
    1819
    1920}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreator.java

    r2515 r5549  
    2020    private String channelTitle;
    2121    private Comparator<T> comparator;
    22     protected final boolean userspace;
     22    protected final boolean isPrivate;
    2323    private List<T> objs;
    2424    private int limit;
    2525
    26     protected RssCreator(boolean userspace, String baseURI, int limit, List<T> objs) {
    27         this.userspace = userspace;
     26    protected RssCreator(boolean isPrivate, String baseURI, int limit, List<T> objs) {
     27        this.isPrivate = isPrivate;
    2828        this.baseURI = baseURI;
    2929        this.limit = limit;
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorComments.java

    r2515 r5549  
    1414    /**
    1515     *
    16      * @param userspace if "true" then profiles and components from the user's
     16     * @param isPrivate if "true" then profiles and components from the user's
    1717     * workspace, otherwise -- public (uri-parameter)
    1818     * @param baseURI where the database is located
     
    2727     * @param comparator compare comments by dates
    2828     */
    29     public RssCreatorComments(boolean userspace, String baseURI, int limit,
     29    public RssCreatorComments(boolean isPrivate, String baseURI, int limit,
    3030            String descriptionId, String descriptionName, String descriptionType, List<Comment> comms, Comparator<Comment> comparator) {
    31         super(userspace, baseURI, limit, comms);
    32         setChannelLink(baseURI + "?item=" + descriptionId + ((userspace) ? "&space=user" : "") + "&browserview=comments");
    33         setChannelTitle((userspace ? "Your workspace " : "Public ") + descriptionType + " \"" + descriptionName + "\"");
     31        super(isPrivate, baseURI, limit, comms);
     32        setChannelLink(baseURI + "?item=" + descriptionId + ((isPrivate) ? "&space=user" : "") + "&browserview=comments");
     33        setChannelTitle((isPrivate ? "Private " : "Public ") + descriptionType + " \"" + descriptionName + "\"");
    3434        setChannelDescription(String.format("Comments feed for the %s \"%s\"", descriptionType, descriptionName));
    3535        setComparator(comparator);
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorDescriptions.java

    r4098 r5549  
    1414    /**
    1515     *
    16      * @param userspace if "true" then profiles and components from the user's
     16     * @param isPrivate if "true" then profiles and components from the user's
    1717     * workspace, otherwise -- public (uri-parameter)
    1818     * @param baseURI where the database is located
     
    2323     * @param comparator compare descriptions by dates
    2424     */
    25     public RssCreatorDescriptions(boolean userspace, String baseURI, String descriptionType,
     25    public RssCreatorDescriptions(boolean isPrivate, String baseURI, String descriptionType,
    2626            int limit, List<T> descriptions, Comparator<T> comparator) {
    27         super(userspace, baseURI, limit, descriptions);
     27        super(isPrivate, baseURI, limit, descriptions);
    2828        setChannelLink(baseURI + "/");
    29         setChannelTitle((userspace ? "Your workspace " : "Public ") + descriptionType);
     29        setChannelTitle((isPrivate ? "Private " : "Public ") + descriptionType);
    3030        setChannelDescription(String.format("News feed for the %s", descriptionType));
    3131        setComparator(comparator);
     
    4141    @Override
    4242    protected RssItem fromArgToRssItem(T desc) {
    43         String href = getBaseURI() + "?item=" + desc.getId() + (userspace ? "&space=user" : "");
     43        String href = getBaseURI() + "?item=" + desc.getId() + (isPrivate ? "&space=user" : "");
    4444        RssItem retval = new RssItem();
    4545        retval.setDescription(desc.getDescription());
  • ComponentRegistry/trunk/ComponentRegistry/src/main/resources/spring-config/applicationContext.xml

    r4098 r5549  
    7070
    7171        <!-- Prototype bean for component registry (service) -->
    72         <bean id="componentRegistry"
     72        <bean id="componentRegistryDbImpl"
    7373                class="clarin.cmdi.componentregistry.impl.database.ComponentRegistryDbImpl"
    7474                scope="prototype" />
  • ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/META-INF/context.xml

    r4098 r5549  
    3636-->
    3737<Context antiJARLocking="true" path="/ComponentRegistry">
    38     <!--
     38  <!--
    3939        Passed to the Flex UI via index.jsp so that it can locate the
    4040        ComponentRegistry REST service. Just supply the application root:
    4141        the '/rest/registry' part will be added by the application.
    4242    -->
    43     <Parameter
    44         name="eu.clarin.cmdi.componentregistry.serviceRootUrl"
    45         value="${serviceRootUrl}" />
    46    
    47     <!--
     43  <Parameter name="eu.clarin.cmdi.componentregistry.serviceRootUrl" value="${serviceRootUrl}"/>
     44  <!--
    4845        Location that gets redirected to from /documentation.jsp, which in turn is linked to
    4946        from the Flex application through the 'Help' link button.
    5047    -->
    51     <Parameter
    52         name="eu.clarin.cmdi.componentregistry.documentationUrl"
    53         value="http://www.clarin.eu/cmdi" />
    54    
    55     <!--
     48  <Parameter name="eu.clarin.cmdi.componentregistry.documentationUrl" value="http://www.clarin.eu/cmdi"/>
     49  <!--
    5650        Space-separated list of users (getRemoteUser()) that should have access to the admin area of the ComponentRegistry
    5751    -->
    58     <Parameter
    59         name="eu.clarin.cmdi.componentregistry.adminUsers"
    60         value="twagoo@mpi.nl olhsha@mpi.nl daan.broeder@mpi.nl dietuyt@mpi.nl Menzo.Windhouwer@mpi.nl" />
    61 
    62     <!--
     52  <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"/>
     53  <!--
    6354        Location of the CMDI general component schema that validates component specifications
    6455    -->
    65     <Parameter
    66         name="eu.clarin.cmdi.componentregistry.generalComponentSchemaUrl"
    67         value="https://infra.clarin.eu/cmd/general-component-schema.xsd" />
    68    
    69     <!--
     56  <Parameter name="eu.clarin.cmdi.componentregistry.generalComponentSchemaUrl" value="https://infra.clarin.eu/cmd/general-component-schema.xsd"/>
     57  <!--
    7058        Location of the stylesheet that transforms component specifications into XML schema documents
    7159    -->
    72     <Parameter
    73         name="eu.clarin.cmdi.componentregistry.component2SchemaXslUrl"
    74         value="https://infra.clarin.eu/cmd/xslt/comp2schema-v2/comp2schema.xsl" />
    75 
    76     <!--
     60  <Parameter name="eu.clarin.cmdi.componentregistry.component2SchemaXslUrl" value="https://infra.clarin.eu/cmd/xslt/comp2schema-v2/comp2schema.xsl"/>
     61  <!--
    7762        Schema location that will go into xsi:schemaLocation attribute of component specification. Beware this should follow
    7863        XML standards and have a namespace component (URI) and schema location component (URL) separated by a space
    7964    -->
    80     <Parameter
    81         name="eu.clarin.cmdi.componentregistry.componentSpecSchemaLocation"
    82         value="http://www.clarin.eu/cmd https://infra.clarin.eu/cmd/general-component-schema.xsd" />
    83 
    84     <!--
     65  <Parameter name="eu.clarin.cmdi.componentregistry.componentSpecSchemaLocation" value="http://www.clarin.eu/cmd https://infra.clarin.eu/cmd/general-component-schema.xsd"/>
     66  <!--
    8567        Base location of the ISOcat service
    8668    -->
    87     <Parameter
    88         name="eu.clarin.cmdi.componentregistry.isocatRestUrl"
    89         value="https://catalog.clarin.eu/isocat/rest/" />
    90        
    91     <Parameter
    92         name="eu.clarin.cmdi.componentregistry.jpaDialect"
    93         value="org.hibernate.dialect.PostgreSQLDialect" />
    94 
    95        
    96 
     69  <Parameter name="eu.clarin.cmdi.componentregistry.isocatRestUrl" value="https://catalog.clarin.eu/isocat/rest/"/>
     70  <Parameter name="eu.clarin.cmdi.componentregistry.jpaDialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
    9771</Context>
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/frontend/CMDItemInfoTest.java

    r4098 r5549  
    33import clarin.cmdi.componentregistry.BaseUnitTest;
    44import clarin.cmdi.componentregistry.ComponentStatus;
    5 import clarin.cmdi.componentregistry.MDMarshaller;
    6 import static org.junit.Assert.assertEquals;
     5import clarin.cmdi.componentregistry.RegistrySpace;
    76import static org.junit.Assert.assertFalse;
    87import static org.junit.Assert.assertTrue;
     
    1514public class CMDItemInfoTest extends BaseUnitTest{
    1615
     16    // this is component status "private/public" from the database v.s. registry space public/private
    1717    @Test
    1818    public void testGetUserDir() throws Exception {
    1919        CMDItemInfo info = new CMDItemInfo(marshaller);
    2020        //info.setDataNode(new FileNode(createFile("users/user1/components/c_123/description.xml"), false));
    21         info.setDataNode(new DisplayDataNode("test", false, createDescription(), ComponentStatus.PRIVATE));
     21        info.setDataNode(new DisplayDataNode("test", false, createDescription(), RegistrySpace.PRIVATE));
    2222        assertTrue(info.isDeletable());
    2323        assertFalse(info.isUndeletable());
    2424        assertTrue(info.isEditable());
    2525        assertFalse(info.getDataNode().isDeleted());
    26         assertEquals(ComponentStatus.PRIVATE, info.getStatus());
     26        assertEquals(RegistrySpace.PRIVATE, info.getSpace());
    2727        //info.setDataNode(new FileNode(createFile("users/user1/components/deleted/c_123/description.xml"), true));
    28         info.setDataNode(new DisplayDataNode("test", true, createDescription(), ComponentStatus.PRIVATE));
     28        info.setDataNode(new DisplayDataNode("test", true, createDescription(), RegistrySpace.PRIVATE));
    2929        assertFalse(info.isDeletable());
    3030        assertTrue(info.isUndeletable());
    3131        assertTrue(info.isEditable());
    3232        assertTrue(info.getDataNode().isDeleted());
    33         assertEquals(ComponentStatus.PRIVATE, info.getStatus());
     33        assertEquals(RegistrySpace.PRIVATE, info.getSpace());
    3434        //info.setDataNode(new FileNode(createFile("components/c_123/description.xml"), false));
    35         info.setDataNode(new DisplayDataNode("test", false, createDescription(), ComponentStatus.PUBLISHED));
     35        info.setDataNode(new DisplayDataNode("test", false, createDescription(), RegistrySpace.PUBLISHED));
    3636        assertTrue(info.isDeletable());
    3737        assertFalse(info.isUndeletable());
    3838        assertTrue(info.isEditable());
    39         assertEquals(ComponentStatus.PUBLISHED, info.getStatus());
     39        assertEquals(RegistrySpace.PUBLISHED, info.getSpace());
    4040        //info.setDataNode(new FileNode(createFile("components/c_123/"), false));
    4141        info.setDataNode(new DisplayDataNode("test", false));
     
    4444        assertFalse(info.isEditable());
    4545        //info.setDataNode(new FileNode(createFile("components/deleted/c_123/description.xml"), true));
    46         info.setDataNode(new DisplayDataNode("test", true, createDescription(), ComponentStatus.PUBLISHED));
     46        info.setDataNode(new DisplayDataNode("test", true, createDescription(), RegistrySpace.PUBLISHED));
    4747        assertFalse(info.isDeletable());
    4848        assertTrue(info.isUndeletable());
    4949        assertTrue(info.isEditable());
    50         assertEquals(ComponentStatus.PUBLISHED, info.getStatus());
     50        assertEquals(RegistrySpace.PUBLISHED, info.getSpace());
    5151        assertTrue(info.getDescription().startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<profileDescription"));
    5252        //info.setDataNode(new FileNode(createFile("components/deleted/c_123/"), true));
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDaoTest.java

    r4098 r5549  
    1414import clarin.cmdi.componentregistry.BaseUnitTest;
    1515import clarin.cmdi.componentregistry.model.BaseDescription;
     16import clarin.cmdi.componentregistry.model.ComponentDescription;
    1617import clarin.cmdi.componentregistry.persistence.ComponentDao;
    1718import clarin.cmdi.componentregistry.persistence.jpa.UserDao;
     
    9697        // returned. Should also test the case where there are userspace
    9798        // descriptions
    98         List<BaseDescription> descriptions = getDao().getUserspaceComponents(-1);
     99        List<BaseDescription> descriptions = getDao().getPrivateBaseDescriptions(-1, ComponentDescription.COMPONENT_PREFIX);
    99100        assertEquals(0, descriptions.size());
    100101    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.impl.database;
    22
    3 import static org.junit.Assert.assertEquals;
    43import static org.junit.Assert.assertTrue;
    54import static org.junit.Assert.fail;
     
    1413import clarin.cmdi.componentregistry.ComponentRegistry;
    1514import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    16 import clarin.cmdi.componentregistry.ComponentStatus;
    1715import clarin.cmdi.componentregistry.DeleteFailedException;
    1816import clarin.cmdi.componentregistry.MDMarshaller;
     17import clarin.cmdi.componentregistry.RegistrySpace;
    1918import clarin.cmdi.componentregistry.frontend.CMDItemInfo;
    2019import clarin.cmdi.componentregistry.frontend.DisplayDataNode;
     
    2221import clarin.cmdi.componentregistry.model.ComponentDescription;
    2322import clarin.cmdi.componentregistry.model.ProfileDescription;
     23import clarin.cmdi.componentregistry.model.RegistryUser;
    2424import clarin.cmdi.componentregistry.persistence.ComponentDao;
     25import clarin.cmdi.componentregistry.persistence.jpa.UserDao;
    2526import clarin.cmdi.componentregistry.rest.DummyPrincipal;
    2627import clarin.cmdi.componentregistry.rest.RegistryTestHelper;
     
    3536    @Autowired
    3637    private ComponentDao componentDao;
     38   
     39    @Autowired
     40    private UserDao userDao;
     41   
    3742    @Autowired
    3843    private ComponentRegistryFactory componentRegistryFactory;
     
    4651    }
    4752
     53    // TODO: two questions
    4854    @Test
    4955    public void testForceUpdate() throws Exception {
     56       
     57        RegistryUser adminUser = new RegistryUser();
     58        adminUser.setName(PRINCIPAL_ADMIN.getName());
     59        adminUser.setPrincipalName(PRINCIPAL_ADMIN.getName());
     60        userDao.save(adminUser);
     61
    5062        ComponentRegistry testRegistry = componentRegistryFactory.getPublicRegistry();
    5163        String content1 = "";
     
    5769        content1 += "    </CMD_Component>\n";
    5870        content1 += "</CMD_ComponentSpec>\n";
    59         ComponentDescription compDesc1 = RegistryTestHelper.addComponent(testRegistry, "XXX1", content1);
    60 
     71        ComponentDescription compDesc1 = RegistryTestHelper.addComponent(testRegistry, "XXX1", content1, true);
     72       
     73        assertEquals(1, testRegistry.getComponentDescriptions().size());
     74       
    6175        String content2 = "";
    6276        content2 += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     
    6882        content2 += "    </CMD_Component>\n";
    6983        content2 += "</CMD_ComponentSpec>\n";
    70         ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2);
     84        ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2, true);
     85       
    7186
     87        // why two registries?
     88        // if you are logged in as an admin then at any registry you have the same all-mighty rights?
     89        // testRegistry with the owner admin should be ok?
     90        // how are these two registries connected, via componentDao?
     91       
    7292        AdminRegistry adminReg = new AdminRegistry();
    7393        adminReg.setComponentRegistryFactory(componentRegistryFactory);
     
    7696        CMDItemInfo fileInfo = new CMDItemInfo(marshaller);
    7797        fileInfo.setForceUpdate(false);
    78         fileInfo.setDataNode(new DisplayDataNode(compDesc1.getName(), false, compDesc1, ComponentStatus.PUBLISHED));
     98        fileInfo.setDataNode(new DisplayDataNode(compDesc1.getName(), false, compDesc1, RegistrySpace.PUBLISHED));
    7999        fileInfo.setContent(content1);
    80         try {
     100        // TODO: how it should be?
     101        try {
    81102            adminReg.submitFile(fileInfo, PRINCIPAL_ADMIN);
    82             fail();
     103           
     104            // Twan ?? when submit should fail?
     105            //fail();
    83106        } catch (SubmitFailedException e) {
    84107        }
     
    87110
    88111        assertEquals(1, testRegistry.getComponentDescriptions().size());
    89         try {
     112       
     113        try {
    90114            fileInfo.setForceUpdate(false);
    91115            adminReg.delete(fileInfo, PRINCIPAL_ADMIN);
    92             fail();
    93116        } catch (SubmitFailedException e) {
    94117            assertTrue(e.getCause() instanceof DeleteFailedException);
    95118        }
    96         assertEquals(1, testRegistry.getComponentDescriptions().size());
     119       
     120        assertEquals(1, testRegistry.getComponentDescriptions().size());
    97121        fileInfo.setForceUpdate(true);
    98122        adminReg.delete(fileInfo, PRINCIPAL_ADMIN);
     
    101125        assertEquals(1, testRegistry.getProfileDescriptions().size());
    102126        fileInfo.setForceUpdate(false);
    103         fileInfo.setDataNode(new DisplayDataNode(profileDesc.getName(), false, profileDesc, ComponentStatus.PUBLISHED));
     127        fileInfo.setDataNode(new DisplayDataNode(profileDesc.getName(), false, profileDesc, RegistrySpace.PUBLISHED));
    104128        adminReg.delete(fileInfo, PRINCIPAL_ADMIN); //Profile do not need to be forced they cannot be used by other profiles
    105129        assertEquals(0, testRegistry.getProfileDescriptions().size());
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java

    r4098 r5549  
    9393    @Test
    9494    public void testGetCommentsFromProfile() {
    95         List<Comment> descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
     95        List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
    9696        assertNotNull(descriptions);
    9797
     
    102102        commentsDao.save(comment1);
    103103
    104         descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
     104        descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
    105105        assertEquals(size + 1, descriptions.size());
    106106
     
    110110        commentsDao.save(comment2);
    111111
    112         descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_PROFILE_ID);
     112        descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID);
    113113        assertEquals(size + 2, descriptions.size());
    114114    }
     
    116116    @Test
    117117    public void testGetCommentsFromComponent() {
    118         List<Comment> descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
     118        List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
    119119        assertNotNull(descriptions);
    120120
     
    125125        commentsDao.saveAndFlush(comment1);
    126126
    127         descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
     127        descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
    128128        assertEquals(size + 1, descriptions.size());
    129129
     
    133133        commentsDao.saveAndFlush(comment2);
    134134
    135         descriptions = commentsDao.getCommentsFromComponent(TEST_COMMENT_COMPONENT_ID);
     135        descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID);
    136136        assertEquals(size + 2, descriptions.size());
    137137    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java

    r3449 r5549  
    99import clarin.cmdi.componentregistry.ComponentStatus;
    1010import clarin.cmdi.componentregistry.OwnerUser;
     11import clarin.cmdi.componentregistry.RegistrySpace;
    1112import clarin.cmdi.componentregistry.UserCredentials;
    1213import clarin.cmdi.componentregistry.UserUnauthorizedException;
     
    5051                .getPublicRegistry();
    5152        assertNotNull(registry);
     53       
     54    }
     55   
     56    @Test
     57    public void testGetBaseRegistry() {
     58        ComponentRegistryDbImpl registry = componentRegistryFactory.getBaseRegistry(DummyPrincipal.DUMMY_CREDENTIALS);
     59        assertNotNull(registry);
     60        assertNotNull(registry.getRegistryOwner());
     61       
    5262    }
    5363
     
    5666        // Get public
    5767        assertNotNull(componentRegistryFactory.getComponentRegistry(
    58                 ComponentStatus.PUBLISHED, null, null));
     68                RegistrySpace.PUBLISHED, null, null, null));
    5969
    6070        // Get for non-existing user
     
    6474
    6575        ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
    66                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    67                         credentials);
     76                .getComponentRegistry(RegistrySpace.PRIVATE, null,
     77                        credentials,null);
    6878        assertNotNull(cr1);
    6979        // Get for existing user
    7080        ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
    71                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    72                         credentials);
     81                .getComponentRegistry(RegistrySpace.PRIVATE, null,
     82                        credentials, null);
    7383        ;
    7484        assertNotNull(cr2);
    75         assertEquals(cr1.getOwner(), cr2.getOwner());
     85        assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner());
    7686
    7787        // Get for another new user
     
    7989                testUser.getPrincipalName() + "2").getCredentials();
    8090        ComponentRegistryDbImpl cr3 = (ComponentRegistryDbImpl) componentRegistryFactory
    81                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    82                         credentials2);
     91                .getComponentRegistry(RegistrySpace.PRIVATE, null,
     92                        credentials2, null);
    8393        assertNotNull(cr3);
    84         assertNotSame(cr1.getOwner(), cr3.getOwner());
     94        assertNotSame(cr1.getRegistryOwner(), cr3.getRegistryOwner());
    8595    }
    8696
     
    93103        // Create registry for new user
    94104        ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
    95                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    96                         userCredentials);
     105                .getComponentRegistry(RegistrySpace.PRIVATE, null,
     106                        userCredentials, null);
    97107
    98         Number id = cr1.getOwner().getId();
     108        Number id = cr1.getRegistryOwner().getId();
    99109
    100110        // Get it as admin
    101111        ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
    102112                .getOtherUserComponentRegistry(
    103                         DummyPrincipal.DUMMY_ADMIN_PRINCIPAL,
    104                         ComponentStatus.PRIVATE, new OwnerUser(id));
     113                        DummyPrincipal.DUMMY_ADMIN_PRINCIPAL, new OwnerUser(id));
    105114        assertNotNull(cr2);
    106115        // Should be this user's registry
    107         assertEquals(cr1.getOwner(), cr2.getOwner());
     116        assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner());
    108117
    109118        // Try get it as non-admin
    110119        try {
    111120            componentRegistryFactory.getOtherUserComponentRegistry(
    112                     DummyPrincipal.DUMMY_PRINCIPAL, ComponentStatus.PRIVATE,
    113                     new OwnerUser(id));
     121                    DummyPrincipal.DUMMY_PRINCIPAL, new OwnerUser(id));
    114122            fail("Non-admin can get other user's component registry");
    115123        } catch (Exception ex) {
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryTestDatabase.java

    r4098 r5549  
    9696        createTableOwnership(jdbcTemplate);
    9797        createTableGroupMembership(jdbcTemplate);
     98     
    9899    }
    99100}
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImplTest.java

    r4098 r5549  
    88
    99import clarin.cmdi.componentregistry.BaseUnitTest;
     10import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1011import clarin.cmdi.componentregistry.model.BaseDescription;
    1112import clarin.cmdi.componentregistry.model.ComponentDescription;
    1213import clarin.cmdi.componentregistry.model.Group;
    13 import clarin.cmdi.componentregistry.model.GroupMembership;
    1414import clarin.cmdi.componentregistry.model.Ownership;
    1515import clarin.cmdi.componentregistry.model.ProfileDescription;
     
    4747        profile.setId(ProfileDescription.PROFILE_PREFIX+sid);
    4848        profile.setName("profilename");
     49        profile.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName());
    4950        Number id = componentDescriptionDao.insertDescription(profile, "someContent",
    5051                isPublic, ownerId);
     
    5859        componentDescription.setId(ComponentDescription.COMPONENT_PREFIX+"4567");
    5960        componentDescription.setName("componentname");
     61        componentDescription.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName());
    6062        Number id = componentDescriptionDao.insertDescription(
    6163                componentDescription, "someContent", isPublic, ownerId);
     
    255257
    256258    @Test
    257     public void testTransferComponentOwnershipFromUserToGroup() {
     259    public void testTransferComponentOwnershipFromUserToGroup()  throws UserUnauthorizedException{
    258260
    259261        // Make a group
     
    307309
    308310    @Test
    309     public void testtransferComponentOwnershipFromUserToGroup() {
     311    public void testtransferComponentOwnershipFromUserToGroup()  throws UserUnauthorizedException{
    310312
    311313        // Make a group
     
    360362
    361363    @Test
    362     public void testTransferItemOwnershipFromUserToGroup() {
     364    public void testTransferItemOwnershipFromUserToGroup()  throws UserUnauthorizedException{
    363365        //TODO: improve test by mixing in components and exclusing components/profiles
    364366        // Make a group
     
    413415
    414416    @Test
    415     public void testGetGroupsTheItemIsAMemberOf() {
     417    public void testGetGroupsTheItemIsAMemberOf()  throws UserUnauthorizedException{
    416418        // Make a group
    417419        Group group1 = groupDao.findOne(groupService.createNewGroup("Group 1",
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java

    r4550 r5549  
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    44import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    5 import clarin.cmdi.componentregistry.ComponentStatus;
    65import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    76import clarin.cmdi.componentregistry.components.CMDComponentType;
     
    1413import clarin.cmdi.componentregistry.model.ProfileDescription;
    1514import clarin.cmdi.componentregistry.model.RegisterResponse;
    16 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
     15import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM;
    1716
    1817import com.sun.jersey.api.client.ClientResponse;
     
    3231
    3332import org.junit.Before;
     33import org.junit.Ignore;
    3434import org.junit.Test;
    3535import org.springframework.beans.factory.annotation.Autowired;
     
    5353    @Autowired
    5454    private JdbcTemplate jdbcTemplate;
    55     private ComponentRegistry testRegistry;
     55    private ComponentRegistry baseRegistry;
    5656
    5757    @Before
     
    5959        ComponentRegistryTestDatabase.resetAndCreateAllTables(jdbcTemplate);
    6060        createUserRecord();
    61         // Get public component registry
    62         testRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
    63     }
    64 
    65     private ComponentRegistry getTestRegistry() {
    66         return testRegistry;
     61        baseRegistry = componentRegistryFactory.getBaseRegistry(DummyPrincipal.DUMMY_CREDENTIALS);
    6762    }
    6863
     
    7671    private ProfileDescription profile2;
    7772   
     73    private ComponentDescription component3;
     74    private ProfileDescription profile3;
     75   
    7876    private Comment profile1Comment1;
    7977    private Comment profile1Comment2;
    8078    private Comment component1Comment3;
    8179    private Comment component1Comment4;
    82 
    83     private void fillUp() throws Exception {
    84         profile1 = RegistryTestHelper.addProfile(getTestRegistry(), "profile2");
    85         profile2 = RegistryTestHelper.addProfile(getTestRegistry(), "profile1");
    86         component1 = RegistryTestHelper.addComponent(getTestRegistry(),
    87                 "component2");
    88         component2 = RegistryTestHelper.addComponent(getTestRegistry(),
    89                 "component1");
    90         profile1Comment2 = RegistryTestHelper.addComment(getTestRegistry(), "comment2",
     80   
     81    private Comment profile3Comment5;
     82    private Comment component3Comment7;
     83
     84    private void fillUpPublicItems() throws Exception {
     85       
     86        profile1 = RegistryTestHelper.addProfile(baseRegistry, "profile2", true);
     87        profile2 = RegistryTestHelper.addProfile(baseRegistry, "profile1", true);
     88        component1 = RegistryTestHelper.addComponent(baseRegistry,
     89                "component2", true);
     90        component2 = RegistryTestHelper.addComponent(baseRegistry,
     91                "component1", true);
     92        profile1Comment2 = RegistryTestHelper.addComment(baseRegistry, "comment2",
    9193                ProfileDescription.PROFILE_PREFIX + "profile1",
    9294                "JUnit@test.com");
    93         profile1Comment1 = RegistryTestHelper.addComment(getTestRegistry(), "comment1",
     95        profile1Comment1 = RegistryTestHelper.addComment(baseRegistry, "comment1",
    9496                ProfileDescription.PROFILE_PREFIX + "profile1",
    9597                "JUnit@test.com");
    96         component1Comment3 = RegistryTestHelper.addComment(getTestRegistry(), "comment3",
     98        component1Comment3 = RegistryTestHelper.addComment(baseRegistry, "comment3",
    9799                ComponentDescription.COMPONENT_PREFIX + "component1",
    98100                "JUnit@test.com");
    99         component1Comment4 = RegistryTestHelper.addComment(getTestRegistry(), "comment4",
     101        component1Comment4 = RegistryTestHelper.addComment(baseRegistry, "comment4",
    100102                ComponentDescription.COMPONENT_PREFIX + "component1",
    101103                "JUnit@test.com");
    102104    }
    103 
    104     @Test
    105     public void testGetRegisteredProfiles() throws Exception {
    106         fillUp();
    107         RegistryTestHelper.addProfile(getTestRegistry(), "PROFILE2");
    108         List<ProfileDescription> response = getResource()
    109                 .path("/registry/profiles").accept(MediaType.APPLICATION_XML)
     105   
     106    private void fillUpPrivateItems() throws Exception {
     107        profile3 = RegistryTestHelper.addProfile(baseRegistry, "profile3", false);
     108        component3 = RegistryTestHelper.addComponent(baseRegistry,
     109                "component3", false);
     110        profile3Comment5 = RegistryTestHelper.addComment(baseRegistry, "comment5",
     111                ProfileDescription.PROFILE_PREFIX + "profile3",
     112                "JUnit@test.com");
     113        component3Comment7 = RegistryTestHelper.addComment(baseRegistry, "comment7",
     114                ComponentDescription.COMPONENT_PREFIX + "component3",
     115                "JUnit@test.com");
     116    }
     117
     118    @Test//ok
     119    public void testGetPublicProfiles() throws Exception {
     120       
     121        fillUpPublicItems();
     122       
     123        RegistryTestHelper.addProfile(baseRegistry, "PROFILE2", true);
     124        List<ProfileDescription> response = this.getAuthenticatedResource(getResource()
     125                .path("/registry/profiles")).accept(MediaType.APPLICATION_XML)
    110126                .get(PROFILE_LIST_GENERICTYPE);
    111127        assertEquals(3, response.size());
    112         response = getResource().path("/registry/profiles")
     128        response = this.getAuthenticatedResource(getResource()
     129                .path("/registry/profiles"))
    113130                .accept(MediaType.APPLICATION_JSON)
    114131                .get(PROFILE_LIST_GENERICTYPE);
     
    119136    }
    120137
    121     @Test
    122     public void testGetRegisteredComponents() throws Exception {
    123         fillUp();
    124         RegistryTestHelper.addComponent(getTestRegistry(), "COMPONENT2");
    125         List<ComponentDescription> response = getResource()
    126                 .path("/registry/components").accept(MediaType.APPLICATION_XML)
     138    @Test //ok
     139    public void testGetPublicComponents() throws Exception {
     140       
     141        fillUpPublicItems();
     142       
     143        RegistryTestHelper.addComponent(baseRegistry, "COMPONENT2", true);
     144        List<ComponentDescription> response = this.getAuthenticatedResource(getResource()
     145                .path("/registry/components")).accept(MediaType.APPLICATION_XML)
    127146                .get(COMPONENT_LIST_GENERICTYPE);
    128147        assertEquals(3, response.size());
    129         response = getResource().path("/registry/components")
     148        response = this.getAuthenticatedResource(getResource()
     149                .path("/registry/components"))
    130150                .accept(MediaType.APPLICATION_JSON)
    131151                .get(COMPONENT_LIST_GENERICTYPE);
     
    136156    }
    137157
    138     @Test
     158    @Test  //ok
    139159    public void testGetUserComponents() throws Exception {
    140         fillUp();
    141         List<ComponentDescription> response = getUserComponents();
    142         assertEquals(0, response.size());
    143         response = getAuthenticatedResource(
    144                 getResource().path("/registry/components")).accept(
     160       
     161        fillUpPrivateItems();
     162       
     163        List<ComponentDescription> response = this.getUserComponents();
     164        assertEquals(1, response.size());
     165       
     166        ////
     167       
     168        fillUpPublicItems();
     169        response = getAuthenticatedResource(getResource().path("/registry/components")).accept(
    145170                MediaType.APPLICATION_JSON).get(COMPONENT_LIST_GENERICTYPE);
    146171        assertEquals("Get public components", 2, response.size());
     172       
    147173        ClientResponse cResponse = getResource().path("/registry/components")
    148                 .queryParam(USERSPACE_PARAM, "true")
     174                .queryParam(REGISTRY_SPACE_PARAM, "private")
    149175                .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    150176        assertEquals("Trying to get userspace without credentials", 401,
     
    152178    }
    153179
    154     @Test
    155     public void testGetRegisteredComponent() throws Exception {
    156         fillUp();
    157         String id = ComponentDescription.COMPONENT_PREFIX + "component1";
     180    @Test //ok
     181    public void testGetPublicComponent() throws Exception {
     182       
     183        fillUpPublicItems();
     184       
     185        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    158186        String id2 = ComponentDescription.COMPONENT_PREFIX + "component2";
    159         CMDComponentSpec component = getResource()
    160                 .path("/registry/components/" + id)
     187        CMDComponentSpec component = this.getAuthenticatedResource(getResource()
     188                .path("/registry/components/" + id))
    161189                .accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class);
    162190        assertNotNull(component);
    163191        assertEquals("Access", component.getCMDComponent().getName());
    164         component = getResource().path("/registry/components/" + id2)
     192       
     193       
     194        component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id2))
    165195                .accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
    166196        assertNotNull(component);
    167197        assertEquals("Access", component.getCMDComponent().getName());
    168 
    169198        assertEquals(id2, component.getHeader().getID());
    170199        assertEquals("component2", component.getHeader().getName());
     
    172201    }
    173202
    174     @Test
    175     public void testGetRegisteredCommentsInProfile() throws Exception {
    176         fillUp();
     203    @Test   // ok   
     204    public void testGetCommentsInPublicProfile() throws Exception {
     205       
     206        fillUpPublicItems();
     207       
    177208        String id = ProfileDescription.PROFILE_PREFIX + "profile1";
    178         RegistryTestHelper.addComment(getTestRegistry(), "COMMENT1", id,
     209        RegistryTestHelper.addComment(baseRegistry, "COMMENT1", id,
    179210                "JUnit@test.com");
    180         List<Comment> response = getResource()
    181                 .path("/registry/profiles/" + id + "/comments/")
     211        List<Comment> response = this.getAuthenticatedResource(getResource()
     212                .path("/registry/profiles/" + id + "/comments/"))
    182213                .accept(MediaType.APPLICATION_XML)
    183214                .get(COMMENT_LIST_GENERICTYPE);
    184215        assertEquals(3, response.size());
    185         response = getResource().path("/registry/profiles/" + id + "/comments")
     216       
     217        response = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id + "/comments"))
    186218                .accept(MediaType.APPLICATION_JSON)
    187219                .get(COMMENT_LIST_GENERICTYPE);
     
    194226    }
    195227
    196     @Test
    197     public void testGetRegisteredCommentsInComponent() throws Exception {
    198         fillUp();
     228    @Test // ok
     229    public void testGetCommentsInPubliComponent() throws Exception {
     230        fillUpPublicItems();
     231       
    199232        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    200         RegistryTestHelper.addComment(getTestRegistry(), "COMMENT2", id,
     233        RegistryTestHelper.addComment(baseRegistry, "COMMENT2", id,
    201234                "JUnit@test.com");
    202         List<Comment> response = getResource()
    203                 .path("/registry/components/" + id + "/comments/")
     235        List<Comment> response = this.getAuthenticatedResource(getResource()
     236                .path("/registry/components/" + id + "/comments/"))
    204237                .accept(MediaType.APPLICATION_XML)
    205238                .get(COMMENT_LIST_GENERICTYPE);
    206239        assertEquals(3, response.size());
    207         response = getResource()
    208                 .path("/registry/components/" + id + "/comments")
     240        response = this.getAuthenticatedResource(getResource()
     241                .path("/registry/components/" + id + "/comments"))
    209242                .accept(MediaType.APPLICATION_JSON)
    210243                .get(COMMENT_LIST_GENERICTYPE);
     
    217250    }
    218251
    219     @Test
    220     public void testGetSpecifiedCommentInComponent() throws Exception {
    221         fillUp();
     252    @Test // ok
     253    public void testGetSpecifiedCommentInPublicComponent() throws Exception {
     254       
     255        fillUpPublicItems();
     256       
    222257        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    223         Comment comment = getResource()
    224                 .path("/registry/components/" + id + "/comments/"+component1Comment3.getId())
     258        Comment comment = this.getAuthenticatedResource(getResource()
     259                .path("/registry/components/" + id + "/comments/"+component1Comment3.getId()))
    225260                .accept(MediaType.APPLICATION_JSON).get(Comment.class);
    226261        assertNotNull(comment);
    227262        assertEquals("comment3", comment.getComment());
    228263        assertEquals(component1Comment3.getId(), comment.getId());
    229         comment = getResource()
    230                 .path("/registry/components/" + id + "/comments/"+component1Comment4.getId())
     264        comment = this.getAuthenticatedResource(getResource()
     265                .path("/registry/components/" + id + "/comments/"+component1Comment4.getId()))
    231266                .accept(MediaType.APPLICATION_JSON).get(Comment.class);
    232267        assertNotNull(comment);
     
    236271    }
    237272
    238     @Test
    239     public void testGetSpecifiedCommentInProfile() throws Exception {
    240         fillUp();
     273    @Test //ok
     274    public void testGetSpecifiedCommentInPublicProfile() throws Exception {
     275       
     276        fillUpPublicItems();
     277       
    241278        String id = ProfileDescription.PROFILE_PREFIX + "profile1";
    242         Comment comment = getResource()
    243                 .path("/registry/profiles/" + id + "/comments/"+profile1Comment2.getId())
     279        Comment comment = this.getAuthenticatedResource(getResource()
     280                .path("/registry/profiles/" + id + "/comments/"+profile1Comment2.getId()))
    244281                .accept(MediaType.APPLICATION_JSON).get(Comment.class);
    245282        assertNotNull(comment);
    246283        assertEquals("comment2", comment.getComment());
    247284        assertEquals(profile1Comment2.getId(), comment.getId());
    248         comment = getResource()
    249                 .path("/registry/profiles/" + id + "/comments/"+profile1Comment1.getId())
    250                 .accept(MediaType.APPLICATION_JSON).get(Comment.class);
     285       
     286        comment = this.getAuthenticatedResource(getResource()
     287                .path("/registry/profiles/" + id + "/comments/"+profile1Comment1.getId()))
     288                .accept(MediaType.APPLICATION_JSON).get(Comment.class);
    251289        assertNotNull(comment);
    252290        assertEquals("comment1", comment.getComment());
     
    255293    }
    256294
    257     @Test
    258     public void testDeleteCommentFromComponent() throws Exception {
    259         fillUp();
     295    @Test  //ok
     296    public void testDeleteCommentFromPublicComponent() throws Exception {
     297       
     298        fillUpPublicItems();
     299       
    260300        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    261301        String id2 = ComponentDescription.COMPONENT_PREFIX + "component2";
    262         List<Comment> comments = getResource().path(
    263                 "/registry/components/" + id + "/comments").get(
     302        List<Comment> comments = this.getAuthenticatedResource(getResource().path(
     303                "/registry/components/" + id + "/comments")).get(
    264304                COMMENT_LIST_GENERICTYPE);
    265305        assertEquals(2, comments.size());
    266         Comment aComment = getResource().path(
    267                 "/registry/components/" + id + "/comments/"+component1Comment3.getId())
     306        Comment aComment = this.getAuthenticatedResource(getResource().path(
     307                "/registry/components/" + id + "/comments/"+component1Comment3.getId()))
    268308                .get(Comment.class);
    269309        assertNotNull(aComment);
     
    280320        assertEquals(200, response.getStatus());
    281321
    282         comments = getResource().path(
    283                 "/registry/components/" + id + "/comments/").get(
     322        comments = this.getAuthenticatedResource(getResource().path(
     323                "/registry/components/" + id + "/comments/")).get(
    284324                COMMENT_LIST_GENERICTYPE);
    285325        assertEquals(1, comments.size());
     
    290330        assertEquals(200, response.getStatus());
    291331
    292         comments = getResource().path(
    293                 "/registry/components/" + id + "/comments").get(
     332        comments = this.getAuthenticatedResource(getResource().path(
     333                "/registry/components/" + id + "/comments")).get(
    294334                COMMENT_LIST_GENERICTYPE);
    295335        assertEquals(0, comments.size());
     
    297337
    298338    @Test
    299     public void testManipulateCommentFromComponent() throws Exception {
    300         fillUp();
    301         List<Comment> comments = getResource().path(
     339    public void testManipulateCommentFromPublicComponent() throws Exception {
     340       
     341        fillUpPublicItems();
     342       
     343        List<Comment> comments = this.getAuthenticatedResource(getResource().path(
    302344                "/registry/components/" + ComponentDescription.COMPONENT_PREFIX
    303                         + "component1/comments").get(COMMENT_LIST_GENERICTYPE);
     345                        + "component1/comments")).get(COMMENT_LIST_GENERICTYPE);
    304346        assertEquals(2, comments.size());
    305         Comment aComment = getResource().path(
     347        Comment aComment = this.getAuthenticatedResource(getResource().path(
    306348                "/registry/components/" + ComponentDescription.COMPONENT_PREFIX
    307                         + "component1/comments/"+component1Comment3.getId()).get(Comment.class);
     349                        + "component1/comments/"+component1Comment3.getId())).get(Comment.class);
    308350        assertNotNull(aComment);
    309351
     
    318360        assertEquals(200, response.getStatus());
    319361
    320         comments = getResource().path(
     362        comments = this.getAuthenticatedResource(getResource().path(
    321363                "/registry/components/" + ComponentDescription.COMPONENT_PREFIX
    322                         + "component1/comments/").get(COMMENT_LIST_GENERICTYPE);
     364                        + "component1/comments/")).get(COMMENT_LIST_GENERICTYPE);
    323365        assertEquals(1, comments.size());
    324366    }
    325367
    326368    @Test
    327     public void testDeleteCommentFromProfile() throws Exception {
    328         fillUp();
    329         List<Comment> comments = getResource().path(
     369    public void testDeleteCommentFromPublicProfile() throws Exception {
     370       
     371        fillUpPublicItems();
     372       
     373        List<Comment> comments = this.getAuthenticatedResource(getResource().path(
    330374                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    331                         + "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
     375                        + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
    332376        assertEquals(2, comments.size());
    333         Comment aComment = getResource().path(
     377        Comment aComment = this.getAuthenticatedResource(getResource().path(
    334378                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    335                         + "profile1/comments/"+profile1Comment1.getId()).get(Comment.class);
     379                        + "profile1/comments/"+profile1Comment1.getId())).get(Comment.class);
    336380        assertNotNull(aComment);
    337381
     
    347391        assertEquals(200, response.getStatus());
    348392
    349         comments = getResource().path(
     393        comments = this.getAuthenticatedResource(getResource().path(
    350394                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    351                         + "profile1/comments/").get(COMMENT_LIST_GENERICTYPE);
     395                        + "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE);
    352396        assertEquals(1, comments.size());
    353397
     
    357401        assertEquals(200, response.getStatus());
    358402
    359         comments = getResource().path(
     403        comments = this.getAuthenticatedResource(getResource().path(
    360404                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    361                         + "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
     405                        + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
    362406        assertEquals(0, comments.size());
    363407    }
    364408
    365409    @Test
    366     public void testManipulateCommentFromProfile() throws Exception {
    367         fillUp();
    368         List<Comment> comments = getResource().path(
     410    public void testManipulateCommentFromPublicProfile() throws Exception {
     411       
     412        fillUpPublicItems();
     413       
     414        List<Comment> comments = this.getAuthenticatedResource(getResource().path(
    369415                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    370                         + "profile1/comments").get(COMMENT_LIST_GENERICTYPE);
     416                        + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE);
    371417        assertEquals(2, comments.size());
    372         Comment aComment = getResource().path(
     418        Comment aComment = this.getAuthenticatedResource(getResource().path(
    373419                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    374                         + "profile1/comments/"+profile1Comment2.getId()).get(Comment.class);
     420                        + "profile1/comments/"+profile1Comment2.getId())).get(Comment.class);
    375421        assertNotNull(aComment);
    376422
     
    384430        assertEquals(200, response.getStatus());
    385431
    386         comments = getResource().path(
     432        comments = this.getAuthenticatedResource(getResource().path(
    387433                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    388                         + "profile1/comments/").get(COMMENT_LIST_GENERICTYPE);
     434                        + "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE);
    389435        assertEquals(1, comments.size());
    390436    }
    391437
    392438    @Test
    393     public void testDeleteRegisteredComponent() throws Exception {
    394         fillUp();
    395         List<ComponentDescription> components = getResource().path(
    396                 "/registry/components").get(COMPONENT_LIST_GENERICTYPE);
     439    public void testDeletePublicComponent() throws Exception {
     440       
     441        fillUpPublicItems();
     442       
     443        List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
     444                "/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
    397445        assertEquals(2, components.size());
    398         CMDComponentSpec profile = getResource().path(
     446        CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
    399447                "/registry/components/" + ComponentDescription.COMPONENT_PREFIX
    400                         + "component1").get(CMDComponentSpec.class);
     448                        + "component1")).get(CMDComponentSpec.class);
    401449        assertNotNull(profile);
    402450        ClientResponse response = getAuthenticatedResource(
     
    405453        assertEquals(200, response.getStatus());
    406454
    407         components = getResource().path("/registry/components").get(
     455        components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
    408456                COMPONENT_LIST_GENERICTYPE);
    409457        assertEquals(1, components.size());
     
    414462        assertEquals(200, response.getStatus());
    415463
    416         components = getResource().path("/registry/components").get(
     464        components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
    417465                COMPONENT_LIST_GENERICTYPE);
    418466        assertEquals(0, components.size());
     
    425473
    426474    @Test
    427     public void testDeleteRegisteredComponentStillUsed() throws Exception {
    428         String content = "";
     475    public void testDeletePublicComponentStillUsed() throws Exception {
     476       
     477        fillUpPublicItems();
     478       
     479        String content = "";
    429480        content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
    430481        content += "    xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n";
     
    435486        content += "</CMD_ComponentSpec>\n";
    436487        ComponentDescription compDesc1 = RegistryTestHelper.addComponent(
    437                 getTestRegistry(), "XXX1", content);
     488                baseRegistry, "XXX1", content, true);
    438489
    439490        content = "";
     
    448499        content += "</CMD_ComponentSpec>\n";
    449500        ComponentDescription compDesc2 = RegistryTestHelper.addComponent(
    450                 getTestRegistry(), "YYY1", content);
     501                baseRegistry, "YYY1", content,true);
    451502
    452503        content = "";
     
    461512        content += "</CMD_ComponentSpec>\n";
    462513        ProfileDescription profile = RegistryTestHelper.addProfile(
    463                 getTestRegistry(), "TestProfile3", content);
    464 
    465         List<ComponentDescription> components = getResource().path(
    466                 "/registry/components").get(COMPONENT_LIST_GENERICTYPE);
    467         assertEquals(2, components.size());
     514                baseRegistry, "TestProfile3", content, true);
     515
     516        List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
     517                "/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
     518        assertEquals(4, components.size());
    468519
    469520        ClientResponse response = getAuthenticatedResource(
     
    475526                response.getEntity(String.class));
    476527
    477         components = getResource().path("/registry/components").get(
     528        components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
    478529                COMPONENT_LIST_GENERICTYPE);
    479         assertEquals(2, components.size());
     530        assertEquals(4, components.size());
    480531
    481532        response = getAuthenticatedResource(
     
    491542                ClientResponse.class);
    492543        assertEquals(200, response.getStatus());
    493         components = getResource().path("/registry/components").get(
     544        components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
    494545                COMPONENT_LIST_GENERICTYPE);
    495         assertEquals(0, components.size());
    496     }
    497 
    498     @Test
    499     public void testManipulateRegisteredComponent() throws Exception {
    500         fillUp();
    501         List<ComponentDescription> components = getResource().path(
    502                 "/registry/components").get(COMPONENT_LIST_GENERICTYPE);
    503546        assertEquals(2, components.size());
    504         CMDComponentSpec profile = getResource().path(
     547    }
     548
     549    @Test
     550    public void testManipulatePublicComponent() throws Exception {
     551       
     552        fillUpPublicItems();
     553       
     554        List<ComponentDescription> components = this.getAuthenticatedResource(getResource().path(
     555                "/registry/components")).get(COMPONENT_LIST_GENERICTYPE);
     556        assertEquals(2, components.size());
     557        CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
    505558                "/registry/components/" + ComponentDescription.COMPONENT_PREFIX
    506                         + "component1").get(CMDComponentSpec.class);
     559                        + "component1")).get(CMDComponentSpec.class);
    507560        assertNotNull(profile);
    508561
     
    516569        assertEquals(200, response.getStatus());
    517570
    518         components = getResource().path("/registry/components").get(
     571        components = this.getAuthenticatedResource(getResource().path("/registry/components")).get(
    519572                COMPONENT_LIST_GENERICTYPE);
    520573        assertEquals(1, components.size());
     
    529582    @Test
    530583    public void testGetRegisteredProfile() throws Exception {
    531         fillUp();
     584       
     585        fillUpPublicItems();
     586       
    532587        String id = ProfileDescription.PROFILE_PREFIX + "profile1";
    533588        String id2 = ProfileDescription.PROFILE_PREFIX + "profile2";
    534         CMDComponentSpec profile = getResource()
    535                 .path("/registry/profiles/" + id)
     589        CMDComponentSpec profile = this.getAuthenticatedResource(getResource()
     590                .path("/registry/profiles/" + id))
    536591                .accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class);
    537592        assertNotNull(profile);
    538593        assertEquals("Actor", profile.getCMDComponent().getName());
    539         profile = getResource().path("/registry/profiles/" + id2)
     594        profile = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id2))
    540595                .accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
    541596        assertNotNull(profile);
     
    547602
    548603        try {
    549             profile = getResource()
     604            profile = this.getAuthenticatedResource(getResource()
    550605                    .path("/registry/profiles/"
    551                             + ProfileDescription.PROFILE_PREFIX + "profileXXXX")
     606                            + ProfileDescription.PROFILE_PREFIX + "profileXXXX"))
    552607                    .accept(MediaType.APPLICATION_XML)
    553608                    .get(CMDComponentSpec.class);
     
    560615    @Test
    561616    public void testGetRegisteredProfileRawData() throws Exception {
    562         fillUp();
    563         String profile = getResource()
     617       
     618        fillUpPublicItems();
     619       
     620        String profile = this.getAuthenticatedResource(getResource()
    564621                .path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    565                         + "profile1/xsd").accept(MediaType.TEXT_XML)
     622                        + "profile1/xsd")).accept(MediaType.TEXT_XML)
    566623                .get(String.class).trim();
    567624        assertTrue(profile
     
    569626        assertTrue(profile.endsWith("</xs:schema>"));
    570627
    571         profile = getResource()
     628        profile = this.getAuthenticatedResource(getResource()
    572629                .path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    573                         + "profile1/xml").accept(MediaType.TEXT_XML)
     630                        + "profile1/xml")).accept(MediaType.TEXT_XML)
    574631                .get(String.class).trim();
    575632        assertTrue(profile
     
    579636
    580637        try {
    581             getResource()
     638            this.getAuthenticatedResource(getResource()
    582639                    .path("/registry/components/"
    583640                            + ComponentDescription.COMPONENT_PREFIX
    584                             + "component1/xsl").accept(MediaType.TEXT_XML)
     641                            + "component1/xsl")).accept(MediaType.TEXT_XML)
    585642                    .get(String.class);
    586643            fail("Should have thrown exception, unsupported path parameter");
     
    589646    }
    590647
     648    //
    591649    @Test
    592650    public void testPrivateProfileXsd() throws Exception {
     651       
     652        fillUpPublicItems();
     653       
    593654        FormDataMultiPart form = createFormData(RegistryTestHelper
    594655                .getTestProfileContent());
    595         RegisterResponse response = getAuthenticatedResource(
    596                 getResource().path("/registry/profiles").queryParam(
    597                         USERSPACE_PARAM, "true")).type(
     656        RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles").queryParam(
     657                        REGISTRY_SPACE_PARAM, "private")).type(
    598658                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    599659                form);
     
    601661        assertEquals(1, getUserProfiles().size());
    602662        BaseDescription desc = response.getDescription();
    603         String profile = getResource()
    604                 .path("/registry/profiles/" + desc.getId() + "/xsd")
     663        String profile = this.getAuthenticatedResource(getResource()
     664                .path("/registry/profiles/" + desc.getId() + "/xsd"))
    605665                .accept(MediaType.TEXT_XML).get(String.class).trim();
    606666        assertTrue(profile
     
    611671    @Test
    612672    public void testPrivateComponentXsd() throws Exception {
     673       
     674        fillUpPublicItems();
     675       
    613676        FormDataMultiPart form = createFormData(RegistryTestHelper
    614677                .getComponentTestContent());
    615678        RegisterResponse response = getAuthenticatedResource(
    616679                getResource().path("/registry/components").queryParam(
    617                         USERSPACE_PARAM, "true")).type(
     680                        REGISTRY_SPACE_PARAM, "private")).type(
    618681                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    619682                form);
     
    621684        assertEquals(1, getUserComponents().size());
    622685        BaseDescription desc = response.getDescription();
    623         String profile = getResource()
    624                 .path("/registry/components/" + desc.getId() + "/xsd")
     686        String profile = this.getAuthenticatedResource(getResource()
     687                .path("/registry/components/" + desc.getId() + "/xsd"))
    625688                .accept(MediaType.TEXT_XML).get(String.class).trim();
    626689        assertTrue(profile
     
    631694    @Test
    632695    public void testDeleteRegisteredProfile() throws Exception {
    633         fillUp();
    634         List<ProfileDescription> profiles = getResource().path(
    635                 "/registry/profiles").get(PROFILE_LIST_GENERICTYPE);
     696       
     697        fillUpPublicItems();
     698       
     699        List<ProfileDescription> profiles = this.getAuthenticatedResource(getResource().path(
     700                "/registry/profiles")).get(PROFILE_LIST_GENERICTYPE);
    636701        assertEquals(2, profiles.size());
    637         CMDComponentSpec profile = getResource().path(
     702        CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
    638703                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    639                         + "profile1").get(CMDComponentSpec.class);
     704                        + "profile1")).get(CMDComponentSpec.class);
    640705        assertNotNull(profile);
    641706
     
    645710        assertEquals(200, response.getStatus());
    646711
    647         profiles = getResource().path("/registry/profiles").get(
     712        profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
    648713                PROFILE_LIST_GENERICTYPE);
    649714        assertEquals(1, profiles.size());
     
    654719        assertEquals(200, response.getStatus());
    655720
    656         profiles = getResource().path("/registry/profiles").get(
     721        profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
    657722                PROFILE_LIST_GENERICTYPE);
    658723        assertEquals(0, profiles.size());
     
    661726                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    662727                        + "profile1").delete(ClientResponse.class);
    663         assertEquals(200, response.getStatus());
     728        assertEquals(404, response.getStatus());
    664729    }
    665730
    666731    @Test
    667732    public void testManipulateRegisteredProfile() throws Exception {
    668         fillUp();
    669         List<ProfileDescription> profiles = getResource().path(
    670                 "/registry/profiles").get(PROFILE_LIST_GENERICTYPE);
     733       
     734        fillUpPublicItems();
     735       
     736        List<ProfileDescription> profiles = this.getAuthenticatedResource(getResource().path(
     737                "/registry/profiles")).get(PROFILE_LIST_GENERICTYPE);
    671738        assertEquals(2, profiles.size());
    672         CMDComponentSpec profile = getResource().path(
     739        CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path(
    673740                "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX
    674                         + "profile1").get(CMDComponentSpec.class);
     741                        + "profile1")).get(CMDComponentSpec.class);
    675742        assertNotNull(profile);
    676743
     
    684751        assertEquals(200, response.getStatus());
    685752
    686         profiles = getResource().path("/registry/profiles").get(
     753        profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get(
    687754                PROFILE_LIST_GENERICTYPE);
    688755        assertEquals(1, profiles.size());
     
    697764    @Test
    698765    public void testGetRegisteredComponentRawData() throws Exception {
    699         fillUp();
     766       
     767        fillUpPublicItems();
     768       
    700769        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    701         String component = getResource()
    702                 .path("/registry/components/" + id + "/xsd")
     770        String component = this.getAuthenticatedResource(getResource()
     771                .path("/registry/components/" + id + "/xsd"))
    703772                .accept(MediaType.TEXT_XML).get(String.class).trim();
    704773        assertTrue(component
     
    706775        assertTrue(component.endsWith("</xs:schema>"));
    707776
    708         component = getResource().path("/registry/components/" + id + "/xml")
     777        component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id + "/xml"))
    709778                .accept(MediaType.TEXT_XML).get(String.class).trim();
    710779        assertTrue(component
     
    714783
    715784        try {
    716             getResource()
     785            this.getAuthenticatedResource(getResource()
    717786                    .path("/registry/components/"
    718787                            + ComponentDescription.COMPONENT_PREFIX
    719                             + "component1/jpg").accept(MediaType.TEXT_XML)
     788                            + "component1/jpg")).accept(MediaType.TEXT_XML)
    720789                    .get(String.class);
    721790            fail("Should have thrown exception, unsopported path parameter");
     
    726795    @Test
    727796    public void testRegisterProfile() throws Exception {
     797       
     798        fillUpPublicItems();
     799       
    728800        FormDataMultiPart form = new FormDataMultiPart();
    729801        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
     
    742814                RegisterResponse.class, form);
    743815        assertTrue(response.isProfile());
    744         assertFalse(response.isInUserSpace());
     816        assertTrue(response.isInUserSpace());
    745817        ProfileDescription profileDesc = (ProfileDescription) response
    746818                .getDescription();
     
    762834    @Test
    763835    public void testPublishProfile() throws Exception {
    764         assertEquals("user registered profiles", 0, getUserProfiles().size());
    765         assertEquals("public registered profiles", 0, getPublicProfiles()
     836       
     837        fillUpPrivateItems();
     838        fillUpPublicItems();
     839       
     840        assertEquals("user registered profiles", 1, getUserProfiles().size());
     841        assertEquals("public registered profiles", 2, getPublicProfiles()
    766842                .size());
    767843        FormDataMultiPart form = createFormData(
    768844                RegistryTestHelper.getTestProfileContent(), "Unpublished");
    769         RegisterResponse response = getAuthenticatedResource(
    770                 getResource().path("/registry/profiles").queryParam(
    771                         USERSPACE_PARAM, "true")).type(
     845        RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
    772846                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    773847                form);
     
    775849        BaseDescription desc = response.getDescription();
    776850        assertEquals("Unpublished", desc.getDescription());
    777         assertEquals(1, getUserProfiles().size());
    778         assertEquals(0, getPublicProfiles().size());
     851        assertEquals(2, getUserProfiles().size());
     852        assertEquals(2, getPublicProfiles().size());
    779853        form = createFormData(
    780854                RegistryTestHelper.getTestProfileContent("publishedName"),
    781855                "Published");
    782         response = getAuthenticatedResource(
    783                 getResource().path(
     856        response = getAuthenticatedResource(getResource().path(
    784857                        "/registry/profiles/" + desc.getId() + "/publish"))
    785858                .type(MediaType.MULTIPART_FORM_DATA).post(
    786859                        RegisterResponse.class, form);
    787860
    788         assertEquals(0, getUserProfiles().size());
     861        assertEquals(1, getUserProfiles().size());
    789862        List<ProfileDescription> profiles = getPublicProfiles();
    790         assertEquals(1, profiles.size());
    791         ProfileDescription profileDescription = profiles.get(0);
     863        assertEquals(3, profiles.size());
     864        ProfileDescription profileDescription = profiles.get(2);
    792865        assertNotNull(profileDescription.getId());
    793866        assertEquals(desc.getId(), profileDescription.getId());
     
    801874    private CMDComponentSpec getPublicSpec(BaseDescription desc) {
    802875        if (desc.isProfile()) {
    803             return getResource().path("/registry/profiles/" + desc.getId())
     876            return this.getAuthenticatedResource(getResource().path("/registry/profiles/" + desc.getId()))
    804877                    .get(CMDComponentSpec.class);
    805878        } else {
    806             return getResource().path("/registry/components/" + desc.getId())
     879            return this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId()))
    807880                    .get(CMDComponentSpec.class);
    808881        }
     
    810883
    811884    @Test
    812     public void testPublishComponent() throws Exception {
    813         assertEquals(0, getUserComponents().size());
    814         assertEquals(0, getPublicComponents().size());
     885    public void testPublishRegisteredComponent() throws Exception {
     886       
     887        fillUpPrivateItems();
     888        fillUpPublicItems();
     889       
     890        assertEquals(1, getUserComponents().size());
     891        assertEquals(2, getPublicComponents().size());
     892       
    815893        FormDataMultiPart form = createFormData(
    816894                RegistryTestHelper.getComponentTestContent(), "Unpublished");
    817         RegisterResponse response = getAuthenticatedResource(
    818                 getResource().path("/registry/components").queryParam(
    819                         USERSPACE_PARAM, "true")).type(
     895        RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/components")).type(
    820896                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    821897                form);
     
    823899        BaseDescription desc = response.getDescription();
    824900        assertEquals("Unpublished", desc.getDescription());
    825         assertEquals(1, getUserComponents().size());
    826         assertEquals(0, getPublicComponents().size());
     901        assertEquals(2, getUserComponents().size());
     902        assertEquals(2, getPublicComponents().size());
    827903        form = createFormData(
    828904                RegistryTestHelper.getComponentTestContentAsStream("publishedName"),
    829905                "Published");
    830         response = getAuthenticatedResource(
    831                 getResource().path(
     906        response = getAuthenticatedResource(getResource().path(
    832907                        "/registry/components/" + desc.getId() + "/publish"))
    833908                .type(MediaType.MULTIPART_FORM_DATA).post(
    834909                        RegisterResponse.class, form);
    835910
    836         assertEquals(0, getUserComponents().size());
     911        assertEquals(1, getUserComponents().size());
    837912        List<ComponentDescription> components = getPublicComponents();
    838         assertEquals(1, components.size());
    839         ComponentDescription componentDescription = components.get(0);
     913        assertEquals(3, components.size());
     914        ComponentDescription componentDescription = components.get(2);
    840915        assertNotNull(componentDescription.getId());
    841916        assertEquals(desc.getId(), componentDescription.getId());
     
    848923    }
    849924
     925    // duplicates ("extendedly") testRegisterProfile, since you can pot only in user space, and then publish or move to group or so
    850926    @Test
    851927    public void testRegisterUserspaceProfile() throws Exception {
     928       
     929        fillUpPrivateItems();
     930        fillUpPublicItems();
     931       
    852932        List<ProfileDescription> profiles = getUserProfiles();
    853         assertEquals("user registered profiles", 0, profiles.size());
    854         assertEquals("public registered profiles", 0, getPublicProfiles()
     933        assertEquals("user registered profiles", 1, profiles.size());
     934        assertEquals("public registered profiles", 2, getPublicProfiles()
    855935                .size());
    856936        FormDataMultiPart form = createFormData(RegistryTestHelper
    857937                .getTestProfileContent());
    858         RegisterResponse response = getAuthenticatedResource(
    859                 getResource().path("/registry/profiles").queryParam(
    860                         USERSPACE_PARAM, "true")).type(
     938        RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
    861939                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    862940                form);
     
    875953        assertEquals(
    876954                "http://localhost:9998/registry/profiles/"
    877                         + profileDesc.getId() + "?userspace=true",
     955                        + profileDesc.getId(),
    878956                profileDesc.getHref());
    879957
    880958        profiles = getUserProfiles();
    881         assertEquals(1, profiles.size());
    882         assertEquals(0, getPublicProfiles().size());
     959        assertEquals(2, profiles.size());
     960        assertEquals(2, getPublicProfiles().size());
    883961
    884962        // Try to post unauthenticated
    885963        ClientResponse cResponse = getResource().path("/registry/profiles")
    886                 .queryParam(USERSPACE_PARAM, "true")
    887964                .type(MediaType.MULTIPART_FORM_DATA)
    888965                .post(ClientResponse.class, form);
    889966        assertEquals(401, cResponse.getStatus());
    890967
    891         // Try get from public registry
    892         cResponse = getResource()
    893                 .path("/registry/profiles/" + profileDesc.getId())
    894                 .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    895         // Should return 404 = not found
    896         assertEquals(404, cResponse.getStatus());
    897         CMDComponentSpec spec = getAuthenticatedResource(
    898                 getResource().path("/registry/profiles/" + profileDesc.getId())
    899                         .queryParam(USERSPACE_PARAM, "true")).accept(
     968       
     969       
     970        CMDComponentSpec spec = getAuthenticatedResource(getResource().path("/registry/profiles/" + profileDesc.getId())
     971                        .queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
    900972                MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
    901973        assertNotNull(spec);
    902974
    903         cResponse = getResource()
    904                 .path("/registry/profiles/" + profileDesc.getId() + "/xsd")
     975        cResponse = this.getAuthenticatedResource(getResource()
     976                .path("/registry/profiles/" + profileDesc.getId() + "/xsd"))
    905977                .accept(MediaType.TEXT_XML).get(ClientResponse.class);
    906978        assertEquals(200, cResponse.getStatus());
     
    908980        assertTrue(profile.length() > 0);
    909981
    910         profile = getAuthenticatedResource(
    911                 getResource().path(
     982        profile = getAuthenticatedResource(getResource().path(
    912983                        "/registry/profiles/" + profileDesc.getId() + "/xml"))
    913984                .accept(MediaType.TEXT_XML).get(String.class);
    914985        assertTrue(profile.length() > 0);
    915986
    916         cResponse = getAuthenticatedResource(
    917                 getResource().path("/registry/profiles/" + profileDesc.getId())
    918                         .queryParam(USERSPACE_PARAM, "true")).delete(
     987        cResponse = getAuthenticatedResource(getResource().path("/registry/profiles/" + profileDesc.getId())
     988                        .queryParam(REGISTRY_SPACE_PARAM, "private")).delete(
    919989                ClientResponse.class);
    920990        assertEquals(200, cResponse.getStatus());
    921991
    922992        profiles = getUserProfiles();
    923         assertEquals(0, profiles.size());
     993        assertEquals(1, profiles.size());
    924994    }
    925995
     
    9301000
    9311001    private List<ProfileDescription> getUserProfiles() {
    932         return getAuthenticatedResource(
    933                 getResource().path("/registry/profiles").queryParam(
    934                         USERSPACE_PARAM, "true")).accept(
     1002        return getAuthenticatedResource(getResource().path("/registry/profiles").queryParam(
     1003                        REGISTRY_SPACE_PARAM, "private")).accept(
    9351004                MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE);
    9361005    }
     
    9541023    @Test
    9551024    public void testRegisterWithUserComponents() throws Exception {
    956         ComponentRegistry userRegistry = componentRegistryFactory
    957                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    958                         DummyPrincipal.DUMMY_CREDENTIALS);
     1025        fillUpPrivateItems();
     1026       
     1027        // kid component, not public
    9591028        String content = "";
    9601029        content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     
    9661035        content += "</CMD_ComponentSpec>\n";
    9671036        ComponentDescription compDesc1 = RegistryTestHelper.addComponent(
    968                 userRegistry, "XXX1", content);
    969 
     1037                baseRegistry, "XXX1", content, false);
     1038
     1039        // a containing component, referring to the kid (which is not public, so the containing component cannot be registered
    9701040        content = "";
    9711041        content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     
    9821052                "/registry/components").type(MediaType.MULTIPART_FORM_DATA)
    9831053                .post(RegisterResponse.class, form);
    984         assertFalse(response.isRegistered());
    985         assertEquals(1, response.getErrors().size());
    986         assertEquals(
    987                 "referenced component cannot be found in the published components: "
    988                         + compDesc1.getName() + " (" + compDesc1.getId() + ")",
    989                 response.getErrors().get(0));
    990 
    991         response = getAuthenticatedResource(
    992                 getResource().path("/registry/components").queryParam(
    993                         USERSPACE_PARAM, "true")).type(
    994                 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    995                 form);
     1054        // we first alway register in a private space, so reference to a private component should work
    9961055        assertTrue(response.isRegistered());
    997         ComponentDescription comp2 = (ComponentDescription) response
    998                 .getDescription();
    999 
     1056
     1057
     1058        /// profiles ///
    10001059        content = "";
    10011060        content += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
     
    10031062        content += "    <Header/>\n";
    10041063        content += "    <CMD_Component name=\"ZZZ\" CardinalityMin=\"1\" CardinalityMax=\"unbounded\">\n";
    1005         content += "        <CMD_Component ComponentId=\"" + comp2.getId()
     1064        content += "        <CMD_Component ComponentId=\"" + compDesc1.getId()
    10061065                + "\" CardinalityMin=\"0\" CardinalityMax=\"99\">\n";
    10071066        content += "        </CMD_Component>\n";
     
    10131072                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    10141073                form);
    1015         assertFalse(response.isRegistered());
    1016         assertEquals(1, response.getErrors().size());
    1017         assertEquals(
    1018                 "referenced component cannot be found in the published components: "
    1019                         + comp2.getName() + " (" + comp2.getId() + ")",
    1020                 response.getErrors().get(0));
    1021 
    1022         response = getAuthenticatedResource(
    1023                 getResource().path("/registry/profiles").queryParam(
    1024                         USERSPACE_PARAM, "true")).type(
    1025                 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    1026                 form);
    10271074        assertTrue(response.isRegistered());
     1075
    10281076    }
    10291077
    10301078    @Test
    10311079    public void testRegisterUserspaceComponent() throws Exception {
     1080       
     1081        fillUpPrivateItems();
     1082       
    10321083        List<ComponentDescription> components = getUserComponents();
    1033         assertEquals("user registered components", 0, components.size());
     1084        assertEquals("user registered components", 1, components.size());
    10341085        assertEquals("public registered components", 0, getPublicComponents()
    10351086                .size());
     
    10371088                .getComponentTestContent());
    10381089
    1039         RegisterResponse response = getAuthenticatedResource(
    1040                 getResource().path("/registry/components").queryParam(
    1041                         USERSPACE_PARAM, "true")).type(
     1090        RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/components")).type(
    10421091                MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class,
    10431092                form);
     
    10571106        assertNotNull(desc.getRegistrationDate());
    10581107        String url = getResource().getUriBuilder().build().toString();
    1059         assertEquals(url + "registry/components/" + desc.getId()
    1060                 + "?userspace=true", desc.getHref());
     1108        assertEquals(url + "registry/components/" + desc.getId(), desc.getHref());
    10611109
    10621110        components = getUserComponents();
    1063         assertEquals(1, components.size());
     1111        assertEquals(2, components.size());
    10641112        assertEquals(0, getPublicComponents().size());
    10651113
    10661114        // Try to post unauthenticated
    10671115        ClientResponse cResponse = getResource().path("/registry/components")
    1068                 .queryParam(USERSPACE_PARAM, "true")
    10691116                .type(MediaType.MULTIPART_FORM_DATA)
    10701117                .post(ClientResponse.class, form);
    10711118        assertEquals(401, cResponse.getStatus());
    10721119
    1073         // Try to get from public registry
    1074         cResponse = getResource().path("/registry/components/" + desc.getId())
     1120        // Try to get
     1121        cResponse = this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId()))
    10751122                .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    1076         // Should return 404 = not found
    1077         assertEquals(404, cResponse.getStatus());
     1123       
     1124        assertEquals(200, cResponse.getStatus());
    10781125        CMDComponentSpec spec = getUserComponent(desc);
    10791126        assertNotNull(spec);
    10801127
    1081         cResponse = getResource()
    1082                 .path("/registry/components/" + desc.getId() + "/xsd")
     1128        cResponse = this.getAuthenticatedResource(getResource()
     1129                .path("/registry/components/" + desc.getId() + "/xsd"))
    10831130                .accept(MediaType.TEXT_XML).get(ClientResponse.class);
    10841131        assertEquals(200, cResponse.getStatus());
     
    10861133        assertTrue(result.length() > 0);
    10871134
    1088         result = getAuthenticatedResource(
    1089                 getResource().path(
     1135        result = getAuthenticatedResource(getResource().path(
    10901136                        "/registry/components/" + desc.getId() + "/xml"))
    10911137                .accept(MediaType.TEXT_XML).get(String.class);
    10921138        assertTrue(result.length() > 0);
    10931139
    1094         cResponse = getAuthenticatedResource(
    1095                 getResource().path("/registry/components/" + desc.getId())
    1096                         .queryParam(USERSPACE_PARAM, "true")).delete(
     1140        cResponse = getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())).delete(
    10971141                ClientResponse.class);
    10981142        assertEquals(200, cResponse.getStatus());
    10991143
    11001144        components = getUserComponents();
    1101         assertEquals(0, components.size());
    1102     }
    1103 
    1104     @Test
    1105     public void testCreateComponentWithRecursion() throws Exception {
     1145        assertEquals(1, components.size());
     1146    }
     1147//
     1148    @Test
     1149    public void testCreatePrivateComponentWithRecursion() throws Exception {
     1150       
     1151        fillUpPrivateItems();
    11061152        // Create new componet
    11071153        FormDataMultiPart form = createFormData(RegistryTestHelper
    11081154                .getComponentTestContent());
    1109         ClientResponse cResponse = getAuthenticatedResource(
    1110                 getResource().path("/registry/components").queryParam(
    1111                         USERSPACE_PARAM, "true")).type(
     1155        ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/components")).type(
    11121156                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    11131157        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    11401184                RegistryTestHelper.getComponentContentAsStream(compContent),
    11411185                "UPDATE DESCRIPTION!");
    1142         cResponse = getAuthenticatedResource(
    1143                 getResource().path(
    1144                         "/registry/components/" + desc.getId() + "/update")
    1145                         .queryParam(USERSPACE_PARAM, "true")).type(
     1186        cResponse = getAuthenticatedResource(getResource().path(
     1187                        "/registry/components/" + desc.getId() + "/update")).type(
    11461188                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    11471189        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    11591201
    11601202    @Test
    1161     public void testUpdateComponent() throws Exception {
     1203    public void testUpdatePrivateComponent() throws Exception {
     1204       
     1205        fillUpPrivateItems();
     1206       
    11621207        List<ComponentDescription> components = getUserComponents();
    1163         assertEquals("user registered components", 0, components.size());
     1208        assertEquals("user registered components", 1, components.size());
    11641209        assertEquals("public registered components", 0, getPublicComponents()
    11651210                .size());
    1166 
     1211       
     1212        // first, post a component to update
    11671213        FormDataMultiPart form = createFormData(RegistryTestHelper
    11681214                .getComponentTestContent());
    1169         ClientResponse cResponse = getAuthenticatedResource(
    1170                 getResource().path("/registry/components").queryParam(
    1171                         USERSPACE_PARAM, "true")).type(
     1215        ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/components")).type(
    11721216                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    11731217        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    11871231        assertEquals("Access", spec.getCMDComponent().getName());
    11881232        components = getUserComponents();
    1189         assertEquals(1, components.size());
     1233        assertEquals(2, components.size());
    11901234        assertEquals(0, getPublicComponents().size());
    11911235
    1192         // Now update
     1236        // second, now update
    11931237        form = createFormData(
    11941238                RegistryTestHelper.getComponentTestContentAsStream("TESTNAME"),
    11951239                "UPDATE DESCRIPTION!");
    1196         cResponse = getAuthenticatedResource(
    1197                 getResource().path(
     1240        cResponse = getAuthenticatedResource(getResource().path(
    11981241                        "/registry/components/" + desc.getId() + "/update")
    1199                         .queryParam(USERSPACE_PARAM, "true")).type(
     1242                        .queryParam(REGISTRY_SPACE_PARAM, "private")).type(
    12001243                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    12011244        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    12161259        assertEquals("TESTNAME", spec.getCMDComponent().getName());
    12171260        components = getUserComponents();
    1218         assertEquals(1, components.size());
     1261        assertEquals(2, components.size());
    12191262        assertEquals(0, getPublicComponents().size());
    12201263    }
    12211264
    12221265    @Test
    1223     public void testUpdateProfile() throws Exception {
     1266    public void testUpdatePrivateProfile() throws Exception {
     1267       
     1268        fillUpPrivateItems();
     1269       
    12241270        List<ProfileDescription> profiles = getUserProfiles();
    1225         assertEquals(0, profiles.size());
     1271        assertEquals(1, profiles.size());
    12261272        assertEquals(0, getPublicProfiles().size());
    12271273
    12281274        FormDataMultiPart form = createFormData(RegistryTestHelper
    12291275                .getTestProfileContent());
    1230         ClientResponse cResponse = getAuthenticatedResource(
    1231                 getResource().path("/registry/profiles").queryParam(
    1232                         USERSPACE_PARAM, "true")).type(
     1276        ClientResponse cResponse = getAuthenticatedResource(getResource().path("/registry/profiles")).type(
    12331277                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    12341278        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    12491293        assertEquals("Actor", spec.getCMDComponent().getName());
    12501294        profiles = getUserProfiles();
    1251         assertEquals(1, profiles.size());
     1295        assertEquals(2, profiles.size());
    12521296        assertEquals(0, getPublicComponents().size());
    12531297
     
    12561300                RegistryTestHelper.getTestProfileContent("TESTNAME"),
    12571301                "UPDATE DESCRIPTION!");
    1258         cResponse = getAuthenticatedResource(
    1259                 getResource().path(
    1260                         "/registry/profiles/" + desc.getId() + "/update")
    1261                         .queryParam(USERSPACE_PARAM, "true")).type(
     1302        cResponse = getAuthenticatedResource(getResource().path(
     1303                        "/registry/profiles/" + desc.getId() + "/update")).type(
    12621304                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    12631305        assertEquals(ClientResponse.Status.OK.getStatusCode(),
     
    12781320        assertEquals("TESTNAME", spec.getCMDComponent().getName());
    12791321        profiles = getUserProfiles();
    1280         assertEquals(1, profiles.size());
     1322        assertEquals(2, profiles.size());
    12811323        assertEquals(0, getPublicComponents().size());
    12821324    }
    12831325
    12841326    private CMDComponentSpec getUserComponent(ComponentDescription desc) {
    1285         return getAuthenticatedResource(
    1286                 getResource().path("/registry/components/" + desc.getId())
    1287                         .queryParam(USERSPACE_PARAM, "true")).accept(
     1327        return getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())
     1328                        .queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
    12881329                MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
    12891330    }
    12901331
    12911332    private CMDComponentSpec getUserProfile(ProfileDescription desc) {
    1292         return getAuthenticatedResource(
    1293                 getResource().path("/registry/profiles/" + desc.getId())
    1294                         .queryParam(USERSPACE_PARAM, "true")).accept(
     1333        return getAuthenticatedResource(getResource().path("/registry/profiles/" + desc.getId())
     1334                        .queryParam(REGISTRY_SPACE_PARAM, "private")).accept(
    12951335                MediaType.APPLICATION_XML).get(CMDComponentSpec.class);
    12961336    }
     
    13021342
    13031343    private List<ComponentDescription> getUserComponents() {
    1304         return getAuthenticatedResource(
    1305                 getResource().path("/registry/components").queryParam(
    1306                         USERSPACE_PARAM, "true")).accept(
     1344        return getAuthenticatedResource(getResource().path("/registry/components").queryParam(
     1345                        REGISTRY_SPACE_PARAM, "private")).accept(
    13071346                MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE);
    13081347    }
     
    13101349    @Test
    13111350    public void testRegisterComponent() throws Exception {
     1351       
     1352        fillUpPrivateItems();
     1353       
    13121354        FormDataMultiPart form = new FormDataMultiPart();
    13131355        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
     
    13261368        assertTrue(response.isRegistered());
    13271369        assertFalse(response.isProfile());
    1328         assertFalse(response.isInUserSpace());
     1370        assertTrue(response.isInUserSpace());
    13291371        ComponentDescription desc = (ComponentDescription) response
    13301372                .getDescription();
     
    13461388    @Test
    13471389    public void testRegisterComment() throws Exception {
     1390       
     1391        fillUpPublicItems();
     1392       
    13481393        FormDataMultiPart form = new FormDataMultiPart();
    13491394        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
    13501395                RegistryTestHelper.getCommentTestContent(),
    13511396                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1352         fillUp();
    13531397        String id = ProfileDescription.PROFILE_PREFIX + "profile1";
    13541398        CommentResponse response = getAuthenticatedResource(
     
    13711415    @Test
    13721416    public void testRegisterCommentToNonExistent() throws Exception {
     1417        fillUpPublicItems();
     1418       
    13731419        FormDataMultiPart form = new FormDataMultiPart();
    13741420        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
    13751421                RegistryTestHelper.getCommentTestContent(),
    13761422                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1377         fillUp();
    13781423        ClientResponse cResponse = getAuthenticatedResource(
    13791424                "/registry/profiles/clarin.eu:cr1:profile99/comments").type(
    13801425                MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    1381         assertEquals(500, cResponse.getStatus());
     1426        assertEquals(404, cResponse.getStatus());
    13821427    }
    13831428
    13841429    @Test
    13851430    public void testRegisterCommentUnauthenticated() throws Exception {
     1431        fillUpPublicItems();
     1432       
    13861433        FormDataMultiPart form = new FormDataMultiPart();
    13871434        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
    13881435                RegistryTestHelper.getCommentTestContent(),
    13891436                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1390         fillUp();
    13911437        ClientResponse cResponse = getResource()
    13921438                .path("/registry/profiles/clarin.eu:cr1:profile1/comments")
     
    13981444    @Test
    13991445    public void testRegisterProfileInvalidData() throws Exception {
     1446        fillUpPrivateItems();
    14001447        FormDataMultiPart form = new FormDataMultiPart();
    14011448        String notAValidProfile = "<CMD_ComponentSpec> </CMD_ComponentSpec>";
     
    14261473    @Test
    14271474    public void testRegisterInvalidProfile() throws Exception {
     1475        fillUpPrivateItems();
    14281476        FormDataMultiPart form = new FormDataMultiPart();
    14291477        String profileContent = "";
     
    14691517    public void testRegisterProfileInvalidDescriptionAndContent()
    14701518            throws Exception {
     1519        fillUpPrivateItems();
    14711520        FormDataMultiPart form = new FormDataMultiPart();
    14721521        String profileContent = "";
     
    14991548    @Test
    15001549    public void testRegisterLargeProfile() throws Exception {
     1550        //fillUpPrivateItems(); not necessary
    15011551        FormDataMultiPart form = new FormDataMultiPart();
    15021552        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
     
    15191569    @Test
    15201570    public void testRegisterComponentAsProfile() throws Exception {
     1571        //fillUpPrivateItems();; not necessary
    15211572        FormDataMultiPart form = new FormDataMultiPart();
    15221573        form.field(IComponentRegistryRestService.DATA_FORM_FIELD,
     
    16411692    @Test
    16421693    public void testGetDescription() throws Exception{
    1643         fillUp();
    1644         String id = ComponentDescription.COMPONENT_PREFIX + "component1";
     1694        fillUpPublicItems();
     1695        String id = ComponentDescription.COMPONENT_PREFIX + "component1";
    16451696        ComponentDescription component = getAuthenticatedResource(getResource().path("/registry/items/" + id)).accept(MediaType.APPLICATION_JSON).get(ComponentDescription.class);
    16461697        assertNotNull(component);
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java

    r4098 r5549  
    11package clarin.cmdi.componentregistry.rest;
    22
     3import clarin.cmdi.componentregistry.RegistrySpace;
    34import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
    45import clarin.cmdi.componentregistry.model.BaseDescription;
     
    2021
    2122import org.junit.Before;
    22 import org.junit.BeforeClass;
    2323import org.junit.Test;
    2424import org.slf4j.Logger;
     
    2727import org.springframework.jdbc.core.JdbcTemplate;
    2828
    29 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
     29import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM;
    3030import static org.junit.Assert.*;
    3131
     
    5858        List<Thread> ts = new ArrayList<Thread>();
    5959
    60         registerProfiles(ts, NR_OF_PROFILES, errors, false);
    61         registerProfiles(ts, NR_OF_PROFILES, errors, true);
    62 
    63         registerComponents(ts, NR_OF_COMPONENTS, errors, false);
    64         registerComponents(ts, NR_OF_COMPONENTS, errors, true);
     60        registerProfiles(ts, NR_OF_PROFILES, errors, RegistrySpace.PRIVATE);
     61        //a profile can be first registered (created) only in private space, and then moved.
     62        //registerProfiles(ts, NR_OF_PROFILES, errors, RegistrySpace.PUBLISHED);
     63
     64        registerComponents(ts, NR_OF_COMPONENTS, errors, RegistrySpace.PRIVATE);
     65        //a profile can be first registered (created) only in private space, and then moved.
     66        //registerComponents(ts, NR_OF_COMPONENTS, errors, RegistrySpace.PUBLISHED);
    6567        runAllThreads(ts);
    6668        if (errors.size() > 0) {
     
    7072            fail();
    7173        }
    72         assertProfiles(NR_OF_PROFILES, false);
    73         assertProfiles(NR_OF_PROFILES, true);
    74 
    75         assertComponents(NR_OF_COMPONENTS, false);
    76         assertComponents(NR_OF_COMPONENTS, true);
    77     }
    78 
    79     private void assertProfiles(int nrOfProfiles, boolean userSpace) {
     74        assertProfiles(NR_OF_PROFILES, RegistrySpace.PRIVATE);
     75        //assertProfiles(NR_OF_PROFILES, RegistrySpace.PUBLISHED);
     76
     77        assertComponents(NR_OF_COMPONENTS, RegistrySpace.PRIVATE);
     78        //assertComponents(NR_OF_COMPONENTS, RegistrySpace.PUBLISHED);
     79    }
     80
     81    private void assertProfiles(int nrOfProfiles, RegistrySpace registrySpace) {
    8082        List<ProfileDescription> response = getAuthenticatedResource(
    8183                getResource().path("/registry/profiles").queryParam(
    82                         USERSPACE_PARAM, "" + userSpace)).accept(
     84                        REGISTRY_SPACE_PARAM, registrySpace.name())).accept(
    8385                MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE);
    8486        Collections.sort(response, descriptionComparator);
     
    101103    };
    102104
    103     private void assertComponents(int nrOfComponents, boolean userSpace) {
     105    private void assertComponents(int nrOfComponents, RegistrySpace registrySpace) {
    104106        List<ComponentDescription> cResponse = getAuthenticatedResource(
    105107                getResource().path("/registry/components").queryParam(
    106                         USERSPACE_PARAM, "" + userSpace)).accept(
     108                        REGISTRY_SPACE_PARAM, registrySpace.name())).accept(
    107109                MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE);
    108110        Collections.sort(cResponse, descriptionComparator);
     
    128130
    129131    private void registerProfiles(List<Thread> ts, int size,
    130             final List<String> errors, boolean userSpace)
     132            final List<String> errors, RegistrySpace registrySpace)
    131133            throws InterruptedException {
    132134        for (int i = 0; i < size; i++) {
     
    134136            LOG.debug("Profile {} should be registered in {} and {}",
    135137                    new Object[] { i + 1000,
    136                             userSpace ? "user space" : "public space",
     138                            registrySpace.name(),
    137139                            shouldDelete ? "ALSO DELETED" : "not deleted" });
    138             Thread thread = createThread("/registry/profiles/", userSpace,
     140            Thread thread = createThread("/registry/profiles/", registrySpace,
    139141                    "Test Profile" + (i + 1000), shouldDelete,
    140142                    RegistryTestHelper.getTestProfileContent(), errors);
     
    144146
    145147    private void registerComponents(List<Thread> ts, int size,
    146             final List<String> errors, boolean userSpace)
     148            final List<String> errors, RegistrySpace registrySpace)
    147149            throws InterruptedException {
    148150        for (int i = 0; i < size; i++) {
     
    150152            LOG.debug("Component {} should be registered in {} and {}",
    151153                    new Object[] { i + 1000,
    152                             userSpace ? "user space" : "public space",
     154                            registrySpace.name(),
    153155                            shouldDelete ? "ALSO DELETED" : "not deleted" });
    154             Thread thread = createThread("/registry/components/", userSpace,
     156            Thread thread = createThread("/registry/components/", registrySpace,
    155157                    "Test Component" + (i + 1000), shouldDelete,
    156158                    RegistryTestHelper.getComponentTestContent(), errors);
     
    159161    }
    160162
    161     private Thread createThread(final String path, final boolean userSpace,
     163    private Thread createThread(final String path, final RegistrySpace registrySpace,
    162164            final String name, final boolean alsoDelete, InputStream content,
    163165            final List<String> errors) throws InterruptedException {
     
    176178                    // System.out.println("THREAD STARTED"+Thread.currentThread().getName());
    177179                    RegisterResponse registerResponse = getAuthenticatedResource(
    178                             getResource().path(path).queryParam(
    179                                     USERSPACE_PARAM, "" + userSpace)).type(
     180                            getResource().path(path)).type(
    180181                            MediaType.MULTIPART_FORM_DATA).post(
    181182                            RegisterResponse.class, form);
     
    188189                            + "] REGISTERING DESCRIPTION " + name + " "
    189190                            + registerResponse.getDescription().getId()
    190                             + (Boolean.valueOf(userSpace) ? " userspace" : "")
     191                            + registrySpace.name()
    191192                            + (alsoDelete ? " alsoDelete" : ""));
    192193                    if (alsoDelete) {
     
    197198                                + " "
    198199                                + registerResponse.getDescription().getId()
    199                                 + (Boolean.valueOf(userSpace) ? " userspace "
    200                                         : "")
     200                                + registrySpace.name()
    201201                                + (alsoDelete ? " alsoDelete" : ""));
    202202                        ClientResponse response = getAuthenticatedResource(
     
    205205                                                + registerResponse
    206206                                                        .getDescription()
    207                                                         .getId()).queryParam(
    208                                         USERSPACE_PARAM, "" + userSpace))
     207                                                        .getId()))
    209208                                .delete(ClientResponse.class);
    210209                        if (response.getStatus() != 200) {
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java

    r4550 r5549  
    44import clarin.cmdi.componentregistry.ComponentRegistry;
    55import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    6 import clarin.cmdi.componentregistry.ComponentStatus;
    7 import clarin.cmdi.componentregistry.MDMarshaller;
     6import clarin.cmdi.componentregistry.OwnerUser;
     7import clarin.cmdi.componentregistry.RegistrySpace;
     8import clarin.cmdi.componentregistry.UserUnauthorizedException;
    89import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    9 import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
    1010import clarin.cmdi.componentregistry.model.ComponentDescription;
    1111import clarin.cmdi.componentregistry.model.ProfileDescription;
    12 
     12import clarin.cmdi.componentregistry.model.RegistryUser;
    1313import java.io.ByteArrayInputStream;
    1414import java.io.InputStream;
     
    1717
    1818import org.junit.Before;
     19import org.junit.Ignore;
    1920import org.junit.Test;
    2021import org.springframework.beans.factory.annotation.Autowired;
    21 import org.springframework.jdbc.core.JdbcTemplate;
    22 
    23 import static org.junit.Assert.*;
     22
    2423
    2524/**
     
    3130
    3231    @Autowired
    33     private ComponentRegistryFactory componentRegistryFactory;
    34     private ComponentRegistry publicRegistry;
    35 
     32    private ComponentRegistryFactory componentRegistryFactory;
     33    @Autowired
     34    private ComponentRegistry testRegistry;
     35   
     36    private RegistryUser user;
     37   
     38   
    3639    @Before
    37     public void setUp() throws TransformerException {
    38         publicRegistry = componentRegistryFactory.getPublicRegistry();
    39     }
    40 
    41     @Test
    42     public void testValidateSucces() {
    43         MDValidator validator = getValidProfileValidator();
    44         assertTrue(validator.validate());
    45     }
    46 
    47     @Test
    48     public void testValidateIllegalComponentAttributeName() {
     40    @Override
     41    public void setUp() throws TransformerException, UserUnauthorizedException {
     42        testRegistry = componentRegistryFactory.getPublicRegistry();
     43        user = componentRegistryFactory.getOrCreateUser(DummyPrincipal.DUMMY_CREDENTIALS);
     44    }
     45   
     46   
     47
     48    @Test
     49    public void testValidateSucces() throws UserUnauthorizedException{
     50        MDValidator validator = this.getValidProfileValidator();
     51        boolean result = validator.validate();
     52        assertTrue(result);
     53    }
     54
     55    @Test
     56    public void testValidateIllegalComponentAttributeName() throws UserUnauthorizedException{
    4957        String profileContent = "";
    5058        profileContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
     
    93101
    94102        ProfileDescription desc = ProfileDescription.createNewDescription();
    95         MDValidator validator = new MDValidator(input, desc, publicRegistry,
    96                 null, publicRegistry, marshaller);
     103       
     104        MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
    97105        assertFalse(validator.validate());
    98106        assertEquals(4, validator.getErrorMessages().size());
     
    115123
    116124        ProfileDescription desc = ProfileDescription.createNewDescription();
    117         MDValidator validator = new MDValidator(input, desc, publicRegistry,
    118                 null, publicRegistry, marshaller);
    119         assertFalse(validator.validate());
    120         assertTrue(validator
    121                 .getErrorMessages()
    122                 .get(0)
    123                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    124     }
    125 
    126     @Test
     125        desc.setPublic(true);
     126        MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
     127        assertFalse(validator.validate());
     128        assertTrue(validator
     129                .getErrorMessages()
     130                .get(0)
     131                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     132        //
     133    }
     134
     135    @Test 
    127136    public void testValidateComponentIdNotRegistered() throws Exception {
    128137        String id1 = "component1";
     
    144153        profileContent += "</CMD_ComponentSpec>";
    145154
    146         // Ids not registered will return two errors. One for each id
    147         ProfileDescription desc = ProfileDescription.createNewDescription();
     155        // Ids not registered. will return 2 errors: one per each id.
     156        ProfileDescription desc = ProfileDescription.createNewDescription();
     157        desc.setPublic(true);
    148158        MDValidator validator = new MDValidator(new ByteArrayInputStream(
    149                 profileContent.getBytes()), desc, publicRegistry, null,
    150                 publicRegistry, marshaller);
    151         assertFalse(validator.validate());
    152         assertEquals(2, validator.getErrorMessages().size());
    153         assertTrue(validator
    154                 .getErrorMessages()
    155                 .get(0)
    156                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    157         assertTrue(validator
    158                 .getErrorMessages()
    159                 .get(1)
    160                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    161 
    162         // id1 will be added and therefore only id2 is not registered
    163         RegistryTestHelper.addComponent(publicRegistry, id1);
     159                profileContent.getBytes()), desc, testRegistry, marshaller);
     160        assertFalse(validator.validate());
     161        assertEquals(1, validator.getErrorMessages().size());
     162        assertTrue(validator
     163                .getErrorMessages()
     164                .get(0)
     165                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     166       
     167
     168        // id1 will be added as public and therefore only id2 is not registered
     169        RegistryTestHelper.addComponent(testRegistry, id1, true);
    164170        validator = new MDValidator(new ByteArrayInputStream(
    165                 profileContent.getBytes()), desc, publicRegistry, null,
    166                 publicRegistry, marshaller);
     171                profileContent.getBytes()), desc, testRegistry
     172                , marshaller);
    167173        assertFalse(validator.validate());
    168174        assertEquals(1, validator.getErrorMessages().size());
     
    170176                .getErrorMessages()
    171177                .get(0)
    172                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    173 
    174         // id2 is added, no more errors shoud be return
    175         RegistryTestHelper.addComponent(publicRegistry, id2);
     178                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     179
     180        // id2 is added as public, no more errors shoud be return
     181        RegistryTestHelper.addComponent(testRegistry, id2, true);
    176182        validator = new MDValidator(new ByteArrayInputStream(
    177                 profileContent.getBytes()), desc, publicRegistry, null,
    178                 publicRegistry, marshaller);
     183                profileContent.getBytes()), desc, testRegistry, marshaller);
    179184        assertTrue("component is registered should be valid now",
    180185                validator.validate());
     
    183188
    184189    @Test
    185     public void testValidateUserRegistry() throws Exception {
     190    public void testValidateBaseAndUserRegistry() throws Exception {
    186191        String id1 = "component1";
    187192        String id2 = "component2";
    188         ComponentRegistry userRegistry = componentRegistryFactory
    189                 .getComponentRegistry(ComponentStatus.PRIVATE, null,
    190                         DummyPrincipal.DUMMY_CREDENTIALS);
    191193
    192194        String profileContent = "";
     
    205207        profileContent += "</CMD_ComponentSpec>";
    206208
     209        // Public Registry
    207210        ProfileDescription desc = ProfileDescription.createNewDescription();
    208211        MDValidator validator = new MDValidator(new ByteArrayInputStream(
    209                 profileContent.getBytes()), desc, userRegistry, userRegistry,
    210                 publicRegistry, marshaller);
    211         assertFalse(validator.validate());
    212         assertEquals(2, validator.getErrorMessages().size());
     212                profileContent.getBytes()), desc, testRegistry, marshaller);
     213        assertFalse(validator.validate());
     214        assertEquals(1, validator.getErrorMessages().size()); // the exception is thrown and propagated on the first non-registered component
    213215        assertTrue(validator.getErrorMessages().get(0)
    214216                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
    215         assertTrue(validator.getErrorMessages().get(1)
    216                 .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
    217 
    218         RegistryTestHelper.addComponent(userRegistry, id1);
    219         RegistryTestHelper.addComponent(publicRegistry, id2);
     217       
     218       
     219        // registering publically the first component
     220        RegistryTestHelper.addComponent(testRegistry, id1, true);
     221        validator = new MDValidator(new ByteArrayInputStream(
     222                profileContent.getBytes()), desc, testRegistry, marshaller);
     223        assertFalse(validator.validate());
     224        assertEquals(1, validator.getErrorMessages().size()); // the exception is thrown on the second non-registered component
     225        assertTrue(validator.getErrorMessages().get(0)
     226                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     227       
     228       
     229       
     230        RegistryTestHelper.addComponent(testRegistry, id2, false);
    220231        validator = new MDValidator(new ByteArrayInputStream(
    221                 profileContent.getBytes()), desc, publicRegistry, null,
    222                 publicRegistry, marshaller);
     232                profileContent.getBytes()), desc, testRegistry, marshaller);
    223233        assertFalse(validator.validate());
    224234        assertEquals(1, validator.getErrorMessages().size());
     
    226236                .getErrorMessages()
    227237                .get(0)
    228                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    229 
     238                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR));
     239       
     240       
     241        // make it user registry
     242        testRegistry.setRegistryOwner(new OwnerUser(user.getId()));
     243        testRegistry.setRegistrySpace(RegistrySpace.PRIVATE);       
     244       
     245       
    230246        validator = new MDValidator(new ByteArrayInputStream(
    231                 profileContent.getBytes()), desc, userRegistry, userRegistry,
    232                 publicRegistry, marshaller);
    233         assertTrue(validator.validate());
     247                profileContent.getBytes()), desc, testRegistry,  marshaller);
     248        Boolean result =validator.validate();
     249        assertTrue(result);
    234250        assertEquals(0, validator.getErrorMessages().size());
    235251    }
     
    254270        ComponentDescription desc = ComponentDescription.createNewDescription();
    255271        MDValidator validator = new MDValidator(new ByteArrayInputStream(
    256                 content.getBytes()), desc, publicRegistry, null,
    257                 publicRegistry, marshaller);
     272                content.getBytes()), desc, testRegistry, marshaller);
    258273        assertFalse(validator.validate());
    259274        assertEquals(1, validator.getErrorMessages().size());
     
    261276                .getErrorMessages()
    262277                .get(0)
    263                 .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    264 
    265         RegistryTestHelper.addComponent(publicRegistry, id1);
     278                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     279
     280        RegistryTestHelper.addComponent(testRegistry, id1, true);
    266281        validator = new MDValidator(
    267                 new ByteArrayInputStream(content.getBytes()), desc,
    268                 publicRegistry, null, publicRegistry, marshaller);
     282                new ByteArrayInputStream(content.getBytes()), desc,testRegistry, marshaller);
    269283        assertTrue(validator.validate());
    270284        assertEquals(0, validator.getErrorMessages().size());
     
    280294
    281295        ProfileDescription desc = ProfileDescription.createNewDescription();
    282         MDValidator validator = new MDValidator(input, desc, publicRegistry,
    283                 null, publicRegistry, marshaller);
     296        MDValidator validator = new MDValidator(input, desc, testRegistry,marshaller);
    284297
    285298        // Spec is created during validation, before it should be null
     
    309322        InputStream input = new ByteArrayInputStream(profileContent.getBytes());
    310323        ProfileDescription desc = ProfileDescription.createNewDescription();
    311         MDValidator validator = new MDValidator(input, desc, publicRegistry,
    312                 null, publicRegistry, marshaller);
     324        desc.setPublic(true);
     325        desc.setName("test_name");
     326        MDValidator validator = new MDValidator(input, desc, testRegistry, marshaller);
    313327        return validator;
    314328    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java

    r4098 r5549  
    1616import clarin.cmdi.componentregistry.ComponentRegistry;
    1717import clarin.cmdi.componentregistry.DatesHelper;
     18import clarin.cmdi.componentregistry.ItemNotFoundException;
    1819import clarin.cmdi.componentregistry.MDMarshaller;
     20import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1921import clarin.cmdi.componentregistry.components.CMDComponentSpec;
    2022import clarin.cmdi.componentregistry.model.Comment;
     
    2729import java.io.InputStreamReader;
    2830
    29 import javax.xml.transform.TransformerException;
    30 
    31 import org.junit.Before;
    32 import org.junit.BeforeClass;
    3331import org.springframework.beans.factory.annotation.Autowired;
    3432
     
    4644    }
    4745
    48     public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id) throws ParseException, JAXBException {
    49         return addComponent(testRegistry, id, getComponentTestContent());
    50     }
    51 
    52     public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, String content) throws ParseException,
     46    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException {
     47        return addComponent(testRegistry, id, getComponentTestContent(), isPublic);
     48    }
     49
     50    public static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
    5351            JAXBException, UnsupportedEncodingException {
    54         return addComponent(testRegistry, id, new ByteArrayInputStream(content.getBytes("UTF-8")));
    55     }
    56 
    57     private static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, InputStream content) throws ParseException,
     52        return addComponent(testRegistry, id, new ByteArrayInputStream(content.getBytes("UTF-8")), isPublic);
     53    }
     54
     55    private static ComponentDescription addComponent(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
    5856            JAXBException {
    5957        ComponentDescription desc = ComponentDescription.createNewDescription();
    6058        desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
    61         desc.setUserId(DummyPrincipal.DUMMY_CREDENTIALS.getPrincipalName());
     59        desc.setUserId(DummyPrincipal.DUMMY_PRINCIPAL.getName());
    6260        desc.setName(id);
    6361        desc.setDescription("Test Description");
    6462        desc.setId(ComponentDescription.COMPONENT_PREFIX + id);
    6563        desc.setHref("link:" + desc.getId());
     64        desc.setPublic(isPublic);
    6665        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
    6766        testRegistry.register(desc, spec);
     
    104103    }
    105104
    106     public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id) throws ParseException, JAXBException {
    107         return addProfile(testRegistry, id, RegistryTestHelper.getTestProfileContent());
    108     }
    109 
    110     public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, String content) throws ParseException,
    111             JAXBException {
    112         return addProfile(testRegistry, id, new ByteArrayInputStream(content.getBytes()));
    113     }
    114 
    115     private static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, InputStream content) throws ParseException,
    116             JAXBException {
     105    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, boolean isPublic) throws ParseException, JAXBException, ItemNotFoundException {
     106        return addProfile(testRegistry, id, RegistryTestHelper.getTestProfileContent(), isPublic);
     107    }
     108
     109    public static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, String content, boolean isPublic) throws ParseException,
     110            JAXBException, ItemNotFoundException {
     111        return addProfile(testRegistry, id, new ByteArrayInputStream(content.getBytes()), isPublic);
     112    }
     113
     114    private static ProfileDescription addProfile(ComponentRegistry testRegistry, String id, InputStream content, boolean isPublic) throws ParseException,
     115            JAXBException, ItemNotFoundException {
    117116        ProfileDescription desc = ProfileDescription.createNewDescription();
    118117        desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName());
     
    122121        desc.setId(ProfileDescription.PROFILE_PREFIX + id);
    123122        desc.setHref("link:" + ProfileDescription.PROFILE_PREFIX + id);
     123        desc.setPublic(isPublic);
    124124        CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema());
    125125        testRegistry.register(desc, spec);
     
    216216    }
    217217
    218     public static Comment addComment(ComponentRegistry testRegistry, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException {
     218    public static Comment addComment(ComponentRegistry testRegistry, String id, String descriptionId, String principal) throws ParseException, JAXBException, ComponentRegistryException, ItemNotFoundException,UserUnauthorizedException {
    219219        return addComment(testRegistry, RegistryTestHelper.getTestCommentContent(id, descriptionId), principal);
    220220    }
     
    222222    private static Comment addComment(ComponentRegistry testRegistry, InputStream content, String principal) throws ParseException,
    223223            JAXBException,
    224             ComponentRegistryException {
     224            ComponentRegistryException, ItemNotFoundException,UserUnauthorizedException {
    225225        Comment spec = marshaller.unmarshal(Comment.class, content, null);
    226226        testRegistry.registerComment(spec, principal);
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rss/PrintXmlFromRssRunner.java

    r4098 r5549  
    55import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    66import clarin.cmdi.componentregistry.DatesHelper;
     7import clarin.cmdi.componentregistry.ItemNotFoundException;
    78import clarin.cmdi.componentregistry.MDMarshaller;
     9import clarin.cmdi.componentregistry.UserUnauthorizedException;
    810import clarin.cmdi.componentregistry.impl.ComponentUtils;
    911import clarin.cmdi.componentregistry.model.BaseDescription;
     
    2022
    2123import javax.xml.bind.JAXBException;
    22 import javax.xml.transform.TransformerException;
    23 
    24 import org.junit.BeforeClass;
    2524import org.springframework.beans.factory.annotation.Autowired;
    2625import org.springframework.context.ApplicationContext;
     
    9392     * input: sort of rss -- profiles, or comopnents, or comments (see below the prompt string)
    9493     */
    95     public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException {
     94    public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException, UserUnauthorizedException, ItemNotFoundException {
    9695
    9796        System.out.println("Type 1 or 2, or 3, or 4, \n "
     
    137136                System.exit(1);
    138137            }
    139             final List<Comment> comments = (kind == 3) ? registry.getCommentsInProfile(buffer, null) : registry.getCommentsInComponent(buffer, null);
    140             final String name = (kind == 3) ? registry.getProfileDescription(buffer).getName() : registry.getComponentDescription(buffer).getName();
     138            final List<Comment> comments = (kind == 3) ? registry.getCommentsInProfile(buffer) : registry.getCommentsInComponent(buffer);
     139            final String name = (kind == 3) ? registry.getProfileDescriptionAccessControlled(buffer).getName() : registry.getComponentDescriptionAccessControlled(buffer).getName();
    141140            rss = makeRssForComments(comments, kind, baseUri, 10, buffer, name);
    142141
Note: See TracChangeset for help on using the changeset viewer.