Changeset 5549
- Timestamp:
- 08/11/14 16:07:55 (10 years ago)
- Location:
- ComponentRegistry/trunk/ComponentRegistry
- Files:
-
- 9 added
- 49 edited
Legend:
- Unmodified
- Added
- Removed
-
ComponentRegistry/trunk/ComponentRegistry/nbactions.xml
r2531 r5549 35 35 </properties> 36 36 </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> 37 51 </actions> -
ComponentRegistry/trunk/ComponentRegistry/pom.xml
r4847 r5549 31 31 <flexDebug>0</flexDebug> 32 32 <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> 34 34 <jackson.version>1.9.13</jackson.version> 35 35 <jersey.version>1.17.1</jersey.version> -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistry.java
r4098 r5549 23 23 public static final String PUBLIC_NAME = "Public Registry"; 24 24 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); 25 39 /** 26 40 * @return List of component descriptions ordered by name ascending 27 41 * @throws ComponentRegistryException 28 42 */ 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 41 49 /** 42 50 * … … 44 52 * @throws ComponentRegistryException 45 53 */ 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 54 56 55 57 /** … … 65 67 * @throws ComponentRegistryException 66 68 */ 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; 72 76 73 77 CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException; 74 75 78 /** 76 79 * … … 84 87 * @return -1 if comment could not be registered 85 88 */ 86 int registerComment(Comment comment, String userId) throws ComponentRegistryException ;89 int registerComment(Comment comment, String userId) throws ComponentRegistryException, ItemNotFoundException, UserUnauthorizedException; 87 90 88 91 /** … … 90 93 * @return -1 if component could not be updated 91 94 */ 92 int update(BaseDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate);95 int update(BaseDescription description, CMDComponentSpec spec, boolean forceUpdate) throws UserUnauthorizedException, ItemNotFoundException; 93 96 94 97 /** … … 97 100 * current (private) workspace to public workspace. 98 101 */ 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 113 115 * @throws IOException 114 116 * @throws UserUnauthorizedException … … 116 118 * @throws DeleteFailedException 117 119 */ 118 void deleteMDProfile(String profileId , Principal principal) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException;120 void deleteMDProfile(String profileId) throws IOException, UserUnauthorizedException, ComponentRegistryException, DeleteFailedException, ItemNotFoundException; 119 121 120 122 /** … … 130 132 * @throws DeleteFailedException 131 133 */ 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; 134 136 135 137 /** … … 149 151 List<ProfileDescription> getUsageInProfiles(String componentId) throws ComponentRegistryException; 150 152 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 160 154 161 155 /** … … 168 162 * @return List of profile descriptions ordered by name ascending 169 163 */ 170 List<ProfileDescription> getDeletedProfileDescriptions() ;164 List<ProfileDescription> getDeletedProfileDescriptions()throws ComponentRegistryException; 171 165 172 166 /** … … 174 168 * @return List of component descriptions ordered by name ascending 175 169 */ 176 List<ComponentDescription> getDeletedComponentDescriptions() ;170 List<ComponentDescription> getDeletedComponentDescriptions() throws ComponentRegistryException; 177 171 178 172 /** … … 182 176 * @throws ComponentRegistryException 183 177 */ 184 List<Comment> getCommentsInProfile(String profileId , Principal principal) throws ComponentRegistryException;178 List<Comment> getCommentsInProfile(String profileId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException; 185 179 186 180 /** … … 191 185 * @throws ComponentRegistryException 192 186 */ 193 Comment getSpecifiedCommentInProfile(String profileId, String commentId , Principal principal) throws ComponentRegistryException;187 Comment getSpecifiedCommentInProfile(String profileId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException; 194 188 195 189 /** … … 199 193 * @throws ComponentRegistryException 200 194 */ 201 List<Comment> getCommentsInComponent(String componentId , Principal principal) throws ComponentRegistryException;195 List<Comment> getCommentsInComponent(String componentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException; 202 196 203 197 /** … … 208 202 * @throws ComponentRegistryException 209 203 */ 210 Comment getSpecifiedCommentInComponent(String componentId, String commentId , Principal principal) throws ComponentRegistryException;204 Comment getSpecifiedCommentInComponent(String componentId, String commentId) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException; 211 205 212 206 /** … … 219 213 * @throws DeleteFailedException 220 214 */ 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; 223 217 224 218 /** … … 239 233 */ 240 234 List<String> getAllNonDeletedComponentIds(); 235 236 Boolean isItemPublic(String id) throws ItemNotFoundException; 237 241 238 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentRegistryFactory.java
r1993 r5549 23 23 * @return 24 24 */ 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; 28 26 29 27 ComponentRegistry getPublicRegistry(); 28 29 ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, Owner owner); 30 31 ComponentRegistry getBaseRegistry(UserCredentials credentials); 30 32 31 33 RegistryUser getOrCreateUser(UserCredentials credentials); -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/ComponentStatus.java
r3035 r5549 7 7 public enum ComponentStatus { 8 8 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 40 16 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/Configuration.java
r3088 r5549 74 74 } 75 75 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 76 84 public void setAdminUsers(Collection<String> adminUsers) { 77 85 LOG.debug("Setting adminUsers to {}", Arrays.toString(adminUsers.toArray())); 78 86 this.adminUsers = adminUsers; 79 87 } 80 88 89 81 90 /** 82 91 * -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java
r4098 r5549 29 29 import clarin.cmdi.componentregistry.ComponentRegistryException; 30 30 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 31 import clarin.cmdi.componentregistry.ComponentStatus;32 31 import clarin.cmdi.componentregistry.MDMarshaller; 32 import clarin.cmdi.componentregistry.RegistrySpace; 33 import clarin.cmdi.componentregistry.UserUnauthorizedException; 33 34 import clarin.cmdi.componentregistry.impl.database.AdminRegistry; 34 35 import clarin.cmdi.componentregistry.model.BaseDescription; … … 43 44 private final static Logger LOG = LoggerFactory.getLogger(AdminHomePage.class); 44 45 private final CMDItemInfo info; 45 private finalLinkTree tree;46 private LinkTree tree; 46 47 private transient AdminRegistry adminRegistry = new AdminRegistry(); 47 48 @SpringBean(name = "componentRegistryFactory") … … 53 54 54 55 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 }; 96 96 form.add(deleteButton); 97 97 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 } 185 190 } 186 191 187 192 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 }); 210 212 } 211 213 212 214 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; 237 238 } 238 239 239 240 private class ItemEditForm extends Form<CMDItemInfo> { 240 241 241 242 243 244 245 246 247 248 249 250 251 252 253 } 254 255 private TreeModel createDBTreeModel() throws ComponentRegistryException {256 257 258 259 260 261 262 263 264 265 266 267 268 269 } 270 271 private void add(DefaultMutableTreeNode parent, ComponentRegistry registry) throws ComponentRegistryException {272 273 274 add(componentsNode, registry.getComponentDescriptions(), false, registry.getStatus());275 276 277 278 add(profilesNode, registry.getProfileDescriptions(), false, registry.getStatus());279 280 281 282 283 284 add(deletedCompNode, deletedComponentDescriptions, true, registry.getStatus());285 286 287 288 289 add(deletedProfNode, deletedProfileDescriptions, true, registry.getStatus());290 } 291 292 private void add(DefaultMutableTreeNode parent, List<? extends BaseDescription> descs, boolean isDeleted, ComponentStatus status) {293 294 DefaultMutableTreeNode child = new DefaultMutableTreeNode(new DisplayDataNode(desc.getName(), isDeleted, desc, status));295 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 } 297 298 } 298 299 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/CMDItemInfo.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.frontend; 2 2 3 import clarin.cmdi.componentregistry.ComponentStatus;4 3 import java.io.Serializable; 5 4 6 5 import clarin.cmdi.componentregistry.MDMarshaller; 6 import clarin.cmdi.componentregistry.RegistrySpace; 7 7 import clarin.cmdi.componentregistry.model.BaseDescription; 8 8 … … 99 99 100 100 101 public ComponentStatus getStatus() {102 return displayNode.getS tatus();101 public RegistrySpace getSpace() { 102 return displayNode.getSpace(); 103 103 } 104 104 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/DisplayDataNode.java
r4098 r5549 2 2 3 3 import clarin.cmdi.componentregistry.ComponentStatus; 4 import clarin.cmdi.componentregistry.RegistrySpace; 4 5 import java.io.Serializable; 5 6 … … 12 13 private final boolean isDeleted; 13 14 private BaseDescription desc; 14 private final ComponentStatus status;15 private final RegistrySpace space; 15 16 16 17 public DisplayDataNode(String name, boolean isDeleted) { 17 18 // TODO: what is sensible default status? 18 this(name, isDeleted, null, ComponentStatus.PRIVATE);19 this(name, isDeleted, null, RegistrySpace.PRIVATE); 19 20 } 20 21 21 public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, ComponentStatus status) {22 public DisplayDataNode(String name, boolean isDeleted, BaseDescription desc, RegistrySpace space) { 22 23 this.name = name; 23 24 this.isDeleted = isDeleted; 24 25 this.desc = desc; 25 this.s tatus = status;26 this.space = space; 26 27 } 27 28 … … 44 45 } 45 46 46 public ComponentStatus getStatus() {47 return s tatus;47 public RegistrySpace getSpace() { 48 return space; 48 49 } 49 50 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/StatisticsPage.java
r4550 r5549 14 14 import clarin.cmdi.componentregistry.ComponentRegistryException; 15 15 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 16 import clarin.cmdi.componentregistry.RegistrySpace; 17 import clarin.cmdi.componentregistry.UserUnauthorizedException; 16 18 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 17 19 import clarin.cmdi.componentregistry.components.CMDComponentType; … … 40 42 } 41 43 42 public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException {44 public StatisticsPage(final PageParameters pageParameters) throws IOException, ComponentRegistryException, UserUnauthorizedException { 43 45 super(pageParameters); 44 ComponentRegistry registry = componentRegistryFactory.get PublicRegistry();46 ComponentRegistry registry = componentRegistryFactory.getComponentRegistry(RegistrySpace.PUBLISHED, null, null, null); 45 47 addLinks(); 46 48 displayStatistics(registry); 47 49 } 48 50 49 private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException {51 private void displayStatistics(ComponentRegistry registry) throws ComponentRegistryException, UserUnauthorizedException { 50 52 List<ProfileDescription> profileList = registry.getProfileDescriptions(); 51 53 RepeatingView repeating = new RepeatingView("repeating"); -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentRegistryImplBase.java
r4550 r5549 14 14 import clarin.cmdi.componentregistry.ComponentRegistry; 15 15 import clarin.cmdi.componentregistry.ComponentRegistryException; 16 import clarin.cmdi.componentregistry. DeleteFailedException;16 import clarin.cmdi.componentregistry.ItemNotFoundException; 17 17 import clarin.cmdi.componentregistry.MDMarshaller; 18 import clarin.cmdi.componentregistry.UserUnauthorizedException; 18 19 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 19 import clarin.cmdi.componentregistry.components.CMDComponentType;20 20 import clarin.cmdi.componentregistry.components.CMDComponentSpec.Header; 21 21 import clarin.cmdi.componentregistry.model.BaseDescription; 22 import clarin.cmdi.componentregistry.model.ComponentDescription;23 22 import clarin.cmdi.componentregistry.model.ProfileDescription; 24 23 … … 33 32 protected abstract MDMarshaller getMarshaller(); 34 33 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 63 35 64 36 /** … … 70 42 @Override 71 43 public List<ProfileDescription> getProfileDescriptionsForMetadaEditor() throws ComponentRegistryException { 72 44 // TODO: Below can also be done by accepting and passing a parameter in the ProfileDescriptionDaoImpl, should have better performance 73 45 74 46 // Get all profile descriptions … … 77 49 ArrayList<ProfileDescription> descriptions = new ArrayList<ProfileDescription>(); 78 50 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) { 82 58 } 59 83 60 } 84 61 // Return filtered list … … 102 79 } 103 80 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 122 84 123 85 protected void writeXsd(CMDComponentSpec expandedSpec, OutputStream outputStream) { … … 135 97 } 136 98 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 - throw143 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 -> throw154 throw new DeleteFailedException("Component is still in use by one or more other components. Request component usage for details.");155 }156 }157 }158 99 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/ComponentUtils.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.impl; 2 2 3 import clarin.cmdi.componentregistry.ComponentRegistryException; 3 4 import java.text.ParseException; 4 5 import java.util.ArrayList; … … 11 12 import org.springframework.beans.BeanUtils; 12 13 13 import clarin.cmdi.componentregistry.DatesHelper;14 14 import clarin.cmdi.componentregistry.model.BaseDescription; 15 15 import clarin.cmdi.componentregistry.model.ComponentDescription; … … 18 18 /** 19 19 * Utilities for working with {@link BaseDescription}s 20 * 20 * 21 21 * @author george.georgovassilis@mpi.nl 22 * 22 * 23 23 */ 24 24 public class ComponentUtils { 25 25 26 26 public static boolean isProfileId(String componentId) { 27 27 return ("" + componentId).startsWith(ProfileDescription.PROFILE_PREFIX); 28 28 } 29 29 30 30 public static boolean isComponentId(String componentId) { 31 32 31 return ("" + componentId) 32 .startsWith(ComponentDescription.COMPONENT_PREFIX); 33 33 } 34 34 35 35 public static void copyPropertiesFrom(BaseDescription from, BaseDescription to) { 36 36 BeanUtils.copyProperties(from, to); 37 37 } 38 38 39 39 public static Date getDate(String registrationDate) throws ParseException { 40 41 new String[] {DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT42 .getPattern()});40 return DateUtils.parseDate(registrationDate, 41 new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT 42 .getPattern()}); 43 43 } 44 44 45 45 public static String createPublicHref(String href) { 46 47 48 49 50 51 52 53 54 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; 55 55 } 56 57 56 /** 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() 60 58 * } 61 59 */ 62 60 public static final Comparator<? super BaseDescription> COMPARE_ON_NAME = new Comparator<BaseDescription>() { 63 64 65 66 67 68 69 70 71 72 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 } 74 72 }; 75 73 /** … … 78 76 */ 79 77 public static final Comparator<? super BaseDescription> COMPARE_ON_DATE = new Comparator<BaseDescription>() { 80 81 82 *o283 84 85 86 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 } 88 86 }; 89 87 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 } 96 99 } 97 100 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 } 104 112 } 105 113 106 114 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; 114 127 } 115 128 116 129 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; 124 142 } 125 126 143 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java
r4098 r5549 14 14 import clarin.cmdi.componentregistry.ComponentRegistryException; 15 15 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 16 import clarin.cmdi.componentregistry.ComponentStatus;17 16 import clarin.cmdi.componentregistry.DeleteFailedException; 17 import clarin.cmdi.componentregistry.ItemNotFoundException; 18 18 import clarin.cmdi.componentregistry.MDMarshaller; 19 import clarin.cmdi.componentregistry. OwnerUser;19 import clarin.cmdi.componentregistry.UserCredentials; 20 20 import clarin.cmdi.componentregistry.UserUnauthorizedException; 21 21 import clarin.cmdi.componentregistry.components.CMDComponentSpec; … … 54 54 55 55 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 57 62 try { 58 63 BaseDescription originalDescription = info.getDataNode() … … 72 77 IOUtils.toInputStream(info.getContent(), "UTF-8"), null); 73 78 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()); 78 81 if (result < 0) { 79 82 throw new SubmitFailedException( … … 83 86 throw new SubmitFailedException(e); 84 87 } catch (IOException e) { 88 throw new SubmitFailedException(e); 89 } catch (ItemNotFoundException e) { 85 90 throw new SubmitFailedException(e); 86 91 } … … 109 114 BaseDescription desc = info.getDataNode().getDescription(); 110 115 try { 111 deleteFromRegistry(userPrincipal, desc, info);116 this.deleteFromRegistry(userPrincipal, desc, info); 112 117 LOG.info("Deleted item: " + id); 113 118 } catch (IOException e) { … … 119 124 } catch (ComponentRegistryException e) { 120 125 throw new SubmitFailedException(e); 126 } catch (ItemNotFoundException e) { 127 throw new SubmitFailedException(e); 121 128 } 122 129 … … 125 132 private void deleteFromRegistry(Principal userPrincipal, 126 133 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)); 129 142 LOG.info("Deleting item: " + desc); 130 143 if (desc.isProfile()) { 131 registry.deleteMDProfile(desc.getId() , userPrincipal);144 registry.deleteMDProfile(desc.getId()); 132 145 } else { 133 registry.deleteMDComponent(desc.getId(), userPrincipal, 134 info.isForceUpdate()); 146 registry.deleteMDComponent(desc.getId(), info.isForceUpdate()); 135 147 } 136 148 } 137 149 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 154 154 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java
r4190 r5549 4 4 import clarin.cmdi.componentregistry.ComponentRegistry; 5 5 import clarin.cmdi.componentregistry.ComponentRegistryException; 6 import clarin.cmdi.componentregistry.ComponentStatus;7 6 import clarin.cmdi.componentregistry.Configuration; 8 7 import clarin.cmdi.componentregistry.DeleteFailedException; 8 import clarin.cmdi.componentregistry.ItemNotFoundException; 9 9 import clarin.cmdi.componentregistry.MDMarshaller; 10 10 import clarin.cmdi.componentregistry.Owner; 11 11 import clarin.cmdi.componentregistry.OwnerUser; 12 import clarin.cmdi.componentregistry.RegistrySpace; 12 13 import clarin.cmdi.componentregistry.UserUnauthorizedException; 13 14 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 15 import clarin.cmdi.componentregistry.components.CMDComponentType; 14 16 import clarin.cmdi.componentregistry.impl.ComponentRegistryImplBase; 15 17 import clarin.cmdi.componentregistry.impl.ComponentUtils; … … 17 19 import clarin.cmdi.componentregistry.model.Comment; 18 20 import clarin.cmdi.componentregistry.model.ComponentDescription; 21 import clarin.cmdi.componentregistry.model.Group; 19 22 import clarin.cmdi.componentregistry.model.ProfileDescription; 20 23 import clarin.cmdi.componentregistry.model.RegistryUser; … … 30 33 import java.io.UnsupportedEncodingException; 31 34 import java.security.Principal; 32 import java.text.ParseException;33 35 import java.util.ArrayList; 34 36 import java.util.Calendar; … … 51 53 * Implementation of ComponentRegistry that uses Database Acces Objects for 52 54 * accessing the registry (ergo: a database implementation) 53 * 55 * 54 56 * @author Twan Goosen <twan.goosen@mpi.nl> 55 57 * @author George.Georgovassilis@mpi.nl … … 58 60 public class ComponentRegistryDbImpl extends ComponentRegistryImplBase implements ComponentRegistry { 59 61 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 } 805 972 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java
r4098 r5549 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 4 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 5 import clarin.cmdi.componentregistry.ComponentStatus;6 5 import clarin.cmdi.componentregistry.Configuration; 7 6 import clarin.cmdi.componentregistry.Owner; 8 7 import clarin.cmdi.componentregistry.OwnerUser; 8 import clarin.cmdi.componentregistry.RegistrySpace; 9 9 import clarin.cmdi.componentregistry.UserCredentials; 10 10 import clarin.cmdi.componentregistry.UserUnauthorizedException; … … 25 25 * ComponentRegistryDbImpl implementation of ComponentRegistry for accessing the 26 26 * registry 27 * 27 * 28 28 * @author Twan Goosen <twan.goosen@mpi.nl> 29 29 * @author George.Georgovassilis@mpi.nl … … 32 32 33 33 private final static Logger LOG = LoggerFactory 34 34 .getLogger(ComponentRegistryFactoryDbImpl.class); 35 35 @Autowired 36 36 private Configuration configuration; … … 43 43 @Override 44 44 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; 73 88 } 74 89 75 90 private ComponentRegistry getPrivateRegistry(Owner owner, 76 77 78 79 80 81 82 83 84 85 86 87 returngetNewComponentRegistryForUser(user.getId());88 89 90 91 92 93 94 95 96 97 98 99 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 } 101 116 } 102 117 103 118 @Override 104 119 public ComponentRegistry getOtherUserComponentRegistry( 105 Principal adminPrincipal, ComponentStatus status, Owner owner) {106 107 108 109 110 111 // TODO: Implement for groups 112 113 114 115 116 117 118 result =getNewComponentRegistryForUser(user.getId());119 120 121 122 123 124 125 126 127 128 129 130 131 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 } 133 148 } 134 149 135 150 @Override 136 151 public ComponentRegistry getPublicRegistry() { 137 138 publicComponentRegistry =getNewComponentRegistryForUser(null);139 140 152 if (publicComponentRegistry == null) { 153 publicComponentRegistry = this.getNewComponentRegistryForUser(null); 154 } 155 return publicComponentRegistry; 141 156 } 142 157 143 158 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; 153 181 } 154 182 155 183 @Override 156 184 public RegistryUser getOrCreateUser(UserCredentials credentials) { 157 158 159 160 returngetOrCreateUser(principalName, credentials.getDisplayName());161 162 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; 163 191 } 164 192 165 193 private synchronized RegistryUser getOrCreateUser(String principalName, 166 167 168 169 170 171 172 new Object[] { principalName, displayName});173 174 175 176 177 178 179 180 181 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; 182 210 } 183 211 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupService.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.impl.database; 2 2 3 import clarin.cmdi.componentregistry.UserUnauthorizedException; 3 4 import java.util.List; 4 5 … … 95 96 * @param componentId 96 97 */ 97 void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId) ;98 void transferItemOwnershipFromUserToGroup(String principal, String groupId, String componentId) throws UserUnauthorizedException; 98 99 99 100 /** … … 103 104 * @param componentId 104 105 */ 105 void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) ;106 void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException; 106 107 107 108 /** … … 126 127 */ 127 128 List<String> getProfileIdsInGroup(long groupId); 128 129 130 boolean userGroupMember(String principalName, String groupId); 131 129 132 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImpl.java
r4169 r5549 1 1 package clarin.cmdi.componentregistry.impl.database; 2 2 3 import clarin.cmdi.componentregistry.UserUnauthorizedException; 3 4 import java.util.ArrayList; 4 5 import java.util.Collections; … … 235 236 ownerships.addAll(ownershipDao.findOwnershipByComponentId(itemId)); 236 237 Set<Group> groups = new HashSet<Group>(); 237 for (Ownership ownership : ownerships) 238 for (Ownership ownership : ownerships) { 238 239 groups.add(groupDao.findOne(ownership.getGroupId())); 240 } 239 241 List<Group> groupList = new ArrayList<Group>(groups); 240 242 Collections.sort(groupList, new Comparator<Group>() { … … 247 249 return groupList; 248 250 } 251 252 249 253 250 254 @ManagedOperation(description = "Make a component owned by a group instead of a user") … … 254 258 @ManagedOperationParameter(name = "componentId", description = "Id of component") }) 255 259 @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 258 263 BaseDescription item = null; 259 264 item = componentDao.getByCmdId(itemId); 260 if (item == null) 265 if (item == null) { 261 266 throw new ValidationException("No profile or component found with ID " + itemId); 267 } 262 268 Group group = groupDao.findGroupByName(groupName); 263 if (group == null) 269 if (group == null) { 264 270 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 265 283 Ownership ownership = null; 266 284 List<Ownership> oldOwnerships = ownershipDao.findOwnershipByComponentId(itemId); … … 273 291 274 292 @Override 275 public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) {293 public void transferItemOwnershipFromUserToGroupId(String principal, long groupId, String componentId) throws UserUnauthorizedException{ 276 294 Group group = groupDao.findOne(groupId); 277 if (group == null) 295 if (group == null) { 278 296 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 } 282 307 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/ComponentDao.java
r4098 r5549 16 16 public interface ComponentDao { 17 17 18 /** 19 * Get all public components 20 * 21 * @return 22 */ 23 List<BaseDescription> getPublicComponentDescriptions(); 24 18 25 19 /** 26 20 * Get all public profiles … … 28 22 * @return 29 23 */ 30 List<BaseDescription> getPublic ProfileDescriptions();24 List<BaseDescription> getPublicBaseDescriptions(String prefix); 31 25 32 26 /** … … 57 51 * public) 58 52 */ 59 boolean isInRegistry(String cmdId, Number userId);53 //boolean isAccessible(String cmdId, Number userId); 60 54 61 55 /** … … 117 111 * @return The description, if it exists; null otherwise 118 112 */ 119 BaseDescription getByCmdId(String id, Number userId) 120 throws DataAccessException; 113 // BaseDescription getByCmdId(String id, Number userId) 114 // throws DataAccessException; 115 121 116 122 117 /** … … 146 141 * not part of any group 147 142 */ 148 List<BaseDescription> get UserspaceComponents(Number userId)143 List<BaseDescription> getPrivateBaseDescriptions(Number userId, String prefix) 149 144 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 159 146 void setDeleted(BaseDescription desc, boolean isDeleted) 160 147 throws DataAccessException; … … 182 169 List<String> getAllNonDeletedComponentIds(); 183 170 171 public List<BaseDescription> getAllNonDeletedDescriptions(); 172 173 // Olha was here 174 public List<String> getAllItemIdsInGroup(String prefix, Long groupId); 184 175 185 176 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java
r4098 r5549 110 110 */ 111 111 private List<BaseDescription> augment(List<BaseDescription> baseDescription) { 112 if (baseDescription.isEmpty()) 112 if (baseDescription.isEmpty()) { 113 113 return baseDescription; 114 } 114 115 Map<String, BaseDescription> map = new HashMap<String, BaseDescription>(); 115 116 List<String> idlist = new ArrayList<String>(); … … 165 166 * public) 166 167 */ 167 @Override168 public boolean isInRegistry(String cmdId, Number userId) {169 if (userId == null) {170 returnisPublic(cmdId);171 } else {172 returnisInUserSpace(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 // } 175 176 176 177 /** … … 207 208 copy.setPublic(isPublic); 208 209 copy.setUserId(toString(userId)); 210 copy.setCreatorName(description.getCreatorName()); 209 211 copy = jpaComponentDao.saveAndFlush(copy); 210 212 jpaComponentDao.updateContent(copy.getId(), content); … … 278 280 } 279 281 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 306 283 /** 307 284 * … … 352 329 */ 353 330 @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 366 337 @Override 367 338 public void setDeleted(BaseDescription desc, boolean isDeleted) { … … 399 370 400 371 @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 412 377 @Override 413 378 public List<String> getAllNonDeletedProfileIds() { … … 419 384 return jpaComponentDao.findNonDeletedItemIds(ComponentDescription.COMPONENT_PREFIX+"%"); 420 385 } 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 422 400 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/CommentsDao.java
r4098 r5549 35 35 */ 36 36 @Query("select c from Comment c where c.componentId = ?1 order by c.commentDate, c.id") 37 List<Comment> getCommentsFrom Component(String componentId)37 List<Comment> getCommentsFromItem(String componentId) 38 38 throws DataAccessException; 39 39 … … 44 44 * @return Principal name of description's owner, if any. Otherwise, null. 45 45 */ 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") 47 48 RegistryUser getOwnerOfComment(long id); 48 49 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/JpaComponentDao.java
r4098 r5549 25 25 26 26 @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> findPubli cItems(String idPrefix);27 List<BaseDescription> findPublishedItems(String idPrefix); 28 28 29 29 @Query("select c from BaseDescription c where c.ispublic = false and c.deleted = true and c.dbUserId = ?1 order by upper(c.name), c.id") … … 33 33 List<BaseDescription> findPublicDeletedItems(); 34 34 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") 35 36 @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") 36 37 List<BaseDescription> findItemsForUserThatAreNotInGroups(Long userId, String idPrefix); … … 48 49 @Query("select c.componentId from BaseDescription c where c.deleted = false and c.componentId like ?1 order by c.id asc") 49 50 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(); 50 54 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); 51 60 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/jpa/UserDao.java
r4098 r5549 28 28 RegistryUser getByPrincipalName(String principalName) 29 29 throws DataAccessException; 30 31 @Query("select u from RegistryUser u where u.id = ?1") 32 RegistryUser getPrincipalNameById(Number id) throws DataAccessException; 30 33 31 34 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentClosure.java
r1352 r5549 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 4 import clarin.cmdi.componentregistry.ComponentRegistryException; 5 import clarin.cmdi.componentregistry.ItemNotFoundException; 6 import clarin.cmdi.componentregistry.UserUnauthorizedException; 5 7 import clarin.cmdi.componentregistry.model.ComponentDescription; 6 8 … … 8 10 9 11 @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); 12 14 } 13 15 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java
r4681 r5549 2 2 3 3 import clarin.cmdi.componentregistry.AllowedAttributetypesXML; 4 import clarin.cmdi.componentregistry.AuthenticationFailException; 4 5 import clarin.cmdi.componentregistry.ComponentRegistry; 5 6 import clarin.cmdi.componentregistry.ComponentRegistryException; 6 7 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 7 import clarin.cmdi.componentregistry.ComponentStatus;8 8 import clarin.cmdi.componentregistry.DeleteFailedException; 9 import clarin.cmdi.componentregistry.ItemNotFoundException; 9 10 import clarin.cmdi.componentregistry.MDMarshaller; 10 import clarin.cmdi.componentregistry. Owner;11 import clarin.cmdi.componentregistry.RegistrySpace; 11 12 import clarin.cmdi.componentregistry.UserCredentials; 12 13 import clarin.cmdi.componentregistry.UserUnauthorizedException; … … 45 46 import javax.servlet.ServletContext; 46 47 import javax.servlet.http.HttpServletRequest; 48 import javax.servlet.http.HttpServletResponse; 47 49 import javax.ws.rs.Consumes; 48 50 import javax.ws.rs.DELETE; … … 72 74 73 75 /** 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 * 75 79 * @author twago@mpi.nl 76 80 * @author olsha@mpi.nl … … 80 84 @Path("/registry") 81 85 @Service 82 @Transactional(rollbackFor = {Exception.class, ValidationException.class})86 @Transactional(rollbackFor = {Exception.class, ValidationException.class}) 83 87 public 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 } 1605 1768 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/IComponentRegistryRestService.java
r4135 r5549 1 1 package clarin.cmdi.componentregistry.rest; 2 2 3 import clarin.cmdi.componentregistry.UserUnauthorizedException; 3 4 import java.io.IOException; 4 5 import java.io.InputStream; … … 13 14 14 15 import clarin.cmdi.componentregistry.AllowedAttributetypesXML; 15 import clarin.cmdi.componentregistry.ComponentRegistry;16 16 import clarin.cmdi.componentregistry.ComponentRegistryException; 17 17 import clarin.cmdi.componentregistry.ComponentRegistryFactory; … … 44 44 public static final String GROUP_FORM_FIELD = "group"; 45 45 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"; 47 47 public static final String GROUPID_PARAM = "groupid"; 48 48 public static final String METADATA_EDITOR_PARAM = "mdEditor"; 49 49 public static final String NUMBER_OF_RSSITEMS = "limit"; 50 50 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 ; 84 78 85 79 /** … … 92 86 * @return 93 87 */ 94 Response manipulateRegisteredProfile(String profileId, String method, 95 boolean userspace); 88 Response manipulateRegisteredProfile(String profileId, String method); 96 89 97 90 Response manipulateCommentFromProfile(String profileId, String commentId, 98 String method , boolean userspace);91 String method); 99 92 100 93 Response manipulateCommentFromComponent(String componentId, 101 String commentId, String method , boolean userspace);94 String commentId, String method); 102 95 103 96 Response publishRegisteredProfile(String profileId, InputStream input, 104 97 String name, String description, String group, String domainName); 105 98 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, 108 101 String domainName); 109 102 … … 117 110 * @return 118 111 */ 119 Response manipulateRegisteredComponent(String componentId, String method, 120 boolean userspace); 112 Response manipulateRegisteredComponent(String componentId, String method); 121 113 122 114 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, 127 119 String domainName); 128 120 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; 140 130 141 131 Response registerProfile(InputStream input, String name, 142 String description, String group, String domainName, 143 boolean userspace); 132 String description, String groupId, String domainName); 144 133 145 134 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; 154 140 155 141 Response pingSession(); … … 158 144 * @param componentRegistryFactory the componentRegistryFactory to set 159 145 */ 160 void setComponentRegistryFactory( 161 ComponentRegistryFactory componentRegistryFactory); 146 void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory); 162 147 163 148 /** … … 169 154 * @throws ParseException 170 155 */ 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; 173 158 174 159 /** … … 180 165 * @throws ParseException 181 166 */ 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; 184 169 185 170 /** … … 194 179 * @throws ParseException 195 180 */ 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; 199 183 200 184 /** … … 209 193 * @throws ParseException 210 194 */ 211 Rss getRssOfCommentsFromComponent(String componentId, boolean userspace,195 Rss getRssOfCommentsFromComponent(String componentId, 212 196 String limit) throws ComponentRegistryException, IOException, 213 197 JAXBException, ParseException; … … 237 221 * @param groupId 238 222 */ 239 void transferItemOwnershipToGroup(String itemId, long groupId);223 String transferItemOwnershipToGroup(String itemId, long groupId) throws IOException; 240 224 241 225 /** … … 244 228 * @return 245 229 */ 246 BaseDescription get ComponentDescription(String componentId) throws ComponentRegistryException;230 BaseDescription getBaseDescription(String componentId) throws ComponentRegistryException, IOException; 247 231 248 232 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/MDValidator.java
r4550 r5549 5 5 import clarin.cmdi.componentregistry.ComponentRegistryResourceResolver; 6 6 import clarin.cmdi.componentregistry.Configuration; 7 import clarin.cmdi.componentregistry.ItemNotFoundException; 7 8 import clarin.cmdi.componentregistry.MDMarshaller; 9 import clarin.cmdi.componentregistry.NullIdException; 10 import clarin.cmdi.componentregistry.RegistrySpace; 11 import clarin.cmdi.componentregistry.UserUnauthorizedException; 8 12 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 9 13 import clarin.cmdi.componentregistry.components.CMDComponentType; 10 14 import clarin.cmdi.componentregistry.model.BaseDescription; 11 import clarin.cmdi.componentregistry.model.ComponentDescription;12 15 import clarin.cmdi.schema.cmd.Validator.Message; 13 16 import clarin.cmdi.schema.cmd.ValidatorException; … … 29 32 30 33 public class MDValidator implements Validator { 31 34 32 35 private final static Logger LOG = LoggerFactory.getLogger(MDValidator.class); 33 36 static final String MISMATCH_ERROR = "Cannot register component as a profile or vica versa."; … … 36 39 static final String SCHEMA_ERROR = "Error in reading general component schema: "; 37 40 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 publishedcomponents: ";41 static final String COMPONENT_NOT_REGISTERED_IN_APPROPRIATE_SPACE_ERROR = "referenced component cannot be found in the appropriate registry components: "; 39 42 static final String COMPONENT_REGISTRY_EXCEPTION_ERROR = "An exception occurred while accessing the component registry: "; 40 43 static final String ILLEGAL_ATTRIBUTE_NAME_ERROR = "Illegal attribute name: "; … … 47 50 private final BaseDescription description; 48 51 private final ComponentRegistry registry; 49 private final ComponentRegistry userRegistry;50 private final ComponentRegistry publicRegistry;51 52 private final MDMarshaller marshaller; 52 53 … … 61 62 * @param registry 62 63 */ 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) { 64 65 this.input = input; 65 66 this.description = description; 66 67 this.registry = registry; 67 this.userRegistry = userRegistry;68 this.publicRegistry = publicRegistry;69 68 this.marshaller = marshaller; 70 69 } 71 70 72 71 @Override 73 72 public List<String> getErrorMessages() { 74 73 return errorMessages; 75 74 } 76 75 77 76 @Override 78 public boolean validate() {77 public boolean validate() throws UserUnauthorizedException { 79 78 try { 80 79 clarin.cmdi.schema.cmd.Validator validator = new clarin.cmdi.schema.cmd.Validator(new URL(Configuration.getInstance().getGeneralComponentSchema())); … … 116 115 } catch (ComponentRegistryException e) { 117 116 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); 118 121 } 119 122 } 120 123 return errorMessages.isEmpty(); 121 124 } 122 125 123 126 private byte[] getBytesFromInputStream() throws IOException { 124 127 int len; 125 128 byte[] b = new byte[4096]; 126 129 final ByteArrayOutputStream bOS = new ByteArrayOutputStream(); 127 130 128 131 while ((len = input.read(b)) > 0) { 129 132 bOS.write(b, 0, len); 130 133 } 131 134 132 135 return bOS.toByteArray(); 133 136 } 134 137 135 private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException {138 private void validateComponents(CMDComponentSpec componentSpec) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException { 136 139 validateComponents(Collections.singletonList(componentSpec.getCMDComponent())); 137 140 } 138 139 private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException {141 142 private void validateComponents(List<CMDComponentType> cmdComponents) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException, NullIdException { 140 143 for (CMDComponentType cmdComponentType : cmdComponents) { 141 validateDescribedComponents(cmdComponentType);142 validateComponents(cmdComponentType.getCMDComponent());//Recursion143 } 144 } 145 146 private void validateDescribedComponents(CMDComponentType cmdComponentType) throws ComponentRegistryException {147 checkPublicComponents(cmdComponentType);148 } 149 150 private void check PublicComponents(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 { 151 154 if (isDefinedInSeparateFile(cmdComponentType)) { 152 155 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; 162 183 } 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; 163 190 } 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; 165 193 } 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 179 201 private boolean isDefinedInSeparateFile(CMDComponentType cmdComponentType) { 180 202 return cmdComponentType.getName() == null; … … 195 217 * has validated. If you are not going to alter this copy, you can re-use 196 218 * 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> 199 220 * 200 221 * @return a freshly unmarshalled copy of the spec based on the bytes … … 209 230 // Re-unmarshall original bytes 210 231 return unmarshalSpec(originalSpecBytes); 211 } 212 232 233 234 } 235 213 236 private CMDComponentSpec unmarshalSpec(byte[] inputBytes) throws JAXBException { 214 237 return marshaller.unmarshal(CMDComponentSpec.class, new ByteArrayInputStream(inputBytes), null); -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ProfileClosure.java
r1352 r5549 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 4 import clarin.cmdi.componentregistry.ComponentRegistryException; 5 import clarin.cmdi.componentregistry.ItemNotFoundException; 6 import clarin.cmdi.componentregistry.UserUnauthorizedException; 5 7 import clarin.cmdi.componentregistry.model.ProfileDescription; 6 8 … … 8 10 9 11 @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); 12 14 } 13 15 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/PublishAction.java
r4098 r5549 4 4 5 5 import clarin.cmdi.componentregistry.ComponentRegistry; 6 import clarin.cmdi.componentregistry.ItemNotFoundException; 7 import clarin.cmdi.componentregistry.UserUnauthorizedException; 6 8 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 7 9 import clarin.cmdi.componentregistry.model.BaseDescription; … … 17 19 18 20 @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{ 20 22 response.setIsInUserSpace(false); 21 23 return registry.publish(desc, spec, principal); -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegisterAction.java
r4098 r5549 2 2 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 import clarin.cmdi.componentregistry.ItemNotFoundException; 5 import clarin.cmdi.componentregistry.UserUnauthorizedException; 4 6 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 5 7 import clarin.cmdi.componentregistry.model.BaseDescription; … … 8 10 public interface RegisterAction { 9 11 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; 11 13 12 14 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/RegistryClosure.java
r4098 r5549 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 4 import clarin.cmdi.componentregistry.ComponentRegistryException; 5 import clarin.cmdi.componentregistry.ItemNotFoundException; 6 import clarin.cmdi.componentregistry.UserUnauthorizedException; 5 7 import clarin.cmdi.componentregistry.model.BaseDescription; 6 8 7 9 public interface RegistryClosure<T extends BaseDescription> { 8 10 9 T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException ;11 T getDescription(ComponentRegistry registry, String id) throws ComponentRegistryException, UserUnauthorizedException, ItemNotFoundException; 10 12 11 13 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/UpdateAction.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.rest; 2 2 3 import java.security.Principal;3 //import java.security.Principal; 4 4 5 5 import clarin.cmdi.componentregistry.ComponentRegistry; 6 import clarin.cmdi.componentregistry.ItemNotFoundException; 7 import clarin.cmdi.componentregistry.UserUnauthorizedException; 6 8 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 7 9 import clarin.cmdi.componentregistry.model.BaseDescription; … … 10 12 public class UpdateAction implements RegisterAction { 11 13 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 // } 17 19 18 20 @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); 21 23 } 22 24 -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/Validator.java
r127 r5549 1 1 package clarin.cmdi.componentregistry.rest; 2 2 3 import clarin.cmdi.componentregistry.UserUnauthorizedException; 3 4 import java.util.List; 4 5 … … 15 16 * Validate and create an error message when something is wrong. 16 17 */ 17 public boolean validate() ;18 public boolean validate() throws UserUnauthorizedException; 18 19 19 20 } -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreator.java
r2515 r5549 20 20 private String channelTitle; 21 21 private Comparator<T> comparator; 22 protected final boolean userspace;22 protected final boolean isPrivate; 23 23 private List<T> objs; 24 24 private int limit; 25 25 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; 28 28 this.baseURI = baseURI; 29 29 this.limit = limit; -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorComments.java
r2515 r5549 14 14 /** 15 15 * 16 * @param userspace if "true" then profiles and components from the user's16 * @param isPrivate if "true" then profiles and components from the user's 17 17 * workspace, otherwise -- public (uri-parameter) 18 18 * @param baseURI where the database is located … … 27 27 * @param comparator compare comments by dates 28 28 */ 29 public RssCreatorComments(boolean userspace, String baseURI, int limit,29 public RssCreatorComments(boolean isPrivate, String baseURI, int limit, 30 30 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 + "\""); 34 34 setChannelDescription(String.format("Comments feed for the %s \"%s\"", descriptionType, descriptionName)); 35 35 setComparator(comparator); -
ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rss/RssCreatorDescriptions.java
r4098 r5549 14 14 /** 15 15 * 16 * @param userspace if "true" then profiles and components from the user's16 * @param isPrivate if "true" then profiles and components from the user's 17 17 * workspace, otherwise -- public (uri-parameter) 18 18 * @param baseURI where the database is located … … 23 23 * @param comparator compare descriptions by dates 24 24 */ 25 public RssCreatorDescriptions(boolean userspace, String baseURI, String descriptionType,25 public RssCreatorDescriptions(boolean isPrivate, String baseURI, String descriptionType, 26 26 int limit, List<T> descriptions, Comparator<T> comparator) { 27 super( userspace, baseURI, limit, descriptions);27 super(isPrivate, baseURI, limit, descriptions); 28 28 setChannelLink(baseURI + "/"); 29 setChannelTitle(( userspace ? "Your workspace " : "Public ") + descriptionType);29 setChannelTitle((isPrivate ? "Private " : "Public ") + descriptionType); 30 30 setChannelDescription(String.format("News feed for the %s", descriptionType)); 31 31 setComparator(comparator); … … 41 41 @Override 42 42 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" : ""); 44 44 RssItem retval = new RssItem(); 45 45 retval.setDescription(desc.getDescription()); -
ComponentRegistry/trunk/ComponentRegistry/src/main/resources/spring-config/applicationContext.xml
r4098 r5549 70 70 71 71 <!-- Prototype bean for component registry (service) --> 72 <bean id="componentRegistry "72 <bean id="componentRegistryDbImpl" 73 73 class="clarin.cmdi.componentregistry.impl.database.ComponentRegistryDbImpl" 74 74 scope="prototype" /> -
ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/META-INF/context.xml
r4098 r5549 36 36 --> 37 37 <Context antiJARLocking="true" path="/ComponentRegistry"> 38 38 <!-- 39 39 Passed to the Flex UI via index.jsp so that it can locate the 40 40 ComponentRegistry REST service. Just supply the application root: 41 41 the '/rest/registry' part will be added by the application. 42 42 --> 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 <!-- 48 45 Location that gets redirected to from /documentation.jsp, which in turn is linked to 49 46 from the Flex application through the 'Help' link button. 50 47 --> 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 <!-- 56 50 Space-separated list of users (getRemoteUser()) that should have access to the admin area of the ComponentRegistry 57 51 --> 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 <!-- 63 54 Location of the CMDI general component schema that validates component specifications 64 55 --> 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 <!-- 70 58 Location of the stylesheet that transforms component specifications into XML schema documents 71 59 --> 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 <!-- 77 62 Schema location that will go into xsi:schemaLocation attribute of component specification. Beware this should follow 78 63 XML standards and have a namespace component (URI) and schema location component (URL) separated by a space 79 64 --> 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 <!-- 85 67 Base location of the ISOcat service 86 68 --> 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"/> 97 71 </Context> -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/frontend/CMDItemInfoTest.java
r4098 r5549 3 3 import clarin.cmdi.componentregistry.BaseUnitTest; 4 4 import clarin.cmdi.componentregistry.ComponentStatus; 5 import clarin.cmdi.componentregistry.MDMarshaller; 6 import static org.junit.Assert.assertEquals; 5 import clarin.cmdi.componentregistry.RegistrySpace; 7 6 import static org.junit.Assert.assertFalse; 8 7 import static org.junit.Assert.assertTrue; … … 15 14 public class CMDItemInfoTest extends BaseUnitTest{ 16 15 16 // this is component status "private/public" from the database v.s. registry space public/private 17 17 @Test 18 18 public void testGetUserDir() throws Exception { 19 19 CMDItemInfo info = new CMDItemInfo(marshaller); 20 20 //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)); 22 22 assertTrue(info.isDeletable()); 23 23 assertFalse(info.isUndeletable()); 24 24 assertTrue(info.isEditable()); 25 25 assertFalse(info.getDataNode().isDeleted()); 26 assertEquals( ComponentStatus.PRIVATE, info.getStatus());26 assertEquals(RegistrySpace.PRIVATE, info.getSpace()); 27 27 //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)); 29 29 assertFalse(info.isDeletable()); 30 30 assertTrue(info.isUndeletable()); 31 31 assertTrue(info.isEditable()); 32 32 assertTrue(info.getDataNode().isDeleted()); 33 assertEquals( ComponentStatus.PRIVATE, info.getStatus());33 assertEquals(RegistrySpace.PRIVATE, info.getSpace()); 34 34 //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)); 36 36 assertTrue(info.isDeletable()); 37 37 assertFalse(info.isUndeletable()); 38 38 assertTrue(info.isEditable()); 39 assertEquals( ComponentStatus.PUBLISHED, info.getStatus());39 assertEquals(RegistrySpace.PUBLISHED, info.getSpace()); 40 40 //info.setDataNode(new FileNode(createFile("components/c_123/"), false)); 41 41 info.setDataNode(new DisplayDataNode("test", false)); … … 44 44 assertFalse(info.isEditable()); 45 45 //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)); 47 47 assertFalse(info.isDeletable()); 48 48 assertTrue(info.isUndeletable()); 49 49 assertTrue(info.isEditable()); 50 assertEquals( ComponentStatus.PUBLISHED, info.getStatus());50 assertEquals(RegistrySpace.PUBLISHED, info.getSpace()); 51 51 assertTrue(info.getDescription().startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<profileDescription")); 52 52 //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 14 14 import clarin.cmdi.componentregistry.BaseUnitTest; 15 15 import clarin.cmdi.componentregistry.model.BaseDescription; 16 import clarin.cmdi.componentregistry.model.ComponentDescription; 16 17 import clarin.cmdi.componentregistry.persistence.ComponentDao; 17 18 import clarin.cmdi.componentregistry.persistence.jpa.UserDao; … … 96 97 // returned. Should also test the case where there are userspace 97 98 // descriptions 98 List<BaseDescription> descriptions = getDao().get UserspaceComponents(-1);99 List<BaseDescription> descriptions = getDao().getPrivateBaseDescriptions(-1, ComponentDescription.COMPONENT_PREFIX); 99 100 assertEquals(0, descriptions.size()); 100 101 } -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.impl.database; 2 2 3 import static org.junit.Assert.assertEquals;4 3 import static org.junit.Assert.assertTrue; 5 4 import static org.junit.Assert.fail; … … 14 13 import clarin.cmdi.componentregistry.ComponentRegistry; 15 14 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 16 import clarin.cmdi.componentregistry.ComponentStatus;17 15 import clarin.cmdi.componentregistry.DeleteFailedException; 18 16 import clarin.cmdi.componentregistry.MDMarshaller; 17 import clarin.cmdi.componentregistry.RegistrySpace; 19 18 import clarin.cmdi.componentregistry.frontend.CMDItemInfo; 20 19 import clarin.cmdi.componentregistry.frontend.DisplayDataNode; … … 22 21 import clarin.cmdi.componentregistry.model.ComponentDescription; 23 22 import clarin.cmdi.componentregistry.model.ProfileDescription; 23 import clarin.cmdi.componentregistry.model.RegistryUser; 24 24 import clarin.cmdi.componentregistry.persistence.ComponentDao; 25 import clarin.cmdi.componentregistry.persistence.jpa.UserDao; 25 26 import clarin.cmdi.componentregistry.rest.DummyPrincipal; 26 27 import clarin.cmdi.componentregistry.rest.RegistryTestHelper; … … 35 36 @Autowired 36 37 private ComponentDao componentDao; 38 39 @Autowired 40 private UserDao userDao; 41 37 42 @Autowired 38 43 private ComponentRegistryFactory componentRegistryFactory; … … 46 51 } 47 52 53 // TODO: two questions 48 54 @Test 49 55 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 50 62 ComponentRegistry testRegistry = componentRegistryFactory.getPublicRegistry(); 51 63 String content1 = ""; … … 57 69 content1 += " </CMD_Component>\n"; 58 70 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 61 75 String content2 = ""; 62 76 content2 += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; … … 68 82 content2 += " </CMD_Component>\n"; 69 83 content2 += "</CMD_ComponentSpec>\n"; 70 ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2); 84 ProfileDescription profileDesc = RegistryTestHelper.addProfile(testRegistry, "YYY1", content2, true); 85 71 86 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 72 92 AdminRegistry adminReg = new AdminRegistry(); 73 93 adminReg.setComponentRegistryFactory(componentRegistryFactory); … … 76 96 CMDItemInfo fileInfo = new CMDItemInfo(marshaller); 77 97 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)); 79 99 fileInfo.setContent(content1); 80 try { 100 // TODO: how it should be? 101 try { 81 102 adminReg.submitFile(fileInfo, PRINCIPAL_ADMIN); 82 fail(); 103 104 // Twan ?? when submit should fail? 105 //fail(); 83 106 } catch (SubmitFailedException e) { 84 107 } … … 87 110 88 111 assertEquals(1, testRegistry.getComponentDescriptions().size()); 89 try { 112 113 try { 90 114 fileInfo.setForceUpdate(false); 91 115 adminReg.delete(fileInfo, PRINCIPAL_ADMIN); 92 fail();93 116 } catch (SubmitFailedException e) { 94 117 assertTrue(e.getCause() instanceof DeleteFailedException); 95 118 } 96 assertEquals(1, testRegistry.getComponentDescriptions().size()); 119 120 assertEquals(1, testRegistry.getComponentDescriptions().size()); 97 121 fileInfo.setForceUpdate(true); 98 122 adminReg.delete(fileInfo, PRINCIPAL_ADMIN); … … 101 125 assertEquals(1, testRegistry.getProfileDescriptions().size()); 102 126 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)); 104 128 adminReg.delete(fileInfo, PRINCIPAL_ADMIN); //Profile do not need to be forced they cannot be used by other profiles 105 129 assertEquals(0, testRegistry.getProfileDescriptions().size()); -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java
r4098 r5549 93 93 @Test 94 94 public void testGetCommentsFromProfile() { 95 List<Comment> descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_PROFILE_ID);95 List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID); 96 96 assertNotNull(descriptions); 97 97 … … 102 102 commentsDao.save(comment1); 103 103 104 descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_PROFILE_ID);104 descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID); 105 105 assertEquals(size + 1, descriptions.size()); 106 106 … … 110 110 commentsDao.save(comment2); 111 111 112 descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_PROFILE_ID);112 descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_PROFILE_ID); 113 113 assertEquals(size + 2, descriptions.size()); 114 114 } … … 116 116 @Test 117 117 public void testGetCommentsFromComponent() { 118 List<Comment> descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_COMPONENT_ID);118 List<Comment> descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID); 119 119 assertNotNull(descriptions); 120 120 … … 125 125 commentsDao.saveAndFlush(comment1); 126 126 127 descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_COMPONENT_ID);127 descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID); 128 128 assertEquals(size + 1, descriptions.size()); 129 129 … … 133 133 commentsDao.saveAndFlush(comment2); 134 134 135 descriptions = commentsDao.getCommentsFrom Component(TEST_COMMENT_COMPONENT_ID);135 descriptions = commentsDao.getCommentsFromItem(TEST_COMMENT_COMPONENT_ID); 136 136 assertEquals(size + 2, descriptions.size()); 137 137 } -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java
r3449 r5549 9 9 import clarin.cmdi.componentregistry.ComponentStatus; 10 10 import clarin.cmdi.componentregistry.OwnerUser; 11 import clarin.cmdi.componentregistry.RegistrySpace; 11 12 import clarin.cmdi.componentregistry.UserCredentials; 12 13 import clarin.cmdi.componentregistry.UserUnauthorizedException; … … 50 51 .getPublicRegistry(); 51 52 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 52 62 } 53 63 … … 56 66 // Get public 57 67 assertNotNull(componentRegistryFactory.getComponentRegistry( 58 ComponentStatus.PUBLISHED, null, null));68 RegistrySpace.PUBLISHED, null, null, null)); 59 69 60 70 // Get for non-existing user … … 64 74 65 75 ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory 66 .getComponentRegistry( ComponentStatus.PRIVATE, null,67 credentials );76 .getComponentRegistry(RegistrySpace.PRIVATE, null, 77 credentials,null); 68 78 assertNotNull(cr1); 69 79 // Get for existing user 70 80 ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory 71 .getComponentRegistry( ComponentStatus.PRIVATE, null,72 credentials );81 .getComponentRegistry(RegistrySpace.PRIVATE, null, 82 credentials, null); 73 83 ; 74 84 assertNotNull(cr2); 75 assertEquals(cr1.get Owner(), cr2.getOwner());85 assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner()); 76 86 77 87 // Get for another new user … … 79 89 testUser.getPrincipalName() + "2").getCredentials(); 80 90 ComponentRegistryDbImpl cr3 = (ComponentRegistryDbImpl) componentRegistryFactory 81 .getComponentRegistry( ComponentStatus.PRIVATE, null,82 credentials2 );91 .getComponentRegistry(RegistrySpace.PRIVATE, null, 92 credentials2, null); 83 93 assertNotNull(cr3); 84 assertNotSame(cr1.get Owner(), cr3.getOwner());94 assertNotSame(cr1.getRegistryOwner(), cr3.getRegistryOwner()); 85 95 } 86 96 … … 93 103 // Create registry for new user 94 104 ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory 95 .getComponentRegistry( ComponentStatus.PRIVATE, null,96 userCredentials );105 .getComponentRegistry(RegistrySpace.PRIVATE, null, 106 userCredentials, null); 97 107 98 Number id = cr1.get Owner().getId();108 Number id = cr1.getRegistryOwner().getId(); 99 109 100 110 // Get it as admin 101 111 ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory 102 112 .getOtherUserComponentRegistry( 103 DummyPrincipal.DUMMY_ADMIN_PRINCIPAL, 104 ComponentStatus.PRIVATE, new OwnerUser(id)); 113 DummyPrincipal.DUMMY_ADMIN_PRINCIPAL, new OwnerUser(id)); 105 114 assertNotNull(cr2); 106 115 // Should be this user's registry 107 assertEquals(cr1.get Owner(), cr2.getOwner());116 assertEquals(cr1.getRegistryOwner(), cr2.getRegistryOwner()); 108 117 109 118 // Try get it as non-admin 110 119 try { 111 120 componentRegistryFactory.getOtherUserComponentRegistry( 112 DummyPrincipal.DUMMY_PRINCIPAL, ComponentStatus.PRIVATE, 113 new OwnerUser(id)); 121 DummyPrincipal.DUMMY_PRINCIPAL, new OwnerUser(id)); 114 122 fail("Non-admin can get other user's component registry"); 115 123 } catch (Exception ex) { -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryTestDatabase.java
r4098 r5549 96 96 createTableOwnership(jdbcTemplate); 97 97 createTableGroupMembership(jdbcTemplate); 98 98 99 } 99 100 } -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/GroupServiceImplTest.java
r4098 r5549 8 8 9 9 import clarin.cmdi.componentregistry.BaseUnitTest; 10 import clarin.cmdi.componentregistry.UserUnauthorizedException; 10 11 import clarin.cmdi.componentregistry.model.BaseDescription; 11 12 import clarin.cmdi.componentregistry.model.ComponentDescription; 12 13 import clarin.cmdi.componentregistry.model.Group; 13 import clarin.cmdi.componentregistry.model.GroupMembership;14 14 import clarin.cmdi.componentregistry.model.Ownership; 15 15 import clarin.cmdi.componentregistry.model.ProfileDescription; … … 47 47 profile.setId(ProfileDescription.PROFILE_PREFIX+sid); 48 48 profile.setName("profilename"); 49 profile.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName()); 49 50 Number id = componentDescriptionDao.insertDescription(profile, "someContent", 50 51 isPublic, ownerId); … … 58 59 componentDescription.setId(ComponentDescription.COMPONENT_PREFIX+"4567"); 59 60 componentDescription.setName("componentname"); 61 componentDescription.setCreatorName(DummyPrincipal.DUMMY_PRINCIPAL.getName()); 60 62 Number id = componentDescriptionDao.insertDescription( 61 63 componentDescription, "someContent", isPublic, ownerId); … … 255 257 256 258 @Test 257 public void testTransferComponentOwnershipFromUserToGroup() {259 public void testTransferComponentOwnershipFromUserToGroup() throws UserUnauthorizedException{ 258 260 259 261 // Make a group … … 307 309 308 310 @Test 309 public void testtransferComponentOwnershipFromUserToGroup() {311 public void testtransferComponentOwnershipFromUserToGroup() throws UserUnauthorizedException{ 310 312 311 313 // Make a group … … 360 362 361 363 @Test 362 public void testTransferItemOwnershipFromUserToGroup() {364 public void testTransferItemOwnershipFromUserToGroup() throws UserUnauthorizedException{ 363 365 //TODO: improve test by mixing in components and exclusing components/profiles 364 366 // Make a group … … 413 415 414 416 @Test 415 public void testGetGroupsTheItemIsAMemberOf() {417 public void testGetGroupsTheItemIsAMemberOf() throws UserUnauthorizedException{ 416 418 // Make a group 417 419 Group group1 = groupDao.findOne(groupService.createNewGroup("Group 1", -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java
r4550 r5549 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 4 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 5 import clarin.cmdi.componentregistry.ComponentStatus;6 5 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 7 6 import clarin.cmdi.componentregistry.components.CMDComponentType; … … 14 13 import clarin.cmdi.componentregistry.model.ProfileDescription; 15 14 import clarin.cmdi.componentregistry.model.RegisterResponse; 16 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService. USERSPACE_PARAM;15 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM; 17 16 18 17 import com.sun.jersey.api.client.ClientResponse; … … 32 31 33 32 import org.junit.Before; 33 import org.junit.Ignore; 34 34 import org.junit.Test; 35 35 import org.springframework.beans.factory.annotation.Autowired; … … 53 53 @Autowired 54 54 private JdbcTemplate jdbcTemplate; 55 private ComponentRegistry testRegistry;55 private ComponentRegistry baseRegistry; 56 56 57 57 @Before … … 59 59 ComponentRegistryTestDatabase.resetAndCreateAllTables(jdbcTemplate); 60 60 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); 67 62 } 68 63 … … 76 71 private ProfileDescription profile2; 77 72 73 private ComponentDescription component3; 74 private ProfileDescription profile3; 75 78 76 private Comment profile1Comment1; 79 77 private Comment profile1Comment2; 80 78 private Comment component1Comment3; 81 79 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", 91 93 ProfileDescription.PROFILE_PREFIX + "profile1", 92 94 "JUnit@test.com"); 93 profile1Comment1 = RegistryTestHelper.addComment( getTestRegistry(), "comment1",95 profile1Comment1 = RegistryTestHelper.addComment(baseRegistry, "comment1", 94 96 ProfileDescription.PROFILE_PREFIX + "profile1", 95 97 "JUnit@test.com"); 96 component1Comment3 = RegistryTestHelper.addComment( getTestRegistry(), "comment3",98 component1Comment3 = RegistryTestHelper.addComment(baseRegistry, "comment3", 97 99 ComponentDescription.COMPONENT_PREFIX + "component1", 98 100 "JUnit@test.com"); 99 component1Comment4 = RegistryTestHelper.addComment( getTestRegistry(), "comment4",101 component1Comment4 = RegistryTestHelper.addComment(baseRegistry, "comment4", 100 102 ComponentDescription.COMPONENT_PREFIX + "component1", 101 103 "JUnit@test.com"); 102 104 } 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) 110 126 .get(PROFILE_LIST_GENERICTYPE); 111 127 assertEquals(3, response.size()); 112 response = getResource().path("/registry/profiles") 128 response = this.getAuthenticatedResource(getResource() 129 .path("/registry/profiles")) 113 130 .accept(MediaType.APPLICATION_JSON) 114 131 .get(PROFILE_LIST_GENERICTYPE); … … 119 136 } 120 137 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) 127 146 .get(COMPONENT_LIST_GENERICTYPE); 128 147 assertEquals(3, response.size()); 129 response = getResource().path("/registry/components") 148 response = this.getAuthenticatedResource(getResource() 149 .path("/registry/components")) 130 150 .accept(MediaType.APPLICATION_JSON) 131 151 .get(COMPONENT_LIST_GENERICTYPE); … … 136 156 } 137 157 138 @Test 158 @Test //ok 139 159 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( 145 170 MediaType.APPLICATION_JSON).get(COMPONENT_LIST_GENERICTYPE); 146 171 assertEquals("Get public components", 2, response.size()); 172 147 173 ClientResponse cResponse = getResource().path("/registry/components") 148 .queryParam( USERSPACE_PARAM, "true")174 .queryParam(REGISTRY_SPACE_PARAM, "private") 149 175 .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); 150 176 assertEquals("Trying to get userspace without credentials", 401, … … 152 178 } 153 179 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"; 158 186 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)) 161 189 .accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class); 162 190 assertNotNull(component); 163 191 assertEquals("Access", component.getCMDComponent().getName()); 164 component = getResource().path("/registry/components/" + id2) 192 193 194 component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id2)) 165 195 .accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class); 166 196 assertNotNull(component); 167 197 assertEquals("Access", component.getCMDComponent().getName()); 168 169 198 assertEquals(id2, component.getHeader().getID()); 170 199 assertEquals("component2", component.getHeader().getName()); … … 172 201 } 173 202 174 @Test 175 public void testGetRegisteredCommentsInProfile() throws Exception { 176 fillUp(); 203 @Test // ok 204 public void testGetCommentsInPublicProfile() throws Exception { 205 206 fillUpPublicItems(); 207 177 208 String id = ProfileDescription.PROFILE_PREFIX + "profile1"; 178 RegistryTestHelper.addComment( getTestRegistry(), "COMMENT1", id,209 RegistryTestHelper.addComment(baseRegistry, "COMMENT1", id, 179 210 "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/")) 182 213 .accept(MediaType.APPLICATION_XML) 183 214 .get(COMMENT_LIST_GENERICTYPE); 184 215 assertEquals(3, response.size()); 185 response = getResource().path("/registry/profiles/" + id + "/comments") 216 217 response = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id + "/comments")) 186 218 .accept(MediaType.APPLICATION_JSON) 187 219 .get(COMMENT_LIST_GENERICTYPE); … … 194 226 } 195 227 196 @Test 197 public void testGetRegisteredCommentsInComponent() throws Exception { 198 fillUp(); 228 @Test // ok 229 public void testGetCommentsInPubliComponent() throws Exception { 230 fillUpPublicItems(); 231 199 232 String id = ComponentDescription.COMPONENT_PREFIX + "component1"; 200 RegistryTestHelper.addComment( getTestRegistry(), "COMMENT2", id,233 RegistryTestHelper.addComment(baseRegistry, "COMMENT2", id, 201 234 "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/")) 204 237 .accept(MediaType.APPLICATION_XML) 205 238 .get(COMMENT_LIST_GENERICTYPE); 206 239 assertEquals(3, response.size()); 207 response = getResource()208 .path("/registry/components/" + id + "/comments") 240 response = this.getAuthenticatedResource(getResource() 241 .path("/registry/components/" + id + "/comments")) 209 242 .accept(MediaType.APPLICATION_JSON) 210 243 .get(COMMENT_LIST_GENERICTYPE); … … 217 250 } 218 251 219 @Test 220 public void testGetSpecifiedCommentInComponent() throws Exception { 221 fillUp(); 252 @Test // ok 253 public void testGetSpecifiedCommentInPublicComponent() throws Exception { 254 255 fillUpPublicItems(); 256 222 257 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())) 225 260 .accept(MediaType.APPLICATION_JSON).get(Comment.class); 226 261 assertNotNull(comment); 227 262 assertEquals("comment3", comment.getComment()); 228 263 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())) 231 266 .accept(MediaType.APPLICATION_JSON).get(Comment.class); 232 267 assertNotNull(comment); … … 236 271 } 237 272 238 @Test 239 public void testGetSpecifiedCommentInProfile() throws Exception { 240 fillUp(); 273 @Test //ok 274 public void testGetSpecifiedCommentInPublicProfile() throws Exception { 275 276 fillUpPublicItems(); 277 241 278 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())) 244 281 .accept(MediaType.APPLICATION_JSON).get(Comment.class); 245 282 assertNotNull(comment); 246 283 assertEquals("comment2", comment.getComment()); 247 284 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); 251 289 assertNotNull(comment); 252 290 assertEquals("comment1", comment.getComment()); … … 255 293 } 256 294 257 @Test 258 public void testDeleteCommentFromComponent() throws Exception { 259 fillUp(); 295 @Test //ok 296 public void testDeleteCommentFromPublicComponent() throws Exception { 297 298 fillUpPublicItems(); 299 260 300 String id = ComponentDescription.COMPONENT_PREFIX + "component1"; 261 301 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( 264 304 COMMENT_LIST_GENERICTYPE); 265 305 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())) 268 308 .get(Comment.class); 269 309 assertNotNull(aComment); … … 280 320 assertEquals(200, response.getStatus()); 281 321 282 comments = getResource().path(283 "/registry/components/" + id + "/comments/") .get(322 comments = this.getAuthenticatedResource(getResource().path( 323 "/registry/components/" + id + "/comments/")).get( 284 324 COMMENT_LIST_GENERICTYPE); 285 325 assertEquals(1, comments.size()); … … 290 330 assertEquals(200, response.getStatus()); 291 331 292 comments = getResource().path(293 "/registry/components/" + id + "/comments") .get(332 comments = this.getAuthenticatedResource(getResource().path( 333 "/registry/components/" + id + "/comments")).get( 294 334 COMMENT_LIST_GENERICTYPE); 295 335 assertEquals(0, comments.size()); … … 297 337 298 338 @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( 302 344 "/registry/components/" + ComponentDescription.COMPONENT_PREFIX 303 + "component1/comments") .get(COMMENT_LIST_GENERICTYPE);345 + "component1/comments")).get(COMMENT_LIST_GENERICTYPE); 304 346 assertEquals(2, comments.size()); 305 Comment aComment = getResource().path(347 Comment aComment = this.getAuthenticatedResource(getResource().path( 306 348 "/registry/components/" + ComponentDescription.COMPONENT_PREFIX 307 + "component1/comments/"+component1Comment3.getId()) .get(Comment.class);349 + "component1/comments/"+component1Comment3.getId())).get(Comment.class); 308 350 assertNotNull(aComment); 309 351 … … 318 360 assertEquals(200, response.getStatus()); 319 361 320 comments = getResource().path(362 comments = this.getAuthenticatedResource(getResource().path( 321 363 "/registry/components/" + ComponentDescription.COMPONENT_PREFIX 322 + "component1/comments/") .get(COMMENT_LIST_GENERICTYPE);364 + "component1/comments/")).get(COMMENT_LIST_GENERICTYPE); 323 365 assertEquals(1, comments.size()); 324 366 } 325 367 326 368 @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( 330 374 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 331 + "profile1/comments") .get(COMMENT_LIST_GENERICTYPE);375 + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE); 332 376 assertEquals(2, comments.size()); 333 Comment aComment = getResource().path(377 Comment aComment = this.getAuthenticatedResource(getResource().path( 334 378 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 335 + "profile1/comments/"+profile1Comment1.getId()) .get(Comment.class);379 + "profile1/comments/"+profile1Comment1.getId())).get(Comment.class); 336 380 assertNotNull(aComment); 337 381 … … 347 391 assertEquals(200, response.getStatus()); 348 392 349 comments = getResource().path(393 comments = this.getAuthenticatedResource(getResource().path( 350 394 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 351 + "profile1/comments/") .get(COMMENT_LIST_GENERICTYPE);395 + "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE); 352 396 assertEquals(1, comments.size()); 353 397 … … 357 401 assertEquals(200, response.getStatus()); 358 402 359 comments = getResource().path(403 comments = this.getAuthenticatedResource(getResource().path( 360 404 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 361 + "profile1/comments") .get(COMMENT_LIST_GENERICTYPE);405 + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE); 362 406 assertEquals(0, comments.size()); 363 407 } 364 408 365 409 @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( 369 415 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 370 + "profile1/comments") .get(COMMENT_LIST_GENERICTYPE);416 + "profile1/comments")).get(COMMENT_LIST_GENERICTYPE); 371 417 assertEquals(2, comments.size()); 372 Comment aComment = getResource().path(418 Comment aComment = this.getAuthenticatedResource(getResource().path( 373 419 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 374 + "profile1/comments/"+profile1Comment2.getId()) .get(Comment.class);420 + "profile1/comments/"+profile1Comment2.getId())).get(Comment.class); 375 421 assertNotNull(aComment); 376 422 … … 384 430 assertEquals(200, response.getStatus()); 385 431 386 comments = getResource().path(432 comments = this.getAuthenticatedResource(getResource().path( 387 433 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 388 + "profile1/comments/") .get(COMMENT_LIST_GENERICTYPE);434 + "profile1/comments/")).get(COMMENT_LIST_GENERICTYPE); 389 435 assertEquals(1, comments.size()); 390 436 } 391 437 392 438 @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); 397 445 assertEquals(2, components.size()); 398 CMDComponentSpec profile = getResource().path(446 CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path( 399 447 "/registry/components/" + ComponentDescription.COMPONENT_PREFIX 400 + "component1") .get(CMDComponentSpec.class);448 + "component1")).get(CMDComponentSpec.class); 401 449 assertNotNull(profile); 402 450 ClientResponse response = getAuthenticatedResource( … … 405 453 assertEquals(200, response.getStatus()); 406 454 407 components = getResource().path("/registry/components").get(455 components = this.getAuthenticatedResource(getResource().path("/registry/components")).get( 408 456 COMPONENT_LIST_GENERICTYPE); 409 457 assertEquals(1, components.size()); … … 414 462 assertEquals(200, response.getStatus()); 415 463 416 components = getResource().path("/registry/components").get(464 components = this.getAuthenticatedResource(getResource().path("/registry/components")).get( 417 465 COMPONENT_LIST_GENERICTYPE); 418 466 assertEquals(0, components.size()); … … 425 473 426 474 @Test 427 public void testDeleteRegisteredComponentStillUsed() throws Exception { 428 String content = ""; 475 public void testDeletePublicComponentStillUsed() throws Exception { 476 477 fillUpPublicItems(); 478 479 String content = ""; 429 480 content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; 430 481 content += " xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n"; … … 435 486 content += "</CMD_ComponentSpec>\n"; 436 487 ComponentDescription compDesc1 = RegistryTestHelper.addComponent( 437 getTestRegistry(), "XXX1", content);488 baseRegistry, "XXX1", content, true); 438 489 439 490 content = ""; … … 448 499 content += "</CMD_ComponentSpec>\n"; 449 500 ComponentDescription compDesc2 = RegistryTestHelper.addComponent( 450 getTestRegistry(), "YYY1", content);501 baseRegistry, "YYY1", content,true); 451 502 452 503 content = ""; … … 461 512 content += "</CMD_ComponentSpec>\n"; 462 513 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()); 468 519 469 520 ClientResponse response = getAuthenticatedResource( … … 475 526 response.getEntity(String.class)); 476 527 477 components = getResource().path("/registry/components").get(528 components = this.getAuthenticatedResource(getResource().path("/registry/components")).get( 478 529 COMPONENT_LIST_GENERICTYPE); 479 assertEquals( 2, components.size());530 assertEquals(4, components.size()); 480 531 481 532 response = getAuthenticatedResource( … … 491 542 ClientResponse.class); 492 543 assertEquals(200, response.getStatus()); 493 components = getResource().path("/registry/components").get(544 components = this.getAuthenticatedResource(getResource().path("/registry/components")).get( 494 545 COMPONENT_LIST_GENERICTYPE); 495 assertEquals(0, components.size());496 }497 498 @Test499 public void testManipulateRegisteredComponent() throws Exception {500 fillUp();501 List<ComponentDescription> components = getResource().path(502 "/registry/components").get(COMPONENT_LIST_GENERICTYPE);503 546 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( 505 558 "/registry/components/" + ComponentDescription.COMPONENT_PREFIX 506 + "component1") .get(CMDComponentSpec.class);559 + "component1")).get(CMDComponentSpec.class); 507 560 assertNotNull(profile); 508 561 … … 516 569 assertEquals(200, response.getStatus()); 517 570 518 components = getResource().path("/registry/components").get(571 components = this.getAuthenticatedResource(getResource().path("/registry/components")).get( 519 572 COMPONENT_LIST_GENERICTYPE); 520 573 assertEquals(1, components.size()); … … 529 582 @Test 530 583 public void testGetRegisteredProfile() throws Exception { 531 fillUp(); 584 585 fillUpPublicItems(); 586 532 587 String id = ProfileDescription.PROFILE_PREFIX + "profile1"; 533 588 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)) 536 591 .accept(MediaType.APPLICATION_JSON).get(CMDComponentSpec.class); 537 592 assertNotNull(profile); 538 593 assertEquals("Actor", profile.getCMDComponent().getName()); 539 profile = getResource().path("/registry/profiles/" + id2)594 profile = this.getAuthenticatedResource(getResource().path("/registry/profiles/" + id2)) 540 595 .accept(MediaType.APPLICATION_XML).get(CMDComponentSpec.class); 541 596 assertNotNull(profile); … … 547 602 548 603 try { 549 profile = getResource()604 profile = this.getAuthenticatedResource(getResource() 550 605 .path("/registry/profiles/" 551 + ProfileDescription.PROFILE_PREFIX + "profileXXXX") 606 + ProfileDescription.PROFILE_PREFIX + "profileXXXX")) 552 607 .accept(MediaType.APPLICATION_XML) 553 608 .get(CMDComponentSpec.class); … … 560 615 @Test 561 616 public void testGetRegisteredProfileRawData() throws Exception { 562 fillUp(); 563 String profile = getResource() 617 618 fillUpPublicItems(); 619 620 String profile = this.getAuthenticatedResource(getResource() 564 621 .path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 565 + "profile1/xsd") .accept(MediaType.TEXT_XML)622 + "profile1/xsd")).accept(MediaType.TEXT_XML) 566 623 .get(String.class).trim(); 567 624 assertTrue(profile … … 569 626 assertTrue(profile.endsWith("</xs:schema>")); 570 627 571 profile = getResource()628 profile = this.getAuthenticatedResource(getResource() 572 629 .path("/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 573 + "profile1/xml") .accept(MediaType.TEXT_XML)630 + "profile1/xml")).accept(MediaType.TEXT_XML) 574 631 .get(String.class).trim(); 575 632 assertTrue(profile … … 579 636 580 637 try { 581 getResource()638 this.getAuthenticatedResource(getResource() 582 639 .path("/registry/components/" 583 640 + ComponentDescription.COMPONENT_PREFIX 584 + "component1/xsl") .accept(MediaType.TEXT_XML)641 + "component1/xsl")).accept(MediaType.TEXT_XML) 585 642 .get(String.class); 586 643 fail("Should have thrown exception, unsupported path parameter"); … … 589 646 } 590 647 648 // 591 649 @Test 592 650 public void testPrivateProfileXsd() throws Exception { 651 652 fillUpPublicItems(); 653 593 654 FormDataMultiPart form = createFormData(RegistryTestHelper 594 655 .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( 598 658 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 599 659 form); … … 601 661 assertEquals(1, getUserProfiles().size()); 602 662 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")) 605 665 .accept(MediaType.TEXT_XML).get(String.class).trim(); 606 666 assertTrue(profile … … 611 671 @Test 612 672 public void testPrivateComponentXsd() throws Exception { 673 674 fillUpPublicItems(); 675 613 676 FormDataMultiPart form = createFormData(RegistryTestHelper 614 677 .getComponentTestContent()); 615 678 RegisterResponse response = getAuthenticatedResource( 616 679 getResource().path("/registry/components").queryParam( 617 USERSPACE_PARAM, "true")).type(680 REGISTRY_SPACE_PARAM, "private")).type( 618 681 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 619 682 form); … … 621 684 assertEquals(1, getUserComponents().size()); 622 685 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")) 625 688 .accept(MediaType.TEXT_XML).get(String.class).trim(); 626 689 assertTrue(profile … … 631 694 @Test 632 695 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); 636 701 assertEquals(2, profiles.size()); 637 CMDComponentSpec profile = getResource().path(702 CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path( 638 703 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 639 + "profile1") .get(CMDComponentSpec.class);704 + "profile1")).get(CMDComponentSpec.class); 640 705 assertNotNull(profile); 641 706 … … 645 710 assertEquals(200, response.getStatus()); 646 711 647 profiles = getResource().path("/registry/profiles").get(712 profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get( 648 713 PROFILE_LIST_GENERICTYPE); 649 714 assertEquals(1, profiles.size()); … … 654 719 assertEquals(200, response.getStatus()); 655 720 656 profiles = getResource().path("/registry/profiles").get(721 profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get( 657 722 PROFILE_LIST_GENERICTYPE); 658 723 assertEquals(0, profiles.size()); … … 661 726 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 662 727 + "profile1").delete(ClientResponse.class); 663 assertEquals( 200, response.getStatus());728 assertEquals(404, response.getStatus()); 664 729 } 665 730 666 731 @Test 667 732 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); 671 738 assertEquals(2, profiles.size()); 672 CMDComponentSpec profile = getResource().path(739 CMDComponentSpec profile = this.getAuthenticatedResource(getResource().path( 673 740 "/registry/profiles/" + ProfileDescription.PROFILE_PREFIX 674 + "profile1") .get(CMDComponentSpec.class);741 + "profile1")).get(CMDComponentSpec.class); 675 742 assertNotNull(profile); 676 743 … … 684 751 assertEquals(200, response.getStatus()); 685 752 686 profiles = getResource().path("/registry/profiles").get(753 profiles = this.getAuthenticatedResource(getResource().path("/registry/profiles")).get( 687 754 PROFILE_LIST_GENERICTYPE); 688 755 assertEquals(1, profiles.size()); … … 697 764 @Test 698 765 public void testGetRegisteredComponentRawData() throws Exception { 699 fillUp(); 766 767 fillUpPublicItems(); 768 700 769 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")) 703 772 .accept(MediaType.TEXT_XML).get(String.class).trim(); 704 773 assertTrue(component … … 706 775 assertTrue(component.endsWith("</xs:schema>")); 707 776 708 component = getResource().path("/registry/components/" + id + "/xml")777 component = this.getAuthenticatedResource(getResource().path("/registry/components/" + id + "/xml")) 709 778 .accept(MediaType.TEXT_XML).get(String.class).trim(); 710 779 assertTrue(component … … 714 783 715 784 try { 716 getResource()785 this.getAuthenticatedResource(getResource() 717 786 .path("/registry/components/" 718 787 + ComponentDescription.COMPONENT_PREFIX 719 + "component1/jpg") .accept(MediaType.TEXT_XML)788 + "component1/jpg")).accept(MediaType.TEXT_XML) 720 789 .get(String.class); 721 790 fail("Should have thrown exception, unsopported path parameter"); … … 726 795 @Test 727 796 public void testRegisterProfile() throws Exception { 797 798 fillUpPublicItems(); 799 728 800 FormDataMultiPart form = new FormDataMultiPart(); 729 801 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, … … 742 814 RegisterResponse.class, form); 743 815 assertTrue(response.isProfile()); 744 assert False(response.isInUserSpace());816 assertTrue(response.isInUserSpace()); 745 817 ProfileDescription profileDesc = (ProfileDescription) response 746 818 .getDescription(); … … 762 834 @Test 763 835 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() 766 842 .size()); 767 843 FormDataMultiPart form = createFormData( 768 844 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( 772 846 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 773 847 form); … … 775 849 BaseDescription desc = response.getDescription(); 776 850 assertEquals("Unpublished", desc.getDescription()); 777 assertEquals( 1, getUserProfiles().size());778 assertEquals( 0, getPublicProfiles().size());851 assertEquals(2, getUserProfiles().size()); 852 assertEquals(2, getPublicProfiles().size()); 779 853 form = createFormData( 780 854 RegistryTestHelper.getTestProfileContent("publishedName"), 781 855 "Published"); 782 response = getAuthenticatedResource( 783 getResource().path( 856 response = getAuthenticatedResource(getResource().path( 784 857 "/registry/profiles/" + desc.getId() + "/publish")) 785 858 .type(MediaType.MULTIPART_FORM_DATA).post( 786 859 RegisterResponse.class, form); 787 860 788 assertEquals( 0, getUserProfiles().size());861 assertEquals(1, getUserProfiles().size()); 789 862 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); 792 865 assertNotNull(profileDescription.getId()); 793 866 assertEquals(desc.getId(), profileDescription.getId()); … … 801 874 private CMDComponentSpec getPublicSpec(BaseDescription desc) { 802 875 if (desc.isProfile()) { 803 return getResource().path("/registry/profiles/" + desc.getId())876 return this.getAuthenticatedResource(getResource().path("/registry/profiles/" + desc.getId())) 804 877 .get(CMDComponentSpec.class); 805 878 } else { 806 return getResource().path("/registry/components/" + desc.getId())879 return this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())) 807 880 .get(CMDComponentSpec.class); 808 881 } … … 810 883 811 884 @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 815 893 FormDataMultiPart form = createFormData( 816 894 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( 820 896 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 821 897 form); … … 823 899 BaseDescription desc = response.getDescription(); 824 900 assertEquals("Unpublished", desc.getDescription()); 825 assertEquals( 1, getUserComponents().size());826 assertEquals( 0, getPublicComponents().size());901 assertEquals(2, getUserComponents().size()); 902 assertEquals(2, getPublicComponents().size()); 827 903 form = createFormData( 828 904 RegistryTestHelper.getComponentTestContentAsStream("publishedName"), 829 905 "Published"); 830 response = getAuthenticatedResource( 831 getResource().path( 906 response = getAuthenticatedResource(getResource().path( 832 907 "/registry/components/" + desc.getId() + "/publish")) 833 908 .type(MediaType.MULTIPART_FORM_DATA).post( 834 909 RegisterResponse.class, form); 835 910 836 assertEquals( 0, getUserComponents().size());911 assertEquals(1, getUserComponents().size()); 837 912 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); 840 915 assertNotNull(componentDescription.getId()); 841 916 assertEquals(desc.getId(), componentDescription.getId()); … … 848 923 } 849 924 925 // duplicates ("extendedly") testRegisterProfile, since you can pot only in user space, and then publish or move to group or so 850 926 @Test 851 927 public void testRegisterUserspaceProfile() throws Exception { 928 929 fillUpPrivateItems(); 930 fillUpPublicItems(); 931 852 932 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() 855 935 .size()); 856 936 FormDataMultiPart form = createFormData(RegistryTestHelper 857 937 .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( 861 939 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 862 940 form); … … 875 953 assertEquals( 876 954 "http://localhost:9998/registry/profiles/" 877 + profileDesc.getId() + "?userspace=true",955 + profileDesc.getId(), 878 956 profileDesc.getHref()); 879 957 880 958 profiles = getUserProfiles(); 881 assertEquals( 1, profiles.size());882 assertEquals( 0, getPublicProfiles().size());959 assertEquals(2, profiles.size()); 960 assertEquals(2, getPublicProfiles().size()); 883 961 884 962 // Try to post unauthenticated 885 963 ClientResponse cResponse = getResource().path("/registry/profiles") 886 .queryParam(USERSPACE_PARAM, "true")887 964 .type(MediaType.MULTIPART_FORM_DATA) 888 965 .post(ClientResponse.class, form); 889 966 assertEquals(401, cResponse.getStatus()); 890 967 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( 900 972 MediaType.APPLICATION_XML).get(CMDComponentSpec.class); 901 973 assertNotNull(spec); 902 974 903 cResponse = getResource()904 .path("/registry/profiles/" + profileDesc.getId() + "/xsd") 975 cResponse = this.getAuthenticatedResource(getResource() 976 .path("/registry/profiles/" + profileDesc.getId() + "/xsd")) 905 977 .accept(MediaType.TEXT_XML).get(ClientResponse.class); 906 978 assertEquals(200, cResponse.getStatus()); … … 908 980 assertTrue(profile.length() > 0); 909 981 910 profile = getAuthenticatedResource( 911 getResource().path( 982 profile = getAuthenticatedResource(getResource().path( 912 983 "/registry/profiles/" + profileDesc.getId() + "/xml")) 913 984 .accept(MediaType.TEXT_XML).get(String.class); 914 985 assertTrue(profile.length() > 0); 915 986 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( 919 989 ClientResponse.class); 920 990 assertEquals(200, cResponse.getStatus()); 921 991 922 992 profiles = getUserProfiles(); 923 assertEquals( 0, profiles.size());993 assertEquals(1, profiles.size()); 924 994 } 925 995 … … 930 1000 931 1001 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( 935 1004 MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE); 936 1005 } … … 954 1023 @Test 955 1024 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 959 1028 String content = ""; 960 1029 content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; … … 966 1035 content += "</CMD_ComponentSpec>\n"; 967 1036 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 970 1040 content = ""; 971 1041 content += "<CMD_ComponentSpec isProfile=\"false\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; … … 982 1052 "/registry/components").type(MediaType.MULTIPART_FORM_DATA) 983 1053 .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 996 1055 assertTrue(response.isRegistered()); 997 ComponentDescription comp2 = (ComponentDescription) response 998 .getDescription(); 999 1056 1057 1058 /// profiles /// 1000 1059 content = ""; 1001 1060 content += "<CMD_ComponentSpec isProfile=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; … … 1003 1062 content += " <Header/>\n"; 1004 1063 content += " <CMD_Component name=\"ZZZ\" CardinalityMin=\"1\" CardinalityMax=\"unbounded\">\n"; 1005 content += " <CMD_Component ComponentId=\"" + comp 2.getId()1064 content += " <CMD_Component ComponentId=\"" + compDesc1.getId() 1006 1065 + "\" CardinalityMin=\"0\" CardinalityMax=\"99\">\n"; 1007 1066 content += " </CMD_Component>\n"; … … 1013 1072 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 1014 1073 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);1027 1074 assertTrue(response.isRegistered()); 1075 1028 1076 } 1029 1077 1030 1078 @Test 1031 1079 public void testRegisterUserspaceComponent() throws Exception { 1080 1081 fillUpPrivateItems(); 1082 1032 1083 List<ComponentDescription> components = getUserComponents(); 1033 assertEquals("user registered components", 0, components.size());1084 assertEquals("user registered components", 1, components.size()); 1034 1085 assertEquals("public registered components", 0, getPublicComponents() 1035 1086 .size()); … … 1037 1088 .getComponentTestContent()); 1038 1089 1039 RegisterResponse response = getAuthenticatedResource( 1040 getResource().path("/registry/components").queryParam( 1041 USERSPACE_PARAM, "true")).type( 1090 RegisterResponse response = getAuthenticatedResource(getResource().path("/registry/components")).type( 1042 1091 MediaType.MULTIPART_FORM_DATA).post(RegisterResponse.class, 1043 1092 form); … … 1057 1106 assertNotNull(desc.getRegistrationDate()); 1058 1107 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()); 1061 1109 1062 1110 components = getUserComponents(); 1063 assertEquals( 1, components.size());1111 assertEquals(2, components.size()); 1064 1112 assertEquals(0, getPublicComponents().size()); 1065 1113 1066 1114 // Try to post unauthenticated 1067 1115 ClientResponse cResponse = getResource().path("/registry/components") 1068 .queryParam(USERSPACE_PARAM, "true")1069 1116 .type(MediaType.MULTIPART_FORM_DATA) 1070 1117 .post(ClientResponse.class, form); 1071 1118 assertEquals(401, cResponse.getStatus()); 1072 1119 1073 // Try to get from public registry1074 cResponse = getResource().path("/registry/components/" + desc.getId())1120 // Try to get 1121 cResponse = this.getAuthenticatedResource(getResource().path("/registry/components/" + desc.getId())) 1075 1122 .accept(MediaType.APPLICATION_XML).get(ClientResponse.class); 1076 // Should return 404 = not found1077 assertEquals( 404, cResponse.getStatus());1123 1124 assertEquals(200, cResponse.getStatus()); 1078 1125 CMDComponentSpec spec = getUserComponent(desc); 1079 1126 assertNotNull(spec); 1080 1127 1081 cResponse = getResource()1082 .path("/registry/components/" + desc.getId() + "/xsd") 1128 cResponse = this.getAuthenticatedResource(getResource() 1129 .path("/registry/components/" + desc.getId() + "/xsd")) 1083 1130 .accept(MediaType.TEXT_XML).get(ClientResponse.class); 1084 1131 assertEquals(200, cResponse.getStatus()); … … 1086 1133 assertTrue(result.length() > 0); 1087 1134 1088 result = getAuthenticatedResource( 1089 getResource().path( 1135 result = getAuthenticatedResource(getResource().path( 1090 1136 "/registry/components/" + desc.getId() + "/xml")) 1091 1137 .accept(MediaType.TEXT_XML).get(String.class); 1092 1138 assertTrue(result.length() > 0); 1093 1139 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( 1097 1141 ClientResponse.class); 1098 1142 assertEquals(200, cResponse.getStatus()); 1099 1143 1100 1144 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(); 1106 1152 // Create new componet 1107 1153 FormDataMultiPart form = createFormData(RegistryTestHelper 1108 1154 .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( 1112 1156 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1113 1157 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1140 1184 RegistryTestHelper.getComponentContentAsStream(compContent), 1141 1185 "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( 1146 1188 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1147 1189 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1159 1201 1160 1202 @Test 1161 public void testUpdateComponent() throws Exception { 1203 public void testUpdatePrivateComponent() throws Exception { 1204 1205 fillUpPrivateItems(); 1206 1162 1207 List<ComponentDescription> components = getUserComponents(); 1163 assertEquals("user registered components", 0, components.size());1208 assertEquals("user registered components", 1, components.size()); 1164 1209 assertEquals("public registered components", 0, getPublicComponents() 1165 1210 .size()); 1166 1211 1212 // first, post a component to update 1167 1213 FormDataMultiPart form = createFormData(RegistryTestHelper 1168 1214 .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( 1172 1216 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1173 1217 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1187 1231 assertEquals("Access", spec.getCMDComponent().getName()); 1188 1232 components = getUserComponents(); 1189 assertEquals( 1, components.size());1233 assertEquals(2, components.size()); 1190 1234 assertEquals(0, getPublicComponents().size()); 1191 1235 1192 // Now update1236 // second, now update 1193 1237 form = createFormData( 1194 1238 RegistryTestHelper.getComponentTestContentAsStream("TESTNAME"), 1195 1239 "UPDATE DESCRIPTION!"); 1196 cResponse = getAuthenticatedResource( 1197 getResource().path( 1240 cResponse = getAuthenticatedResource(getResource().path( 1198 1241 "/registry/components/" + desc.getId() + "/update") 1199 .queryParam( USERSPACE_PARAM, "true")).type(1242 .queryParam(REGISTRY_SPACE_PARAM, "private")).type( 1200 1243 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1201 1244 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1216 1259 assertEquals("TESTNAME", spec.getCMDComponent().getName()); 1217 1260 components = getUserComponents(); 1218 assertEquals( 1, components.size());1261 assertEquals(2, components.size()); 1219 1262 assertEquals(0, getPublicComponents().size()); 1220 1263 } 1221 1264 1222 1265 @Test 1223 public void testUpdateProfile() throws Exception { 1266 public void testUpdatePrivateProfile() throws Exception { 1267 1268 fillUpPrivateItems(); 1269 1224 1270 List<ProfileDescription> profiles = getUserProfiles(); 1225 assertEquals( 0, profiles.size());1271 assertEquals(1, profiles.size()); 1226 1272 assertEquals(0, getPublicProfiles().size()); 1227 1273 1228 1274 FormDataMultiPart form = createFormData(RegistryTestHelper 1229 1275 .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( 1233 1277 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1234 1278 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1249 1293 assertEquals("Actor", spec.getCMDComponent().getName()); 1250 1294 profiles = getUserProfiles(); 1251 assertEquals( 1, profiles.size());1295 assertEquals(2, profiles.size()); 1252 1296 assertEquals(0, getPublicComponents().size()); 1253 1297 … … 1256 1300 RegistryTestHelper.getTestProfileContent("TESTNAME"), 1257 1301 "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( 1262 1304 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1263 1305 assertEquals(ClientResponse.Status.OK.getStatusCode(), … … 1278 1320 assertEquals("TESTNAME", spec.getCMDComponent().getName()); 1279 1321 profiles = getUserProfiles(); 1280 assertEquals( 1, profiles.size());1322 assertEquals(2, profiles.size()); 1281 1323 assertEquals(0, getPublicComponents().size()); 1282 1324 } 1283 1325 1284 1326 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( 1288 1329 MediaType.APPLICATION_XML).get(CMDComponentSpec.class); 1289 1330 } 1290 1331 1291 1332 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( 1295 1335 MediaType.APPLICATION_XML).get(CMDComponentSpec.class); 1296 1336 } … … 1302 1342 1303 1343 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( 1307 1346 MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE); 1308 1347 } … … 1310 1349 @Test 1311 1350 public void testRegisterComponent() throws Exception { 1351 1352 fillUpPrivateItems(); 1353 1312 1354 FormDataMultiPart form = new FormDataMultiPart(); 1313 1355 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, … … 1326 1368 assertTrue(response.isRegistered()); 1327 1369 assertFalse(response.isProfile()); 1328 assert False(response.isInUserSpace());1370 assertTrue(response.isInUserSpace()); 1329 1371 ComponentDescription desc = (ComponentDescription) response 1330 1372 .getDescription(); … … 1346 1388 @Test 1347 1389 public void testRegisterComment() throws Exception { 1390 1391 fillUpPublicItems(); 1392 1348 1393 FormDataMultiPart form = new FormDataMultiPart(); 1349 1394 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, 1350 1395 RegistryTestHelper.getCommentTestContent(), 1351 1396 MediaType.APPLICATION_OCTET_STREAM_TYPE); 1352 fillUp();1353 1397 String id = ProfileDescription.PROFILE_PREFIX + "profile1"; 1354 1398 CommentResponse response = getAuthenticatedResource( … … 1371 1415 @Test 1372 1416 public void testRegisterCommentToNonExistent() throws Exception { 1417 fillUpPublicItems(); 1418 1373 1419 FormDataMultiPart form = new FormDataMultiPart(); 1374 1420 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, 1375 1421 RegistryTestHelper.getCommentTestContent(), 1376 1422 MediaType.APPLICATION_OCTET_STREAM_TYPE); 1377 fillUp();1378 1423 ClientResponse cResponse = getAuthenticatedResource( 1379 1424 "/registry/profiles/clarin.eu:cr1:profile99/comments").type( 1380 1425 MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); 1381 assertEquals( 500, cResponse.getStatus());1426 assertEquals(404, cResponse.getStatus()); 1382 1427 } 1383 1428 1384 1429 @Test 1385 1430 public void testRegisterCommentUnauthenticated() throws Exception { 1431 fillUpPublicItems(); 1432 1386 1433 FormDataMultiPart form = new FormDataMultiPart(); 1387 1434 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, 1388 1435 RegistryTestHelper.getCommentTestContent(), 1389 1436 MediaType.APPLICATION_OCTET_STREAM_TYPE); 1390 fillUp();1391 1437 ClientResponse cResponse = getResource() 1392 1438 .path("/registry/profiles/clarin.eu:cr1:profile1/comments") … … 1398 1444 @Test 1399 1445 public void testRegisterProfileInvalidData() throws Exception { 1446 fillUpPrivateItems(); 1400 1447 FormDataMultiPart form = new FormDataMultiPart(); 1401 1448 String notAValidProfile = "<CMD_ComponentSpec> </CMD_ComponentSpec>"; … … 1426 1473 @Test 1427 1474 public void testRegisterInvalidProfile() throws Exception { 1475 fillUpPrivateItems(); 1428 1476 FormDataMultiPart form = new FormDataMultiPart(); 1429 1477 String profileContent = ""; … … 1469 1517 public void testRegisterProfileInvalidDescriptionAndContent() 1470 1518 throws Exception { 1519 fillUpPrivateItems(); 1471 1520 FormDataMultiPart form = new FormDataMultiPart(); 1472 1521 String profileContent = ""; … … 1499 1548 @Test 1500 1549 public void testRegisterLargeProfile() throws Exception { 1550 //fillUpPrivateItems(); not necessary 1501 1551 FormDataMultiPart form = new FormDataMultiPart(); 1502 1552 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, … … 1519 1569 @Test 1520 1570 public void testRegisterComponentAsProfile() throws Exception { 1571 //fillUpPrivateItems();; not necessary 1521 1572 FormDataMultiPart form = new FormDataMultiPart(); 1522 1573 form.field(IComponentRegistryRestService.DATA_FORM_FIELD, … … 1641 1692 @Test 1642 1693 public void testGetDescription() throws Exception{ 1643 fillUp ();1644 1694 fillUpPublicItems(); 1695 String id = ComponentDescription.COMPONENT_PREFIX + "component1"; 1645 1696 ComponentDescription component = getAuthenticatedResource(getResource().path("/registry/items/" + id)).accept(MediaType.APPLICATION_JSON).get(ComponentDescription.class); 1646 1697 assertNotNull(component); -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java
r4098 r5549 1 1 package clarin.cmdi.componentregistry.rest; 2 2 3 import clarin.cmdi.componentregistry.RegistrySpace; 3 4 import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase; 4 5 import clarin.cmdi.componentregistry.model.BaseDescription; … … 20 21 21 22 import org.junit.Before; 22 import org.junit.BeforeClass;23 23 import org.junit.Test; 24 24 import org.slf4j.Logger; … … 27 27 import org.springframework.jdbc.core.JdbcTemplate; 28 28 29 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService. USERSPACE_PARAM;29 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.REGISTRY_SPACE_PARAM; 30 30 import static org.junit.Assert.*; 31 31 … … 58 58 List<Thread> ts = new ArrayList<Thread>(); 59 59 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); 65 67 runAllThreads(ts); 66 68 if (errors.size() > 0) { … … 70 72 fail(); 71 73 } 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) { 80 82 List<ProfileDescription> response = getAuthenticatedResource( 81 83 getResource().path("/registry/profiles").queryParam( 82 USERSPACE_PARAM, "" + userSpace)).accept(84 REGISTRY_SPACE_PARAM, registrySpace.name())).accept( 83 85 MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE); 84 86 Collections.sort(response, descriptionComparator); … … 101 103 }; 102 104 103 private void assertComponents(int nrOfComponents, boolean userSpace) {105 private void assertComponents(int nrOfComponents, RegistrySpace registrySpace) { 104 106 List<ComponentDescription> cResponse = getAuthenticatedResource( 105 107 getResource().path("/registry/components").queryParam( 106 USERSPACE_PARAM, "" + userSpace)).accept(108 REGISTRY_SPACE_PARAM, registrySpace.name())).accept( 107 109 MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE); 108 110 Collections.sort(cResponse, descriptionComparator); … … 128 130 129 131 private void registerProfiles(List<Thread> ts, int size, 130 final List<String> errors, boolean userSpace)132 final List<String> errors, RegistrySpace registrySpace) 131 133 throws InterruptedException { 132 134 for (int i = 0; i < size; i++) { … … 134 136 LOG.debug("Profile {} should be registered in {} and {}", 135 137 new Object[] { i + 1000, 136 userSpace ? "user space" : "public space",138 registrySpace.name(), 137 139 shouldDelete ? "ALSO DELETED" : "not deleted" }); 138 Thread thread = createThread("/registry/profiles/", userSpace,140 Thread thread = createThread("/registry/profiles/", registrySpace, 139 141 "Test Profile" + (i + 1000), shouldDelete, 140 142 RegistryTestHelper.getTestProfileContent(), errors); … … 144 146 145 147 private void registerComponents(List<Thread> ts, int size, 146 final List<String> errors, boolean userSpace)148 final List<String> errors, RegistrySpace registrySpace) 147 149 throws InterruptedException { 148 150 for (int i = 0; i < size; i++) { … … 150 152 LOG.debug("Component {} should be registered in {} and {}", 151 153 new Object[] { i + 1000, 152 userSpace ? "user space" : "public space",154 registrySpace.name(), 153 155 shouldDelete ? "ALSO DELETED" : "not deleted" }); 154 Thread thread = createThread("/registry/components/", userSpace,156 Thread thread = createThread("/registry/components/", registrySpace, 155 157 "Test Component" + (i + 1000), shouldDelete, 156 158 RegistryTestHelper.getComponentTestContent(), errors); … … 159 161 } 160 162 161 private Thread createThread(final String path, final boolean userSpace,163 private Thread createThread(final String path, final RegistrySpace registrySpace, 162 164 final String name, final boolean alsoDelete, InputStream content, 163 165 final List<String> errors) throws InterruptedException { … … 176 178 // System.out.println("THREAD STARTED"+Thread.currentThread().getName()); 177 179 RegisterResponse registerResponse = getAuthenticatedResource( 178 getResource().path(path).queryParam( 179 USERSPACE_PARAM, "" + userSpace)).type( 180 getResource().path(path)).type( 180 181 MediaType.MULTIPART_FORM_DATA).post( 181 182 RegisterResponse.class, form); … … 188 189 + "] REGISTERING DESCRIPTION " + name + " " 189 190 + registerResponse.getDescription().getId() 190 + (Boolean.valueOf(userSpace) ? " userspace" : "")191 + registrySpace.name() 191 192 + (alsoDelete ? " alsoDelete" : "")); 192 193 if (alsoDelete) { … … 197 198 + " " 198 199 + registerResponse.getDescription().getId() 199 + (Boolean.valueOf(userSpace) ? " userspace " 200 : "") 200 + registrySpace.name() 201 201 + (alsoDelete ? " alsoDelete" : "")); 202 202 ClientResponse response = getAuthenticatedResource( … … 205 205 + registerResponse 206 206 .getDescription() 207 .getId()).queryParam( 208 USERSPACE_PARAM, "" + userSpace)) 207 .getId())) 209 208 .delete(ClientResponse.class); 210 209 if (response.getStatus() != 200) { -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java
r4550 r5549 4 4 import clarin.cmdi.componentregistry.ComponentRegistry; 5 5 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 6 import clarin.cmdi.componentregistry.ComponentStatus; 7 import clarin.cmdi.componentregistry.MDMarshaller; 6 import clarin.cmdi.componentregistry.OwnerUser; 7 import clarin.cmdi.componentregistry.RegistrySpace; 8 import clarin.cmdi.componentregistry.UserUnauthorizedException; 8 9 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 9 import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;10 10 import clarin.cmdi.componentregistry.model.ComponentDescription; 11 11 import clarin.cmdi.componentregistry.model.ProfileDescription; 12 12 import clarin.cmdi.componentregistry.model.RegistryUser; 13 13 import java.io.ByteArrayInputStream; 14 14 import java.io.InputStream; … … 17 17 18 18 import org.junit.Before; 19 import org.junit.Ignore; 19 20 import org.junit.Test; 20 21 import org.springframework.beans.factory.annotation.Autowired; 21 import org.springframework.jdbc.core.JdbcTemplate; 22 23 import static org.junit.Assert.*; 22 24 23 25 24 /** … … 31 30 32 31 @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 36 39 @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{ 49 57 String profileContent = ""; 50 58 profileContent += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; … … 93 101 94 102 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); 97 105 assertFalse(validator.validate()); 98 106 assertEquals(4, validator.getErrorMessages().size()); … … 115 123 116 124 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 127 136 public void testValidateComponentIdNotRegistered() throws Exception { 128 137 String id1 = "component1"; … … 144 153 profileContent += "</CMD_ComponentSpec>"; 145 154 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); 148 158 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); 164 170 validator = new MDValidator(new ByteArrayInputStream( 165 profileContent.getBytes()), desc, publicRegistry, null,166 publicRegistry, marshaller);171 profileContent.getBytes()), desc, testRegistry 172 , marshaller); 167 173 assertFalse(validator.validate()); 168 174 assertEquals(1, validator.getErrorMessages().size()); … … 170 176 .getErrorMessages() 171 177 .get(0) 172 .startsWith(MDValidator.COMPONENT_NOT_ PUBLICLY_REGISTERED_ERROR));173 174 // id2 is added , no more errors shoud be return175 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); 176 182 validator = new MDValidator(new ByteArrayInputStream( 177 profileContent.getBytes()), desc, publicRegistry, null, 178 publicRegistry, marshaller); 183 profileContent.getBytes()), desc, testRegistry, marshaller); 179 184 assertTrue("component is registered should be valid now", 180 185 validator.validate()); … … 183 188 184 189 @Test 185 public void testValidate UserRegistry() throws Exception {190 public void testValidateBaseAndUserRegistry() throws Exception { 186 191 String id1 = "component1"; 187 192 String id2 = "component2"; 188 ComponentRegistry userRegistry = componentRegistryFactory189 .getComponentRegistry(ComponentStatus.PRIVATE, null,190 DummyPrincipal.DUMMY_CREDENTIALS);191 193 192 194 String profileContent = ""; … … 205 207 profileContent += "</CMD_ComponentSpec>"; 206 208 209 // Public Registry 207 210 ProfileDescription desc = ProfileDescription.createNewDescription(); 208 211 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 213 215 assertTrue(validator.getErrorMessages().get(0) 214 216 .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); 220 231 validator = new MDValidator(new ByteArrayInputStream( 221 profileContent.getBytes()), desc, publicRegistry, null, 222 publicRegistry, marshaller); 232 profileContent.getBytes()), desc, testRegistry, marshaller); 223 233 assertFalse(validator.validate()); 224 234 assertEquals(1, validator.getErrorMessages().size()); … … 226 236 .getErrorMessages() 227 237 .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 230 246 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); 234 250 assertEquals(0, validator.getErrorMessages().size()); 235 251 } … … 254 270 ComponentDescription desc = ComponentDescription.createNewDescription(); 255 271 MDValidator validator = new MDValidator(new ByteArrayInputStream( 256 content.getBytes()), desc, publicRegistry, null, 257 publicRegistry, marshaller); 272 content.getBytes()), desc, testRegistry, marshaller); 258 273 assertFalse(validator.validate()); 259 274 assertEquals(1, validator.getErrorMessages().size()); … … 261 276 .getErrorMessages() 262 277 .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); 266 281 validator = new MDValidator( 267 new ByteArrayInputStream(content.getBytes()), desc, 268 publicRegistry, null, publicRegistry, marshaller); 282 new ByteArrayInputStream(content.getBytes()), desc,testRegistry, marshaller); 269 283 assertTrue(validator.validate()); 270 284 assertEquals(0, validator.getErrorMessages().size()); … … 280 294 281 295 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); 284 297 285 298 // Spec is created during validation, before it should be null … … 309 322 InputStream input = new ByteArrayInputStream(profileContent.getBytes()); 310 323 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); 313 327 return validator; 314 328 } -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/RegistryTestHelper.java
r4098 r5549 16 16 import clarin.cmdi.componentregistry.ComponentRegistry; 17 17 import clarin.cmdi.componentregistry.DatesHelper; 18 import clarin.cmdi.componentregistry.ItemNotFoundException; 18 19 import clarin.cmdi.componentregistry.MDMarshaller; 20 import clarin.cmdi.componentregistry.UserUnauthorizedException; 19 21 import clarin.cmdi.componentregistry.components.CMDComponentSpec; 20 22 import clarin.cmdi.componentregistry.model.Comment; … … 27 29 import java.io.InputStreamReader; 28 30 29 import javax.xml.transform.TransformerException;30 31 import org.junit.Before;32 import org.junit.BeforeClass;33 31 import org.springframework.beans.factory.annotation.Autowired; 34 32 … … 46 44 } 47 45 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, 53 51 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, 58 56 JAXBException { 59 57 ComponentDescription desc = ComponentDescription.createNewDescription(); 60 58 desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName()); 61 desc.setUserId(DummyPrincipal.DUMMY_CREDENTIALS.getPrincipalName());59 desc.setUserId(DummyPrincipal.DUMMY_PRINCIPAL.getName()); 62 60 desc.setName(id); 63 61 desc.setDescription("Test Description"); 64 62 desc.setId(ComponentDescription.COMPONENT_PREFIX + id); 65 63 desc.setHref("link:" + desc.getId()); 64 desc.setPublic(isPublic); 66 65 CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema()); 67 66 testRegistry.register(desc, spec); … … 104 103 } 105 104 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 { 117 116 ProfileDescription desc = ProfileDescription.createNewDescription(); 118 117 desc.setCreatorName(DummyPrincipal.DUMMY_CREDENTIALS.getDisplayName()); … … 122 121 desc.setId(ProfileDescription.PROFILE_PREFIX + id); 123 122 desc.setHref("link:" + ProfileDescription.PROFILE_PREFIX + id); 123 desc.setPublic(isPublic); 124 124 CMDComponentSpec spec = marshaller.unmarshal(CMDComponentSpec.class, content, marshaller.getCMDComponentSchema()); 125 125 testRegistry.register(desc, spec); … … 216 216 } 217 217 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 { 219 219 return addComment(testRegistry, RegistryTestHelper.getTestCommentContent(id, descriptionId), principal); 220 220 } … … 222 222 private static Comment addComment(ComponentRegistry testRegistry, InputStream content, String principal) throws ParseException, 223 223 JAXBException, 224 ComponentRegistryException {224 ComponentRegistryException, ItemNotFoundException,UserUnauthorizedException { 225 225 Comment spec = marshaller.unmarshal(Comment.class, content, null); 226 226 testRegistry.registerComment(spec, principal); -
ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rss/PrintXmlFromRssRunner.java
r4098 r5549 5 5 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 6 6 import clarin.cmdi.componentregistry.DatesHelper; 7 import clarin.cmdi.componentregistry.ItemNotFoundException; 7 8 import clarin.cmdi.componentregistry.MDMarshaller; 9 import clarin.cmdi.componentregistry.UserUnauthorizedException; 8 10 import clarin.cmdi.componentregistry.impl.ComponentUtils; 9 11 import clarin.cmdi.componentregistry.model.BaseDescription; … … 20 22 21 23 import javax.xml.bind.JAXBException; 22 import javax.xml.transform.TransformerException;23 24 import org.junit.BeforeClass;25 24 import org.springframework.beans.factory.annotation.Autowired; 26 25 import org.springframework.context.ApplicationContext; … … 93 92 * input: sort of rss -- profiles, or comopnents, or comments (see below the prompt string) 94 93 */ 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 { 96 95 97 96 System.out.println("Type 1 or 2, or 3, or 4, \n " … … 137 136 System.exit(1); 138 137 } 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(); 141 140 rss = makeRssForComments(comments, kind, baseUri, 10, buffer, name); 142 141
Note: See TracChangeset
for help on using the changeset viewer.