Changeset 2287
- Timestamp:
- 10/05/12 11:47:03 (12 years ago)
- Location:
- ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src
- Files:
-
- 12 edited
Legend:
- Unmodified
- Added
- Removed
-
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreator.java
r2286 r2287 2 2 3 3 import clarin.cmdi.componentregistry.model.AbstractDescription; 4 import clarin.cmdi.componentregistry.rest.ComponentRegistryRestService;5 4 import clarin.cmdi.componentregistry.rss.Category; 6 5 import clarin.cmdi.componentregistry.rss.Cloud; … … 9 8 import clarin.cmdi.componentregistry.rss.Rss; 10 9 import clarin.cmdi.componentregistry.rss.RssChannel; 11 12 10 import clarin.cmdi.componentregistry.rss.RssItem; 13 11 import clarin.cmdi.componentregistry.rss.SkipDaysList; … … 18 16 import java.text.SimpleDateFormat; 19 17 import java.util.ArrayList; 20 import java.util.Comparator;21 18 import java.util.Date; 22 19 import java.util.List; 23 import javax.xml.bind.DatatypeConverter;24 import org.slf4j.Logger;25 import org.slf4j.LoggerFactory;26 20 27 21 /** … … 31 25 public abstract class RssCreator<T> { // extends nothing so far, throuw nothing // make it abstract 32 26 33 34 27 private String title; 35 28 private String link; … … 54 47 private double version = 2.0; // of an rss 55 48 56 57 58 49 public double getVersion() { 59 50 return (version); 60 51 } 61 52 … … 65 56 */ 66 57 public void setVersion(double version) { 67 58 this.version = version; 68 59 } 69 60 … … 75 66 */ 76 67 public void setTitle(String value) { 77 68 this.title = value; 78 69 } 79 70 80 71 public String getTitle() { 81 72 return this.title; 82 73 } 83 74 … … 89 80 */ 90 81 public void setLink(String value) { 91 82 this.link = value; 92 83 } 93 84 94 85 public String getLink() { 95 86 return this.link; 96 87 } 97 88 … … 110 101 */ 111 102 public void setDescription(String value) { 112 103 this.description = value; 113 104 } 114 105 … … 120 111 */ 121 112 public void setLanguage(String value) { 122 113 this.language = value; 123 114 } 124 115 … … 130 121 */ 131 122 public void setCopyright(String value) { 132 123 this.copyright = value; 133 124 } 134 125 … … 140 131 */ 141 132 public void setManagingEditor(String value) { 142 133 this.managingEditor = value; 143 134 } 144 135 … … 150 141 */ 151 142 public void setWebMaster(String value) { 152 143 this.webMaster = value; 153 144 } 154 145 … … 160 151 */ 161 152 public void setPubDate(String value) { 162 153 this.pubDate = value; 163 154 } 164 155 … … 170 161 */ 171 162 public void setLastBuildDate(String value) { 172 163 this.lastBuildDate = value; 173 164 } 174 165 … … 180 171 */ 181 172 public void setCategory(Category value) { 182 173 this.category = value; 183 174 } 184 175 … … 190 181 */ 191 182 public void setGenerator(String value) { 192 183 this.generator = value; 193 184 } 194 185 … … 200 191 */ 201 192 public void setDocs(String value) { 202 193 this.docs = value; 203 194 } 204 195 … … 210 201 */ 211 202 public void setCloud(Cloud value) { 212 203 this.cloud = value; 213 204 } 214 205 … … 220 211 */ 221 212 public void setTtl(BigInteger value) { 222 213 this.ttl = value; 223 214 } 224 215 … … 230 221 */ 231 222 public void setImage(Image value) { 232 223 this.image = value; 233 224 } 234 225 … … 240 231 */ 241 232 public void setRating(String value) { 242 233 this.rating = value; 243 234 } 244 235 … … 250 241 */ 251 242 public void setTextInput(TextInput value) { 252 243 this.textInput = value; 253 244 } 254 245 … … 260 251 */ 261 252 public void setSkipHours(SkipHoursList value) { 262 253 this.skipHours = value; 263 254 } 264 255 … … 270 261 */ 271 262 public void setSkipDays(SkipDaysList value) { 272 263 this.skipDays = value; 273 264 } 274 265 … … 276 267 protected abstract RssItem fromArgToRssItem(T obj) throws ParseException; 277 268 278 //makes (and returns ) an rss out of a list of RssItems 269 /** 270 * Makes an rss out of a list of RssItems 271 * 272 * @param rssItems 273 * @return rss from the RssItems 274 */ 279 275 private Rss makeRssChannel(List<RssItem> rssItems) { 280 281 final Rss rss = new Rss();282 final RssChannel channel = new RssChannel(); 283 284 channel.setCategory(category);285 channel.setCloud(cloud);286 channel.setCopyright(copyright);287 channel.setDescription(description);288 channel.setDocs(docs);289 channel.setGenerator(generator);290 channel.setImage(image);291 channel.setLanguage(language);292 channel.setLastBuildDate(lastBuildDate);293 channel.setLink(link);294 channel.setManagingEditor(managingEditor);295 channel.setPubDate(pubDate);296 channel.setRating(rating);297 channel.setSkipDays(skipDays);298 channel.setSkipHours(skipHours);299 channel.setTextInput(textInput);300 channel.setTitle(title);301 channel.setTtl(ttl);302 channel.setWebMaster(webMaster); 303 304 305 rss.setChannel(channel); 306 307 rss.setVersion(version);308 309 310 311 312 for (RssItem currentItem : rssItems) { 313 channel.getItem().add(currentItem);314 }315 316 return rss;317 }318 319 //makes (and returns) a list of items out a list of descriptions, return the pointer to the list of items276 final Rss rss = new Rss(); 277 final RssChannel channel = new RssChannel(); 278 279 channel.setCategory(category); 280 channel.setCloud(cloud); 281 channel.setCopyright(copyright); 282 channel.setDescription(description); 283 channel.setDocs(docs); 284 channel.setGenerator(generator); 285 channel.setImage(image); 286 channel.setLanguage(language); 287 channel.setLastBuildDate(lastBuildDate); 288 channel.setLink(link); 289 channel.setManagingEditor(managingEditor); 290 channel.setPubDate(pubDate); 291 channel.setRating(rating); 292 channel.setSkipDays(skipDays); 293 channel.setSkipHours(skipHours); 294 channel.setTextInput(textInput); 295 channel.setTitle(title); 296 channel.setTtl(ttl); 297 channel.setWebMaster(webMaster); 298 299 rss.setChannel(channel); 300 rss.setVersion(version); 301 302 for (RssItem currentItem : rssItems) { 303 channel.getItem().add(currentItem); 304 } 305 306 return rss; 307 } 308 309 /** 310 * Makes a list of items out a list of descriptions, return the pointer to the list of items 311 * 312 * @param descriptions 313 * @return items out a list of descriptions 314 * @throws ParseException 315 */ 320 316 private List<RssItem> makeListOfRssItems(List<T> objs) throws ParseException { 321 317 List<RssItem> listOfItems = new ArrayList<RssItem>(); 322 318 323 319 for (T currentObj : objs) { 324 325 320 RssItem currentItem = fromArgToRssItem(currentObj); 326 327 328 329 321 listOfItems.add(currentItem); 322 } 323 324 return listOfItems; 330 325 } 331 326 332 327 public Rss makeRss(List<T> objs) throws ParseException { 333 328 return (makeRssChannel(makeListOfRssItems(objs))); 334 329 } 335 330 336 331 // Helping stuff 337 332 protected Guid makeGuid(String href) { 338 339 340 341 333 Guid result = new Guid(); 334 // result.setIsPermaLink(null); 335 result.setValue(href); 336 return result; 342 337 } 343 338 344 339 /// Helping stuff: for working with dates 345 340 private static Date parseWorks(String dateString) { 346 Date d = null; 347 try { 348 d = AbstractDescription.getDate(dateString); 349 } catch (ParseException pe) { 350 return null; 351 }; 352 return d; 341 try { 342 return AbstractDescription.getDate(dateString); 343 } catch (ParseException pe) { 344 return null; 345 } 353 346 } 354 347 355 348 protected String getRFCDateTime(String dateString) { 356 357 Date date = parseWorks(dateString); 358 359 if (date == null) { 360 return dateString; 361 } else { 362 SimpleDateFormat RFC822DATEFORMAT = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z"); 363 return RFC822DATEFORMAT.format(date); 364 } 365 } 366 367 368 /////// 369 // returns 1 if ds1 is older (before) than ds2, returns -1 if ds1 is younger (after) than ds2 370 public static int compareDateStrings(String ds1, String ds2) { 371 372 int result = 0; 373 374 Date d1 = parseWorks(ds1); 375 Date d2 = parseWorks(ds2); 376 377 if (d1 == null) { 378 if (d2 == null) { 379 result = 0; 380 } else { 381 result = 1; 382 } 383 } else { 384 if (d2 == null) { 385 result = -1; 386 } else { 387 // cpmparteTo reurns: 388 // a value less than 0 if d2 is before d1 (d1 is younger than d2); 389 // a value greater than 0 if d2 is after d1 (d1 is older than d2) 390 result = d2.compareTo(d1); 391 } 392 393 } 394 return result; 349 final Date date = parseWorks(dateString); 350 351 if (date == null) { 352 return dateString; 353 } else { 354 SimpleDateFormat RFC822DATEFORMAT = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z"); 355 return RFC822DATEFORMAT.format(date); 356 } 357 } 358 359 /** 360 * Compares two date strings 361 * 362 * @param date1 363 * @param date2 364 * @return 1 if date1 is older (before) than date2, returns -1 if date1 is younger (after) than date2, 0 if they are the same 365 */ 366 public static int compareDateStrings(String date1, String date2) { 367 final Date d1 = parseWorks(date1); 368 final Date d2 = parseWorks(date2); 369 370 if (d1 == null) { 371 if (d2 == null) { 372 return 0; 373 } else { 374 return 1; 375 } 376 } else { 377 if (d2 == null) { 378 return -1; 379 } else { 380 // compareTo returns: 381 // a value less than 0 if d2 is before d1 (d1 is younger than d2); 382 // a value greater than 0 if d2 is after d1 (d1 is older than d2) 383 return d2.compareTo(d1); 384 } 385 } 395 386 } 396 387 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreatorComments.java
r2286 r2287 1 /*2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */5 1 package clarin.cmdi.componentregistry; 6 2 7 import clarin.cmdi.componentregistry.model.AbstractDescription;8 3 import clarin.cmdi.componentregistry.model.Comment; 9 4 import clarin.cmdi.componentregistry.rss.RssItem; … … 16 11 public class RssCreatorComments extends RssCreator<Comment> { 17 12 18 19 // creator method, comment to rssItem, ovverrides the dummy method of the RssCreator class 20 // ?? is there a better way than boolean flag to arrange switch beween comment for profiles and commentss for components 21 22 23 24 @Override 25 protected RssItem fromArgToRssItem(Comment comm) throws ParseException{ 13 /** 14 * creator method, comment to rssItem, overrides the dummy method of the RssCreator class 15 * 16 * @param comm 17 * @return 18 * @throws ParseException 19 */ 20 @Override 21 protected RssItem fromArgToRssItem(Comment comm) throws ParseException { 22 final String href = super.getLink() + "&commentId=" + comm.getId(); 26 23 27 28 RssItem retval = new RssItem(); 29 30 31 //The content 32 retval.setDescription(comm.getComment()); 33 String href = super.getLink()+"&commentId="+comm.getId(); 34 35 //Guid 36 retval.setGuid(makeGuid(href)); 37 38 // link 39 retval.setLink(href); 40 41 42 43 44 //date-Time 45 retval.setPubDate(getRFCDateTime(comm.getCommentDate())); 46 47 // Title 48 retval.setTitle(makeCommentTitle(comm.getId(), comm.getUserName())); 49 50 return retval; 51 52 24 RssItem retval = new RssItem(); 25 retval.setDescription(comm.getComment()); 26 retval.setGuid(makeGuid(href)); 27 retval.setLink(href); 28 retval.setPubDate(getRFCDateTime(comm.getCommentDate())); 29 retval.setTitle(String.format("Comment %1$s\nby %2$s", comm.getId(), comm.getUserName())); 30 return retval; 53 31 } 54 55 protected String makeCommentTitle(String commentId, String user){56 57 return("Comment "+commentId +"\n by "+user+" ");58 59 }60 61 32 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreatorDescriptions.java
r2286 r2287 1 /*2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */5 1 package clarin.cmdi.componentregistry; 6 2 7 3 import clarin.cmdi.componentregistry.model.AbstractDescription; 8 4 import clarin.cmdi.componentregistry.rss.RssItem; 9 import org.slf4j.Logger;10 import org.slf4j.LoggerFactory;11 5 12 6 /** … … 14 8 * @author olhsha 15 9 */ 16 public class RssCreatorDescriptions<T extends AbstractDescription> extends RssCreator<T> { 17 18 private final static Logger LOG = LoggerFactory.getLogger(RssCreatorDescriptions.class); 19 // creator method, desc to rssItem, ovverrides the dummy method of the RssCreatorClass 20 @Override 10 public class RssCreatorDescriptions<T extends AbstractDescription> extends RssCreator<T> { 11 12 /** 13 * creator method, desc to rssItem, overrides the dummy method of the RssCreatorClass 14 * 15 * @param desc 16 * @return 17 */ 18 @Override 21 19 protected RssItem fromArgToRssItem(T desc) { 22 20 23 21 //TODO: Make more generic by requiring a link that has at least one (dummy) parameter in URL 22 String connectParam; 23 if (super.getUserspace()) { 24 connectParam = "&"; 25 } else { 26 connectParam = "?"; 27 } 28 String href = super.getLink() + connectParam + "item=" + desc.getId(); 24 29 25 RssItem retval = new RssItem(); 26 27 //Description (blah-blah) 28 retval.setDescription(desc.getDescription()); 29 30 String connectParam; 31 if (super.getUserspace()) {connectParam="&";} else {connectParam="?";} 32 String href = super.getLink()+connectParam+"item="+desc.getId(); 33 34 //Guid 35 retval.setGuid(makeGuid(href)); 36 37 // link 38 39 retval.setLink(href); 40 41 //time-date 42 retval.setPubDate(desc.getRegistrationDate()); 43 44 //Title 45 retval.setTitle(makeDescriptionTitle(desc.getName(),desc.getCreatorName(), desc.getGroupName())); 46 47 return retval; 48 30 RssItem retval = new RssItem(); 31 retval.setDescription(desc.getDescription()); 32 retval.setGuid(makeGuid(href)); 33 retval.setLink(href); 34 retval.setPubDate(desc.getRegistrationDate()); 35 retval.setTitle(makeDescriptionTitle(desc.getName(), desc.getCreatorName(), desc.getGroupName())); 36 return retval; 49 37 } 50 38 51 protected String makeDescriptionTitle(String name, String creatorname, String group){ 52 53 String help; 54 if (group==null) {help="is unspecified";} else {help=group;}; 55 56 return(name+" by user "+creatorname+", group "+help); 57 39 protected String makeDescriptionTitle(String name, String creatorname, String group) { 40 final String help = (group == null) ? "is unspecified" : group; 41 return (name + " by user " + creatorname + ", group " + help); 58 42 } 59 43 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/AbstractDescription.java
r2268 r2287 5 5 import java.util.Comparator; 6 6 import java.util.Date; 7 8 7 import javax.xml.bind.annotation.XmlAccessType; 9 8 import javax.xml.bind.annotation.XmlAccessorType; … … 11 10 import javax.xml.bind.annotation.XmlRootElement; 12 11 import javax.xml.bind.annotation.XmlSeeAlso; 13 14 12 import org.apache.commons.codec.digest.DigestUtils; 15 13 import org.apache.commons.lang.time.DateFormatUtils; … … 34 32 private String groupName; 35 33 private int commentsCount; 36 private final static Logger LOG = LoggerFactory.getLogger(AbstractDescription.class);37 34 38 35 public void setId(String id) { 39 36 this.id = id; 40 37 } 41 38 42 39 public String getId() { 43 40 return id; 44 41 } 45 42 46 43 public void setDescription(String description) { 47 44 this.description = description; 48 45 } 49 46 50 47 public String getDescription() { 51 48 return description; 52 49 } 53 50 54 51 public void setName(String name) { 55 52 this.name = name; 56 53 } 57 54 58 55 public String getName() { 59 56 return name; 60 57 } 61 58 62 59 public void setRegistrationDate(String registrationDate) { 63 60 this.registrationDate = registrationDate; 64 61 } 65 62 66 63 public String getRegistrationDate() { 67 64 return registrationDate; 68 65 } 69 66 70 67 public void setCreatorName(String creatorName) { 71 68 this.creatorName = creatorName; 72 69 } 73 70 74 71 public String getCreatorName() { 75 72 return creatorName; 76 73 } 77 74 78 75 public void setUserId(String userId) { 79 76 this.userId = userId; 80 77 } 81 78 … … 85 82 */ 86 83 public String getUserId() { 87 84 return userId; 88 85 } 89 86 90 87 public void setDomainName(String domainName) { 91 88 this.domainName = domainName; 92 89 } 93 90 94 91 public String getDomainName() { 95 92 return domainName; 96 93 } 97 94 98 95 public void setHref(String href) { 99 96 this.href = href; 100 97 } 101 98 102 99 public String getHref() { 103 100 return href; 104 101 } 105 102 106 103 public void setGroupName(String groupName) { 107 104 this.groupName = groupName; 108 105 } 109 106 110 107 public String getGroupName() { 111 108 return groupName; 112 109 } 113 110 … … 116 113 */ 117 114 public int getCommentsCount() { 118 115 return commentsCount; 119 116 } 120 117 … … 123 120 */ 124 121 public void setCommentsCount(int commentsCount) { 125 122 this.commentsCount = commentsCount; 126 123 } 127 124 128 125 @Override 129 126 public String toString() { 130 127 return "Name=" + getName() + ", id=" + getId() + ", creatorName=" + getCreatorName() + ", userId=" + getUserId(); 131 128 } 132 129 133 130 public boolean isProfile() { 134 131 return this instanceof ProfileDescription; 135 132 } 136 133 137 134 public String getType() { 138 135 return isProfile() ? "profile" : "component"; 139 136 } 140 137 141 138 public static String createNewDate() { 142 139 return createNewDate(new Date().getTime()); 143 140 } 144 141 145 142 public static String createNewDate(long time) { 146 143 return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()); 147 144 } 148 145 … … 154 151 */ 155 152 public boolean isThisTheOwner(String userId) { 156 157 153 String userHash = DigestUtils.md5Hex(userId); 154 return userHash.equals(getUserId()); 158 155 } 159 156 160 157 public static Date getDate(String registrationDate) throws ParseException { 161 162 } 163 158 return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()}); 159 } 160 164 161 public static String createPublicHref(String href) { 165 String result = href; 166 if (href != null) { 167 int index = href.indexOf("?"); 168 if (index != -1) { //strip off query params the rest should be the public href. 169 result = href.substring(0, index); 170 } 171 } 172 return result; 173 } 162 String result = href; 163 if (href != null) { 164 int index = href.indexOf("?"); 165 if (index != -1) { //strip off query params the rest should be the public href. 166 result = href.substring(0, index); 167 } 168 } 169 return result; 170 } 171 /** 172 * Compares two descriptions by the their value as returned by {@link AbstractDescription#getName() } 173 */ 174 174 public static final Comparator<? super AbstractDescription> COMPARE_ON_NAME = new Comparator<AbstractDescription>() { 175 176 177 178 179 180 181 182 183 184 185 175 @Override 176 public int compare(AbstractDescription o1, AbstractDescription o2) { 177 int result = 0; 178 if (o1.getName() != null && o2.getName() != null) { 179 result = o1.getName().compareToIgnoreCase(o2.getName()); 180 } 181 if (o1.getId() != null && result == 0) { 182 result = o1.getId().compareTo(o2.getId()); 183 } 184 return result; 185 } 186 186 }; 187 /** 188 * Compares two descriptions by the their value as returned by {@link AbstractDescription#getRegistrationDate() () } 189 */ 187 190 public static final Comparator<? super AbstractDescription> COMPARE_ON_DATE = new Comparator<AbstractDescription>() { 188 //compare two components by the date of registration 189 // returns 1 if o11 is older than o2, returns -1 if o1 is younger than o2 190 @Override 191 public int compare(AbstractDescription o1, AbstractDescription o2) { 192 193 return (RssCreator.compareDateStrings(o1.getRegistrationDate(), o2.getRegistrationDate())); 194 } 191 /** 192 * @returns 1 if o11 is older than o2, returns -1 if o1 is younger than o2 193 */ 194 @Override 195 public int compare(AbstractDescription o1, AbstractDescription o2) { 196 197 return (RssCreator.compareDateStrings(o1.getRegistrationDate(), o2.getRegistrationDate())); 198 } 195 199 }; 196 200 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/Comment.java
r2268 r2287 2 2 3 3 import clarin.cmdi.componentregistry.RssCreator; 4 import java.text.DateFormat;5 4 import java.text.ParseException; 6 5 import java.util.Comparator; 7 6 import java.util.Date; 8 import javax.xml.bind.DatatypeConverter;9 7 import javax.xml.bind.annotation.XmlAccessType; 10 8 import javax.xml.bind.annotation.XmlAccessorType; … … 13 11 import org.apache.commons.lang.time.DateFormatUtils; 14 12 import org.apache.commons.lang.time.DateUtils; 15 import org.slf4j.Logger;16 import org.slf4j.LoggerFactory;17 13 18 14 /** … … 34 30 @XmlTransient // this prevents userId from being serialized to XML and thus exposed (which is useless and undesirable) 35 31 private String userId; 36 private final static Logger LOG = LoggerFactory.getLogger(Comment.class);37 32 38 33 public void setComment(String comment) { 39 34 this.comments = comment; 40 35 } 41 36 42 37 public String getComment() { 43 38 return comments; 44 39 } 45 40 46 41 public void setCommentDate(String commentDate) { 47 42 this.commentDate = commentDate; 48 43 } 49 44 50 45 public String getCommentDate() { 51 46 return commentDate; 52 47 } 53 48 54 49 public void setId(String commentId) { 55 50 this.id = commentId; 56 51 } 57 52 58 53 public String getId() { 59 54 return id; 60 55 } 61 56 62 57 public String getComponentDescriptionId() { 63 58 return componentDescriptionId; 64 59 } 65 60 66 61 public void setComponentDescriptionId(String ComponentDescriptionId) { 67 62 this.componentDescriptionId = ComponentDescriptionId; 68 63 } 69 64 70 65 public void setProfileDescriptionId(String profileDescriptionId) { 71 66 this.profileDescriptionId = profileDescriptionId; 72 67 } 73 68 74 69 public String getProfileDescriptionId() { 75 70 return profileDescriptionId; 76 71 } 77 72 78 73 public void setUserId(String userId) { 79 74 this.userId = userId; 80 75 } 81 76 82 77 public String getUserId() { 83 78 return userId; 84 79 } 85 80 … … 89 84 */ 90 85 public String getUserName() { 91 86 return userName; 92 87 } 93 88 … … 96 91 */ 97 92 public void setUserName(String userName) { 98 93 this.userName = userName; 99 94 } 100 95 … … 103 98 */ 104 99 public boolean isCanDelete() { 105 100 return canDelete; 106 101 } 107 102 … … 110 105 */ 111 106 public void setCanDelete(boolean canDelete) { 112 107 this.canDelete = canDelete; 113 108 } 114 109 115 110 public static Date getDate(String registrationDate) throws ParseException { 116 111 return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()}); 117 112 } 118 113 … … 121 116 */ 122 117 public static String createNewDate() { 123 118 return createNewDate(new Date().getTime()); 124 119 } 125 120 … … 129 124 */ 130 125 public static String createNewDate(long time) { 131 126 return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()); 132 127 } 133 128 134 129 public static Comment createANewComment() { 135 136 137 130 Comment com = new Comment(); 131 com.setCommentDate(createNewDate()); 132 return com; 138 133 } 139 134 /** 135 * Compares two commments by their value as returned by {@link Comment#getCommentDate() } 136 */ 140 137 public static final Comparator<Comment> COMPARE_ON_DATE = new Comparator<Comment>() { 141 //compare two commments by the date of registration 142 // returns 1 if o11 is older than o2, returns -1 if o1 is younger than o2 143 @Override 144 public int compare(Comment o1, Comment o2) { 138 /** 139 * @return 1 if o11 is older than o2, returns -1 if o1 is younger than o2 140 */ 141 @Override 142 public int compare(Comment o1, Comment o2) { 145 143 146 147 144 return (RssCreator.compareDateStrings(o1.getCommentDate(), o2.getCommentDate())); 145 } 148 146 }; 149 147 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/ComponentDescription.java
r2221 r2287 1 1 package clarin.cmdi.componentregistry.model; 2 3 import java.io.Serializable;4 import java.util.Comparator;5 6 import javax.xml.bind.annotation.XmlRootElement;7 2 8 3 import clarin.cmdi.componentregistry.ComponentRegistry; 9 4 import clarin.cmdi.componentregistry.IdSequence; 5 import java.io.Serializable; 6 import java.util.Comparator; 7 import javax.xml.bind.annotation.XmlRootElement; 10 8 11 9 @XmlRootElement(name = "componentDescription") … … 14 12 private static final long serialVersionUID = 1L; 15 13 public static final Comparator<? super ComponentDescription> COMPARE_ON_GROUP_AND_NAME = new Comparator<ComponentDescription>() { 16 public int compare(ComponentDescription o1, ComponentDescription o2) { 17 int result = 0; 18 if (o1.getGroupName() != null && o2.getGroupName() != null) { 19 result = o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); 20 } 21 if (result == 0) { 22 if (o1.getName() != null && o2.getName() != null) { 23 result = o1.getName().compareToIgnoreCase(o2.getName()); 24 } else { 25 result = o1.getId().compareTo(o2.getId()); 26 } 27 } 28 return result; 29 } 14 @Override 15 public int compare(ComponentDescription o1, ComponentDescription o2) { 16 int result = 0; 17 if (o1.getGroupName() != null && o2.getGroupName() != null) { 18 result = o1.getGroupName().compareToIgnoreCase(o2.getGroupName()); 19 } 20 if (result == 0) { 21 if (o1.getName() != null && o2.getName() != null) { 22 result = o1.getName().compareToIgnoreCase(o2.getName()); 23 } else { 24 result = o1.getId().compareTo(o2.getId()); 25 } 26 } 27 return result; 28 } 30 29 }; 31 32 30 33 31 public static ComponentDescription createNewDescription() { 34 35 36 37 38 32 String id = ComponentRegistry.REGISTRY_ID + "c_" + IdSequence.get(); 33 ComponentDescription desc = new ComponentDescription(); 34 desc.setId(id); 35 desc.setRegistrationDate(createNewDate()); 36 return desc; 39 37 } 40 38 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java
r2286 r2287 6 6 import clarin.cmdi.componentregistry.ComponentStatus; 7 7 import clarin.cmdi.componentregistry.DeleteFailedException; 8 import clarin.cmdi.componentregistry.MDMarshaller;9 8 import clarin.cmdi.componentregistry.Owner; 10 9 import clarin.cmdi.componentregistry.RssCreatorComments; … … 23 22 import com.sun.jersey.multipart.FormDataParam; 24 23 import com.sun.jersey.spi.inject.Inject; 25 import java.io.ByteArrayOutputStream;26 import java.io.File;27 import java.io.FileOutputStream;28 24 import java.io.IOException; 29 25 import java.io.InputStream; … … 97 93 @Deprecated 98 94 private static ComponentStatus getStatus(boolean userSpace) { 99 100 101 102 103 95 if (userSpace) { 96 return ComponentStatus.DEVELOPMENT; 97 } else { 98 return ComponentStatus.PUBLIC; 99 } 104 100 } 105 101 106 102 private ComponentRegistry getRegistry(ComponentStatus status) { 107 108 109 103 Principal userPrincipal = security.getUserPrincipal(); 104 UserCredentials userCredentials = getUserCredentials(userPrincipal); 105 return getRegistry(status, null, userCredentials); 110 106 } 111 107 112 108 private ComponentRegistry getRegistry(ComponentStatus status, Owner owner, UserCredentials userCredentials) { 113 114 115 116 117 118 109 try { 110 return componentRegistryFactory.getComponentRegistry(status, owner, userCredentials); 111 } catch (UserUnauthorizedException uuEx) { 112 //TODO: Throw actual exception and catch nicely 113 throw new RuntimeException("Cannot access requested registry", uuEx); 114 } 119 115 } 120 116 … … 125 121 */ 126 122 private Principal checkAndGetUserPrincipal() throws UserUnauthorizedException { 127 128 129 130 131 123 Principal principal = security.getUserPrincipal(); 124 if (principal == null) { 125 throw new UserUnauthorizedException("no user principal found."); 126 } 127 return principal; 132 128 } 133 129 134 130 private UserCredentials getUserCredentials(Principal userPrincipal) { 135 136 137 138 139 131 UserCredentials userCredentials = null; 132 if (userPrincipal != null) { 133 userCredentials = new UserCredentials(userPrincipal); 134 } 135 return userCredentials; 140 136 } 141 137 … … 144 140 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 145 141 public List<ComponentDescription> getRegisteredComponents(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 146 147 148 149 150 142 long start = System.currentTimeMillis(); 143 List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions(); 144 LOG.info("Releasing " + components.size() + " registered components into the world (" + (System.currentTimeMillis() - start) 145 + " millisecs)"); 146 return components; 151 147 } 152 148 … … 155 151 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 156 152 public List<ProfileDescription> getRegisteredProfiles(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, 157 158 159 160 161 162 163 164 165 166 167 168 153 @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor) throws ComponentRegistryException { 154 long start = System.currentTimeMillis(); 155 List<ProfileDescription> profiles; 156 if (metadataEditor) { 157 profiles = getRegistry(getStatus(userspace)).getProfileDescriptionsForMetadaEditor(); 158 } else { 159 profiles = getRegistry(getStatus(userspace)).getProfileDescriptions(); 160 } 161 162 LOG.info("Releasing " + profiles.size() + " registered profiles into the world (" + (System.currentTimeMillis() - start) 163 + " millisecs)"); 164 return profiles; 169 165 } 170 166 … … 173 169 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 174 170 public Response getRegisteredComponent(@PathParam("componentId") String componentId, 175 176 177 178 179 180 181 182 171 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 172 LOG.info("Component with id: " + componentId + " is requested."); 173 CMDComponentSpec mdComponent = getRegistry(getStatus(userspace)).getMDComponent(componentId); 174 if (mdComponent == null) { 175 return Response.status(Status.NOT_FOUND).build(); 176 } else { 177 return Response.ok(mdComponent).build(); 178 } 183 179 } 184 180 … … 187 183 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML}) 188 184 public Response getRegisteredComponentRawType(@PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) { 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 185 LOG.info("Component with id: " + componentId + " and rawType:" + rawType + " is requested."); 186 StreamingOutput result = null; 187 try { 188 final ComponentRegistry registry = findRegistry(componentId, new ComponentClosure()); 189 if (registry == null) { 190 return Response.status(Status.NOT_FOUND).entity("Id: " + componentId + " is not registered, cannot create data.").build(); 191 } 192 ComponentDescription desc = registry.getComponentDescription(componentId); 193 checkAndThrowDescription(desc, componentId); 194 String fileName = desc.getName() + "." + rawType; 195 if ("xml".equalsIgnoreCase(rawType)) { 196 result = new StreamingOutput() { 197 @Override 198 public void write(OutputStream output) throws IOException, WebApplicationException { 199 try { 200 registry.getMDComponentAsXml(componentId, output); 201 } catch (ComponentRegistryException e) { 202 LOG.info("Could not retrieve component", e); 203 throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); 204 } 205 } 206 }; 207 } else if ("xsd".equalsIgnoreCase(rawType)) { 208 result = new StreamingOutput() { 209 @Override 210 public void write(OutputStream output) throws IOException, WebApplicationException { 211 try { 212 registry.getMDComponentAsXsd(componentId, output); 213 } catch (ComponentRegistryException e) { 214 LOG.info("Could not retrieve component", e); 215 throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); 216 } 217 218 } 219 }; 220 } else { 221 throw new WebApplicationException(Response.serverError().entity( 222 "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build()); 223 } 224 return createDownloadResponse(result, fileName); 225 } catch (ComponentRegistryException e) { 226 LOG.info("Could not retrieve component", e); 227 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 228 } 233 229 } 234 230 235 231 public ComponentRegistry findRegistry(String id, RegistryClosure<? extends AbstractDescription> clos) throws ComponentRegistryException { 236 237 238 239 240 241 242 243 244 245 246 247 248 249 232 AbstractDescription desc = null; 233 ComponentRegistry result = getRegistry(getStatus(false)); 234 desc = clos.getDescription(result, id); 235 if (desc == null) { 236 List<ComponentRegistry> userRegs = componentRegistryFactory.getAllUserRegistries(); 237 for (ComponentRegistry reg : userRegs) { 238 desc = clos.getDescription(reg, id); 239 if (desc != null) { 240 result = reg; 241 break; 242 } 243 } 244 } 245 return result; 250 246 } 251 247 … … 254 250 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 255 251 public Response getRegisteredProfile(@PathParam("profileId") String profileId, 256 257 258 259 260 261 262 263 252 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 253 LOG.info("Profile with id: " + profileId + " is requested."); 254 CMDComponentSpec mdProfile = getRegistry(getStatus(userspace)).getMDProfile(profileId); 255 if (mdProfile == null) { 256 return Response.status(Status.NOT_FOUND).build(); 257 } else { 258 return Response.ok(mdProfile).build(); 259 } 264 260 } 265 261 … … 268 264 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 269 265 public List<AbstractDescription> getComponentUsage(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("true") boolean userspace) throws ComponentRegistryException { 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 266 try { 267 final long start = System.currentTimeMillis(); 268 ComponentRegistry registry = getRegistry(getStatus(userspace)); 269 List<ComponentDescription> components = registry.getUsageInComponents(componentId); 270 List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId); 271 272 LOG.info("Found " + components.size() + " components and " + profiles.size() + " profiles that use component " + componentId 273 + " (" + (System.currentTimeMillis() - start) + " millisecs)"); 274 275 List<AbstractDescription> usages = new ArrayList<AbstractDescription>(components.size() + profiles.size()); 276 usages.addAll(components); 277 usages.addAll(profiles); 278 279 return usages; 280 } catch (ComponentRegistryException e) { 281 LOG.info("Could not retrieve profile usage", e); 282 throw e; 283 } 288 284 } 289 285 … … 292 288 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 293 289 public List<Comment> getCommentsFromProfile(@PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 294 295 296 297 298 299 290 long start = System.currentTimeMillis(); 291 final Principal principal = security.getUserPrincipal(); 292 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal); 293 LOG.info("Releasing " + comments.size() + " registered comments in Profile into the world (" + (System.currentTimeMillis() - start) 294 + " millisecs)"); 295 return comments; 300 296 } 301 297 … … 304 300 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 305 301 public List<Comment> getCommentsFromComponent(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 306 307 308 309 310 311 302 long start = System.currentTimeMillis(); 303 final Principal principal = security.getUserPrincipal(); 304 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal); 305 LOG.info("Releasing " + comments.size() + " registered comments in Component into the world (" + (System.currentTimeMillis() - start) 306 + " millisecs)"); 307 return comments; 312 308 } 313 309 … … 316 312 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 317 313 public Comment getSpecifiedCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 318 319 320 314 LOG.info(" Comments of component with id" + commentId + " are requested."); 315 final Principal principal = security.getUserPrincipal(); 316 return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(profileId, commentId, principal); 321 317 } 322 318 … … 325 321 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 326 322 public Comment getSpecifiedCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 327 328 329 323 LOG.info(" Comments of component with id" + commentId + " are requested."); 324 final Principal principal = security.getUserPrincipal(); 325 return getRegistry(getStatus(userspace)).getSpecifiedCommentInComponent(componentId, commentId, principal); 330 326 } 331 327 … … 342 338 @Path("/profiles/{profileId}") 343 339 public Response manipulateRegisteredProfile(@PathParam("profileId") String profileId, @FormParam("method") String method, 344 345 346 347 348 349 340 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 341 if ("delete".equalsIgnoreCase(method)) { 342 return deleteRegisteredProfile(profileId, userspace); 343 } else { 344 return Response.ok().build(); 345 } 350 346 } 351 347 … … 353 349 @Path("/profiles/{profileId}/comments/{commentId}") 354 350 public Response manipulateCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @FormParam("method") String method, 355 356 357 358 359 360 351 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 352 if ("delete".equalsIgnoreCase(method)) { 353 return deleteCommentFromProfile(profileId, commentId, userspace); 354 } else { 355 return Response.ok().build(); 356 } 361 357 } 362 358 … … 364 360 @Path("/components/{componentId}/comments/{commentId}") 365 361 public Response manipulateCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @FormParam("method") String method, 366 367 368 369 370 371 362 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 363 if ("delete".equalsIgnoreCase(method)) { 364 return deleteCommentFromComponent(componentId, commentId, userspace); 365 } else { 366 return Response.ok().build(); 367 } 372 368 } 373 369 … … 376 372 @Consumes("multipart/form-data") 377 373 public Response publishRegisteredProfile(@PathParam("profileId") String profileId, @FormDataParam(DATA_FORM_FIELD) InputStream input, 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 374 @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description, 375 @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) { 376 try { 377 Principal principal = checkAndGetUserPrincipal(); 378 ProfileDescription desc = getRegistry(getStatus(true)).getProfileDescription(profileId); 379 if (desc != null) { 380 updateDescription(desc, name, description, domainName, group); 381 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal)); 382 } else { 383 LOG.error("Update of nonexistent id (" + profileId + ") failed."); 384 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build(); 385 } 386 } catch (ComponentRegistryException e) { 387 LOG.info("Could not retrieve component", e); 388 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 389 } catch (UserUnauthorizedException ex) { 390 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 391 } 396 392 } 397 393 … … 400 396 @Consumes("multipart/form-data") 401 397 public Response updateRegisteredProfile(@PathParam("profileId") String profileId, 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 398 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input, 399 @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description, 400 @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) { 401 try { 402 Principal principal = checkAndGetUserPrincipal(); 403 UserCredentials userCredentials = getUserCredentials(principal); 404 ProfileDescription desc = getRegistry(getStatus(userspace)).getProfileDescription(profileId); 405 if (desc != null) { 406 updateDescription(desc, name, description, domainName, group); 407 return register(input, desc, userCredentials, userspace, new UpdateAction(principal)); 408 } else { 409 LOG.error("Update of nonexistent id (" + profileId + ") failed."); 410 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build(); 411 } 412 } catch (ComponentRegistryException e) { 413 LOG.info("Could not retrieve component", e); 414 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 415 } catch (UserUnauthorizedException ex) { 416 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 417 } 422 418 423 419 } … … 435 431 @Path("/components/{componentId}") 436 432 public Response manipulateRegisteredComponent(@PathParam("componentId") String componentId, @FormParam("method") String method, 437 438 439 440 441 442 433 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 434 if ("delete".equalsIgnoreCase(method)) { 435 return deleteRegisteredComponent(componentId, userspace); 436 } else { 437 return Response.ok().build(); 438 } 443 439 } 444 440 … … 447 443 @Consumes("multipart/form-data") 448 444 public Response publishRegisteredComponent(@PathParam("componentId") String componentId, 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 445 @FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name, 446 @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, 447 @FormDataParam(DOMAIN_FORM_FIELD) String domainName) { 448 try { 449 Principal principal = checkAndGetUserPrincipal(); 450 // TODO: Get status from parameter 451 ComponentDescription desc = getRegistry(getStatus(true)).getComponentDescription(componentId); 452 if (desc != null) { 453 updateDescription(desc, name, description, domainName, group); 454 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal)); 455 } else { 456 LOG.error("Update of nonexistent id (" + componentId + ") failed."); 457 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build(); 458 } 459 } catch (ComponentRegistryException e) { 460 LOG.info("Could not retrieve component", e); 461 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 462 } catch (UserUnauthorizedException ex) { 463 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 464 } 469 465 } 470 466 … … 473 469 @Consumes("multipart/form-data") 474 470 public Response updateRegisteredComponent(@PathParam("componentId") String componentId, 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 471 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input, 472 @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description, 473 @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) { 474 try { 475 Principal principal = checkAndGetUserPrincipal(); 476 ComponentDescription desc = getRegistry(getStatus(userspace)).getComponentDescription(componentId); 477 if (desc != null) { 478 updateDescription(desc, name, description, domainName, group); 479 return register(input, desc, getUserCredentials(principal), userspace, new UpdateAction(principal)); 480 } else { 481 LOG.error("Update of nonexistent id (" + componentId + ") failed."); 482 return Response.serverError().entity("Invalid id, cannot update nonexistent component").build(); 483 } 484 } catch (ComponentRegistryException e) { 485 LOG.info("Could not retrieve component", e); 486 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 487 } catch (UserUnauthorizedException ex) { 488 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 489 } 494 490 } 495 491 496 492 private void updateDescription(AbstractDescription desc, String name, String description, String domainName, String group) { 497 498 499 500 501 493 desc.setName(name); 494 desc.setDescription(description); 495 desc.setDomainName(domainName); 496 desc.setGroupName(group); 497 desc.setRegistrationDate(AbstractDescription.createNewDate()); 502 498 } 503 499 … … 505 501 @Path("/components/{componentId}") 506 502 public Response deleteRegisteredComponent(@PathParam("componentId") String componentId, 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 503 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 504 try { 505 Principal principal = checkAndGetUserPrincipal(); 506 ComponentRegistry registry = getRegistry(getStatus(userspace)); 507 LOG.info("Component with id: " + componentId + " set for deletion."); 508 registry.deleteMDComponent(componentId, principal, false); 509 } catch (DeleteFailedException e) { 510 LOG.info("Component with id: " + componentId + " deletion failed.", e); 511 return Response.status(Status.FORBIDDEN).entity("" + e.getMessage()).build(); 512 } catch (ComponentRegistryException e) { 513 LOG.info("Component with id: " + componentId + " deletion failed.", e); 514 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 515 } catch (IOException e) { 516 LOG.info("Component with id: " + componentId + " deletion failed.", e); 517 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 518 } catch (UserUnauthorizedException e) { 519 LOG.info("Component with id: " + componentId + " deletion failed: " + e.getMessage()); 520 return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build(); 521 } 522 LOG.info("Component with id: " + componentId + " deleted."); 523 return Response.ok().build(); 528 524 } 529 525 … … 531 527 @Path("/profiles/{profileId}") 532 528 public Response deleteRegisteredProfile(@PathParam("profileId") String profileId, 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 529 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 530 try { 531 Principal principal = checkAndGetUserPrincipal(); 532 LOG.info("Profile with id: " + profileId + " set for deletion."); 533 getRegistry(getStatus(userspace)).deleteMDProfile(profileId, principal); 534 } catch (DeleteFailedException e) { 535 LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage()); 536 return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build(); 537 } catch (ComponentRegistryException e) { 538 LOG.info("Could not retrieve component", e); 539 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 540 } catch (IOException e) { 541 LOG.info("Profile with id: " + profileId + " deletion failed.", e); 542 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 543 } catch (UserUnauthorizedException e) { 544 LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage()); 545 return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build(); 546 } 547 LOG.info("Profile with id: " + profileId + " deleted."); 548 return Response.ok().build(); 553 549 } 554 550 … … 556 552 @Path("/profiles/{profileId}/comments/{commentId}") 557 553 public Response deleteCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 554 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 555 try { 556 final Principal principal = checkAndGetUserPrincipal(); 557 final ComponentRegistry registry = getRegistry(getStatus(userspace)); 558 final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId, principal); 559 if (comment != null && profileId.equals(comment.getProfileDescriptionId())) { 560 LOG.info("Comment with id: " + commentId + " set for deletion."); 561 registry.deleteComment(commentId, principal); 562 } else { 563 throw new ComponentRegistryException("Comment not found for specified profile"); 564 } 565 } catch (DeleteFailedException e) { 566 LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage()); 567 return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build(); 568 } catch (ComponentRegistryException e) { 569 LOG.info("Could not retrieve component", e); 570 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 571 } catch (IOException e) { 572 LOG.info("Comment with id: " + commentId + " deletion failed.", e); 573 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 574 } catch (UserUnauthorizedException e) { 575 LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage()); 576 return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build(); 577 } 578 LOG.info("Comment with id: " + commentId + " deleted."); 579 return Response.ok().build(); 584 580 } 585 581 … … 587 583 @Path("/components/{componentId}/comments/{commentId}") 588 584 public Response deleteCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 585 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 586 try { 587 final Principal principal = checkAndGetUserPrincipal(); 588 final ComponentRegistry registry = getRegistry(getStatus(userspace)); 589 final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId, principal); 590 if (comment != null && componentId.equals(comment.getComponentDescriptionId())) { 591 LOG.info("Comment with id: " + commentId + " set for deletion."); 592 registry.deleteComment(commentId, principal); 593 } else { 594 throw new ComponentRegistryException("Comment not found for specified component"); 595 } 596 } catch (DeleteFailedException e) { 597 LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage()); 598 return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build(); 599 } catch (ComponentRegistryException e) { 600 LOG.info("Could not retrieve component", e); 601 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 602 } catch (IOException e) { 603 LOG.info("Comment with id: " + commentId + " deletion failed.", e); 604 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 605 } catch (UserUnauthorizedException e) { 606 LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage()); 607 return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build(); 608 } 609 LOG.info("Comment with id: " + commentId + " deleted."); 610 return Response.ok().build(); 615 611 } 616 612 … … 619 615 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML}) 620 616 public Response getRegisteredProfileRawType(@PathParam("profileId") final String profileId, @PathParam("rawType") String rawType) { 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 617 LOG.info("Profile with id: " + profileId + " and rawType:" + rawType + " is requested."); 618 StreamingOutput result = null; 619 try { 620 final ComponentRegistry registry = findRegistry(profileId, new ProfileClosure()); 621 if (registry == null) { 622 return Response.status(Status.NOT_FOUND).entity("Id: " + profileId + " is not registered, cannot create data.").build(); 623 } 624 ProfileDescription desc = registry.getProfileDescription(profileId); 625 checkAndThrowDescription(desc, profileId); 626 String fileName = desc.getName() + "." + rawType; 627 628 if ("xml".equalsIgnoreCase(rawType)) { 629 result = new StreamingOutput() { 630 @Override 631 public void write(OutputStream output) throws IOException, WebApplicationException { 632 try { 633 registry.getMDProfileAsXml(profileId, output); 634 } catch (ComponentRegistryException e) { 635 LOG.warn("Could not retrieve component", e); 636 throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); 637 } 638 } 639 }; 640 } else if ("xsd".equalsIgnoreCase(rawType)) { 641 result = new StreamingOutput() { 642 @Override 643 public void write(OutputStream output) throws IOException, WebApplicationException { 644 try { 645 registry.getMDProfileAsXsd(profileId, output); 646 } catch (ComponentRegistryException e) { 647 LOG.warn("Could not retrieve component", e); 648 throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build()); 649 } 650 } 651 }; 652 } else { 653 throw new WebApplicationException(Response.serverError().entity( 654 "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build()); 655 } 656 return createDownloadResponse(result, fileName); 657 } catch (ComponentRegistryException e) { 658 LOG.info("Could not retrieve component", e); 659 return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); 660 } 665 661 } 666 662 667 663 private void checkAndThrowDescription(AbstractDescription desc, String id) { 668 669 670 664 if (desc == null) { 665 throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build()); 666 } 671 667 } 672 668 673 669 private Response createDownloadResponse(StreamingOutput result, String fileName) { 674 675 676 677 670 //Making response so it triggers browsers native save as dialog. 671 Response response = Response.ok().type("application/x-download").header("Content-Disposition", 672 "attachment; filename=\"" + fileName + "\"").entity(result).build(); 673 return response; 678 674 679 675 } … … 684 680 @Consumes("multipart/form-data") 685 681 public Response registerProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name, 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 682 @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName, 683 @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 684 try { 685 Principal principal = checkAndGetUserPrincipal(); 686 UserCredentials userCredentials = getUserCredentials(principal); 687 ProfileDescription desc = createNewProfileDescription(); 688 desc.setCreatorName(userCredentials.getDisplayName()); 689 desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl 690 desc.setName(name); 691 desc.setDescription(description); 692 desc.setGroupName(group); 693 desc.setDomainName(domainName); 694 LOG.info("Trying to register Profile: " + desc); 695 return register(input, desc, userCredentials, userspace, new NewAction()); 696 } catch (UserUnauthorizedException ex) { 697 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 698 } 703 699 } 704 700 … … 708 704 @Consumes("multipart/form-data") 709 705 public Response registerComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name, 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 706 @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, 707 @FormDataParam(DOMAIN_FORM_FIELD) String domainName, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) { 708 try { 709 Principal principal = checkAndGetUserPrincipal(); 710 UserCredentials userCredentials = getUserCredentials(principal); 711 ComponentDescription desc = createNewComponentDescription(); 712 desc.setCreatorName(userCredentials.getDisplayName()); 713 desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl 714 desc.setName(name); 715 desc.setDescription(description); 716 desc.setGroupName(group); 717 desc.setDomainName(domainName); 718 LOG.info("Trying to register Component: " + desc); 719 return register(input, desc, userCredentials, userspace, new NewAction()); 720 } catch (UserUnauthorizedException ex) { 721 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 722 } 727 723 } 728 724 … … 732 728 @Consumes("multipart/form-data") 733 729 public Response registerCommentInComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input, 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 730 @PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 731 try { 732 Principal principal = checkAndGetUserPrincipal(); 733 UserCredentials userCredentials = getUserCredentials(principal); 734 if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) { 735 throw new UserUnauthorizedException("Cannot materialize authenticated user"); 736 } 737 // TODO: Add user/group param 738 ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials); 739 ComponentDescription description = registry.getComponentDescription(componentId); 740 if (description != null) { 741 LOG.info("Trying to register comment to " + componentId); 742 return registerComment(input, registry, userspace, description, principal, userCredentials); 743 } else { 744 LOG.error("Attempt to post comment on nonexistent component id (" + componentId + ") failed."); 745 return Response.serverError().entity("Invalid id, cannot comment on nonexistent component").build(); 746 } 747 } catch (UserUnauthorizedException ex) { 748 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 749 } 754 750 } 755 751 … … 759 755 @Consumes("multipart/form-data") 760 756 public Response registerCommentInProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input, 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 757 @PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException { 758 try { 759 Principal principal = checkAndGetUserPrincipal(); 760 UserCredentials userCredentials = getUserCredentials(principal); 761 if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) { 762 throw new UserUnauthorizedException("Cannot materialize authenticated user"); 763 } 764 // TODO: Add user/group param 765 ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials); 766 ProfileDescription description = registry.getProfileDescription(profileId); 767 if (description != null) { 768 LOG.info("Trying to register comment to " + profileId); 769 return registerComment(input, registry, userspace, description, principal, userCredentials); 770 } else { 771 LOG.error("Attempt to post comment on nonexistent profile id (" + profileId + ") failed."); 772 return Response.serverError().entity("Invalid id, cannot comment on nonexistent profile").build(); 773 } 774 } catch (UserUnauthorizedException ex) { 775 return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build(); 776 } 781 777 } 782 778 … … 785 781 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 786 782 public Response pingSession() { 787 788 789 790 791 792 793 794 795 783 boolean stillActive = false; 784 Principal userPrincipal = security.getUserPrincipal(); 785 LOG.info("ping by user: " + (userPrincipal == null ? "null" : userPrincipal.getName())); 786 if (request != null) { 787 if (userPrincipal != null && !ComponentRegistryFactory.ANONYMOUS_USER.equals(userPrincipal.getName())) { 788 stillActive = !((HttpServletRequest) request).getSession().isNew(); 789 } 790 } 791 return Response.ok().entity("<session stillActive=\"" + stillActive + "\"/>").build(); 796 792 } 797 793 798 794 private Response register(InputStream input, AbstractDescription desc, UserCredentials userCredentials, boolean userspace, 799 RegisterAction action) { 800 try { 801 // TODO: Add user/group param 802 ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials); 803 DescriptionValidator descriptionValidator = new DescriptionValidator(desc); 804 MDValidator validator = new MDValidator(input, desc, registry, getRegistry(getStatus(true)), componentRegistryFactory.getPublicRegistry()); 805 RegisterResponse response = new RegisterResponse(); 806 response.setIsInUserSpace(userspace); 807 validate(response, descriptionValidator, validator); 808 if (response.getErrors().isEmpty()) { 809 810 CMDComponentSpec spec = validator.getCMDComponentSpec(); 811 812 // Olha: removing filename from spec before it gets extended!!! recursion over all the components 813 setFileNamesFromListToNull(spec.getCMDComponent()); 814 815 816 817 try { 818 819 820 // Expand to check for recursion 821 registry.getExpander().expandNestedComponent(spec.getCMDComponent(), desc.getId()); 822 823 824 825 // Add profile 826 827 828 int returnCode = action.execute(desc, spec, response, registry); 829 if (returnCode == 0) { 830 response.setRegistered(true); 831 response.setDescription(desc); 832 } else { 833 response.setRegistered(false); 834 response.addError("Unable to register at this moment. Internal server error."); 835 } 836 } catch (ComponentRegistryException ex) { 837 // Recursion detected 838 response.setRegistered(false); 839 response.addError("Error while expanding specification. " + ex.getMessage()); 840 } 841 } else { 842 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray())); 843 response.setRegistered(false); 844 } 845 response.setIsProfile(desc.isProfile()); 846 return Response.ok(response).build(); 847 } finally { 848 try { 849 input.close();//either we read the input or there was an exception, we need to close it. 850 } catch (IOException e) { 851 LOG.error("Error when closing inputstream: ", e); 852 } 853 } 795 RegisterAction action) { 796 try { 797 // TODO: Add user/group param 798 ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials); 799 DescriptionValidator descriptionValidator = new DescriptionValidator(desc); 800 MDValidator validator = new MDValidator(input, desc, registry, getRegistry(getStatus(true)), componentRegistryFactory.getPublicRegistry()); 801 RegisterResponse response = new RegisterResponse(); 802 response.setIsInUserSpace(userspace); 803 validate(response, descriptionValidator, validator); 804 if (response.getErrors().isEmpty()) { 805 806 CMDComponentSpec spec = validator.getCMDComponentSpec(); 807 808 // removing filename from spec before it gets extended. recursion over all the components 809 setFileNamesFromListToNull(spec.getCMDComponent()); 810 811 try { 812 // Expand to check for recursion (todo: run on copy or do a dry-run so that the actual spec does not get expanded) 813 registry.getExpander().expandNestedComponent(spec.getCMDComponent(), desc.getId()); 814 815 // Add profile 816 int returnCode = action.execute(desc, spec, response, registry); 817 if (returnCode == 0) { 818 response.setRegistered(true); 819 response.setDescription(desc); 820 } else { 821 response.setRegistered(false); 822 response.addError("Unable to register at this moment. Internal server error."); 823 } 824 } catch (ComponentRegistryException ex) { 825 // Recursion detected 826 response.setRegistered(false); 827 response.addError("Error while expanding specification. " + ex.getMessage()); 828 } 829 } else { 830 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray())); 831 response.setRegistered(false); 832 } 833 response.setIsProfile(desc.isProfile()); 834 return Response.ok(response).build(); 835 } finally { 836 try { 837 input.close();//either we read the input or there was an exception, we need to close it. 838 } catch (IOException e) { 839 LOG.error("Error when closing inputstream: ", e); 840 } 841 } 854 842 } 855 843 856 844 private Response registerComment(InputStream input, ComponentRegistry registry, boolean userspace, 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 845 AbstractDescription description, Principal principal, UserCredentials userCredentials) { 846 try { 847 CommentValidator validator = new CommentValidator(input, description); 848 CommentResponse response = new CommentResponse(); 849 response.setIsInUserSpace(userspace); 850 validateComment(response, validator); 851 if (response.getErrors().isEmpty()) { 852 Comment com = validator.getCommentSpec(); 853 //int returnCode = action.executeComment(com, response, registry, principal.getName()); 854 855 // If user name is left empty, fill it using the user's display name 856 if (null == com.getUserName() || "".equals(com.getUserName())) { 857 if (userCredentials != null) { 858 com.setUserName(userCredentials.getDisplayName()); 859 } else { 860 com.setUserName(principal.getName()); 861 } 862 } 863 864 int returnCode = registry.registerComment(com, principal.getName()); 865 if (returnCode == 0) { 866 response.setRegistered(true); 867 response.setComment(com); 868 } else { 869 response.setRegistered(false); 870 response.addError("Unable to register at this moment. Internal server error."); 871 } 872 } else { 873 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray())); 874 response.setRegistered(false); 875 } 876 return Response.ok(response).build(); 877 } catch (ComponentRegistryException ex) { 878 LOG.error("Error while inserting comment: ", ex); 879 return Response.serverError().entity(ex.getMessage()).build(); 880 } finally { 881 try { 882 input.close();//either we read the input or there was an exception, we need to close it. 883 } catch (IOException e) { 884 LOG.error("Error when closing inputstream: ", e); 885 return Response.serverError().build(); 886 } 887 } 900 888 } 901 889 902 890 private ComponentDescription createNewComponentDescription() { 903 904 905 891 ComponentDescription desc = ComponentDescription.createNewDescription(); 892 desc.setHref(createXlink(desc.getId())); 893 return desc; 906 894 } 907 895 908 896 private ProfileDescription createNewProfileDescription() { 909 910 911 897 ProfileDescription desc = ProfileDescription.createNewDescription(); 898 desc.setHref(createXlink(desc.getId())); 899 return desc; 912 900 } 913 901 914 902 private String createXlink(String id) { 915 916 903 URI uri = uriInfo.getRequestUriBuilder().path(id).build(); 904 return uri.toString(); 917 905 } 918 906 … … 928 916 */ 929 917 private String getApplicationBaseURI() { 930 918 return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM); 931 919 } 932 920 933 921 private void validate(RegisterResponse response, Validator... validators) { 934 935 936 937 938 939 940 922 for (Validator validator : validators) { 923 if (!validator.validate()) { 924 for (String error : validator.getErrorMessages()) { 925 response.addError(error); 926 } 927 } 928 } 941 929 } 942 930 943 931 private void validateComment(CommentResponse response, Validator... validators) { 944 945 946 947 948 949 950 932 for (Validator validator : validators) { 933 if (!validator.validate()) { 934 for (String error : validator.getErrorMessages()) { 935 response.addError(error); 936 } 937 } 938 } 951 939 } 952 940 … … 955 943 */ 956 944 public void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory) { 957 this.componentRegistryFactory = componentRegistryFactory; 958 } 959 960 /// two muchually recursive methods below are used to set filenames of components (and their child components) to null 945 this.componentRegistryFactory = componentRegistryFactory; 946 } 947 961 948 /* 949 * Two muchually recursive methods below are used to set filenames of components (and their child components) to null 962 950 * @param List<CMDComponentType> listofcomponents the list of components whose filenames (and the children's names) are to be set to null 963 951 */ 964 952 public void setFileNamesFromListToNull(List<CMDComponentType> listofcomponents) { 965 953 966 967 968 954 for (CMDComponentType currentcomponent : listofcomponents) { 955 setFileNamesToNullCurrent(currentcomponent); 956 } 969 957 970 958 } … … 974 962 */ 975 963 public void setFileNamesToNullCurrent(CMDComponentType currentcomponent) { 976 977 currentcomponent.setFilename(null); 978 setFileNamesFromListToNull(currentcomponent.getCMDComponent()); 979 980 } 981 982 /* 983 * a working-horse method called to generate Rss feed for both, profiles and components 984 * 964 currentcomponent.setFilename(null); 965 setFileNamesFromListToNull(currentcomponent.getCMDComponent()); 966 } 967 968 /** 969 * Generates RSS feeds for profile and component descriptions 970 * 971 * @param <T> type of description 972 * @param limit number of items to include in the RSS 973 * @param descriptions descriptions to include 974 * @param channelDescription channel description 975 * @param channelTitle channel title 976 * @param channelLink channel link 977 * @return 978 * @throws ComponentRegistryException 979 * @throws ParseException 985 980 */ 986 protected <T extends AbstractDescription> Rss getRss(String limit, List<T> descs, 987 String description, String title, String link, boolean userspace) throws ComponentRegistryException, ParseException { 988 989 990 RssCreatorDescriptions rssCreator = new RssCreatorDescriptions(); 991 992 String space= ""; 993 if (userspace) {space="?space=user";}; 994 rssCreator.setUserspace(userspace); 995 996 rssCreator.setLink(link+space); 997 rssCreator.setDescription(description); 998 rssCreator.setTitle(title); 999 1000 Collections.sort(descs, AbstractDescription.COMPARE_ON_DATE); 1001 1002 int limitInt = Integer.parseInt(limit); 1003 1004 if (descs.size() < limitInt) { 1005 limitInt = descs.size(); 1006 }; 1007 List<T> sublist = descs.subList(0, limitInt); 1008 1009 Rss rss = rssCreator.makeRss(sublist); 1010 1011 return rss; 1012 } 1013 //////////////////////////////////////////////// 981 protected <T extends AbstractDescription> Rss getRss(String limit, List<T> descriptions, 982 String channelDescription, String channelTitle, String channelLink, boolean userspace) throws ComponentRegistryException, ParseException { 983 RssCreatorDescriptions rssCreator = new RssCreatorDescriptions(); 984 985 String space = ""; 986 if (userspace) { 987 space += "?space=user"; 988 }; 989 rssCreator.setUserspace(userspace); 990 991 rssCreator.setLink(channelLink + space); 992 rssCreator.setDescription(channelDescription); 993 rssCreator.setTitle(channelTitle); 994 995 Collections.sort(descriptions, AbstractDescription.COMPARE_ON_DATE); 996 997 int limitInt = Integer.parseInt(limit); 998 999 if (descriptions.size() < limitInt) { 1000 limitInt = descriptions.size(); 1001 } 1002 List<T> sublist = descriptions.subList(0, limitInt); 1003 1004 Rss rss = rssCreator.makeRss(sublist); 1005 1006 return rss; 1007 } 1014 1008 1015 1009 @GET … … 1017 1011 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 1018 1012 public Rss getRssComponent(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException { 1019 1020 List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions(); 1021 1022 1023 String title; 1024 if (userspace) { title= "Workspace components";} 1025 else {title= "Public components"; 1026 } 1027 1028 Rss rss = getRss(limit, components,"Updates for components" , title, getApplicationBaseURI() + "/", userspace); 1029 1030 LOG.info("Releasing " + limit + " most recent registered components into the world"); 1031 1032 1033 return rss; 1034 } 1035 1036 //////////////////////////////////////////////// 1013 final List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions(); 1014 1015 final String title = userspace ? "Workspace components" : "Public components"; 1016 final Rss rss = getRss(limit, components, "Updates for components", title, getApplicationBaseURI() + "/", userspace); 1017 LOG.info("Releasing RSS of " + limit + " most recently registered components"); 1018 1019 return rss; 1020 } 1021 1037 1022 @GET 1038 1023 @Path("/profiles/rss") 1039 1024 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 1040 1025 public Rss getRssProfile(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException { 1041 1042 1043 // ?? How to get rid of the deprecated stuff ?? 1044 List<ProfileDescription> profiles = getRegistry(getStatus(userspace)).getProfileDescriptions(); 1045 1046 String title; 1047 if (userspace) { title= "Workspace profiles";} 1048 else {title= "Public profiles"; 1049 } 1050 1051 Rss rss = getRss(limit, profiles, "Updates for profiles", title, getApplicationBaseURI() + "/", userspace); 1052 1053 1054 LOG.info("Releasing " + limit + " most recent registered profiles into the world"); 1055 return rss; 1056 } 1057 1058 1059 1060 /////////////////////////////////////////////////////////// 1061 /* 1062 * a working-horse method for obtaing a comment for a given profile or a component (via the profile/component's and cpmment's Id) 1026 // ?? How to get rid of the deprecated stuff ?? 1027 List<ProfileDescription> profiles = getRegistry(getStatus(userspace)).getProfileDescriptions(); 1028 1029 final String title = userspace ? "Workspace profiles" : "Public profiles"; 1030 Rss rss = getRss(limit, profiles, "Updates for profiles", title, getApplicationBaseURI() + "/", userspace); 1031 LOG.info("Releasing RSS of " + limit + " most recently registered profiles"); 1032 return rss; 1033 } 1034 1035 /** 1036 * Obtains a comment for a given profile or a component (via the profile/component's and comment's Id) 1037 * 1038 * @param limit 1039 * @param comments 1040 * @param channelDescription 1041 * @param channelTitle 1042 * @param itemId 1043 * @param baseUri 1044 * @return 1045 * @throws ComponentRegistryException 1046 * @throws ParseException 1047 * @throws IOException 1048 * @throws JAXBException 1063 1049 */ 1064 protected Rss getRssOfComments(String limit, List<Comment> comments, String description, 1065 String title, String id, String baseUri, boolean userspace) throws ComponentRegistryException, ParseException, IOException, JAXBException { 1066 1067 Collections.sort(comments, Comment.COMPARE_ON_DATE); 1068 1069 int limitInt = Integer.parseInt(limit); 1070 if (comments.size() < limitInt) { 1071 limitInt = comments.size(); 1072 }; 1073 List<Comment> sublist = comments.subList(0, limitInt); 1074 1075 RssCreatorComments instance = new RssCreatorComments(); 1076 1077 String space= ""; 1078 if (userspace) {space="&space=user";}; 1079 instance.setUserspace(userspace); 1080 1081 instance.setDescription(description); 1082 instance.setLink(baseUri + "?item=" + id + space+ "&browserview=comments"); 1083 instance.setTitle(title); 1084 1085 Rss result = instance.makeRss(sublist); 1086 return result; 1087 1088 } 1089 1090 /////////////////////////////////////////////////////// 1050 protected Rss getRssOfComments(String limit, List<Comment> comments, String channelDescription, 1051 String channelTitle, String itemId, String baseUri, boolean userspace) throws ComponentRegistryException, ParseException, IOException, JAXBException { 1052 Collections 1053 .sort(comments, Comment.COMPARE_ON_DATE); 1054 1055 int limitInt = Integer.parseInt(limit); 1056 if (comments.size() < limitInt) { 1057 limitInt = comments.size(); 1058 } 1059 List<Comment> sublist = comments.subList(0, limitInt); 1060 RssCreatorComments rssCreator = new RssCreatorComments(); 1061 1062 String space = ""; 1063 if (userspace) { 1064 space = "&space=user"; 1065 } 1066 rssCreator.setUserspace(userspace); 1067 rssCreator.setDescription(channelDescription); 1068 rssCreator.setLink(baseUri + "?item=" + itemId + space + "&browserview=comments"); 1069 rssCreator.setTitle(channelTitle); 1070 1071 return rssCreator.makeRss(sublist); 1072 } 1073 1091 1074 @GET 1092 1075 @Path("/profiles/{profileId}/comments/rss") 1093 1076 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 1094 1077 public Rss getRssOfCommentsFromProfile(@PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, IOException, JAXBException, ParseException { 1095 1096 1097 final Principal principal = security.getUserPrincipal(); 1098 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal); 1099 1100 1101 String title = "Comments feed for the profile \"" 1102 + getRegistry(getStatus(userspace)).getProfileDescription(profileId).getName() 1103 + "\" "; 1104 1105 Rss result = getRssOfComments(limit, comments, "Update of comments for the current profile", 1106 title, profileId, getApplicationBaseURI() + "/", userspace); 1107 1108 1109 return result; 1110 } 1111 1112 ////////////////////////////// 1078 final Principal principal = security.getUserPrincipal(); 1079 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal); 1080 1081 final String profileName = getRegistry(getStatus(userspace)).getProfileDescription(profileId).getName(); 1082 final String title = String.format("Comments feed for the profile \"%1$s\"", profileName); 1083 Rss result = getRssOfComments(limit, comments, "Update of comments for the current profile", 1084 title, profileId, getApplicationBaseURI() + "/", userspace); 1085 1086 return result; 1087 } 1088 1113 1089 @GET 1114 1090 @Path("/components/{componentId}/comments/rss") 1115 1091 @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) 1116 1092 public Rss getRssOfCommentsFromComponent(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, IOException, JAXBException, ParseException { 1117 1118 1119 final Principal principal = security.getUserPrincipal(); 1120 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal); 1121 1122 String title = "Comments feed for the component \"" 1123 + getRegistry(getStatus(userspace)).getComponentDescription(componentId).getName() 1124 + "\" "; 1125 1126 Rss result = getRssOfComments(limit, comments, "Update of comments for the current component", 1127 title, componentId, getApplicationBaseURI() + "/", userspace); 1128 1129 1130 1131 return result; 1132 } 1133 1134 1093 final Principal principal = security.getUserPrincipal(); 1094 List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal); 1095 1096 final String componentName = getRegistry(getStatus(userspace)).getComponentDescription(componentId).getName(); 1097 final String title = String.format("Comments feed for the component \"%1$s\" ", componentName); 1098 Rss result = getRssOfComments(limit, comments, "Update of comments for the current component", 1099 title, componentId, getApplicationBaseURI() + "/", userspace); 1100 1101 return result; 1102 } 1135 1103 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/RssCreatorCommentsTest.java
r2270 r2287 1 /*2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */5 1 package clarin.cmdi.componentregistry; 6 2 7 3 import clarin.cmdi.componentregistry.model.Comment; 8 import clarin.cmdi.componentregistry.model.ProfileDescription;9 4 import clarin.cmdi.componentregistry.rss.Rss; 10 5 import clarin.cmdi.componentregistry.rss.RssItem; … … 14 9 import java.util.List; 15 10 import org.junit.Test; 11 16 12 import static org.junit.Assert.*; 13 17 14 /** 18 15 * … … 20 17 */ 21 18 public class RssCreatorCommentsTest { 22 23 24 25 private Comment makeTestComment(boolean canDelete, boolean isFromProfile, String comtext, String date, String commentId, 26 String descrId, String userName){ 27 28 Comment comm =new Comment(); 29 30 comm.setCanDelete(canDelete); 31 comm.setComment(comtext); 32 comm.setCommentDate(date); 33 if (isFromProfile) {comm.setProfileDescriptionId(descrId);} 34 else {comm.setComponentDescriptionId(descrId);} 35 comm.setId(commentId); 36 comm.setUserName(userName); 37 38 39 40 return comm; 41 19 20 private Comment makeTestComment(boolean canDelete, boolean isFromProfile, String comtext, String date, String commentId, 21 String descrId, String userName) { 22 Comment comm = new Comment(); 23 24 comm.setCanDelete(canDelete); 25 comm.setComment(comtext); 26 comm.setCommentDate(date); 27 if (isFromProfile) { 28 comm.setProfileDescriptionId(descrId); 29 } else { 30 comm.setComponentDescriptionId(descrId); 31 } 32 comm.setId(commentId); 33 comm.setUserName(userName); 34 35 return comm; 42 36 } 43 37 44 38 /** 45 * 39 * 46 40 */ 47 48 private void compareInputsVsRssItems(String href, String commtext, String date, String title, RssItem rssItem){ 49 50 51 assertEquals(href, rssItem.getGuid().getValue()); 52 assertEquals(href, rssItem.getLink()); 53 assertEquals(commtext, rssItem.getDescription()); 54 assertEquals(date, rssItem.getPubDate()); 55 assertEquals(title, rssItem.getTitle()); 56 41 private void compareInputsVsRssItems(String href, String commtext, String date, String title, RssItem rssItem) { 42 assertEquals(href, rssItem.getGuid().getValue()); 43 assertEquals(href, rssItem.getLink()); 44 assertEquals(commtext, rssItem.getDescription()); 45 assertEquals(date, rssItem.getPubDate()); 46 assertEquals(title, rssItem.getTitle()); 47 57 48 } 58 59 60 49 61 50 @Test 62 public void testMakeRss() throws ParseException{ 63 64 String testPrfId = "p_1234"; 65 String href = "http://catalog.clarin.eu/ds/ComponentRegistry/?item="+testPrfId+"&view=comments"; 66 Boolean isFromProfile = true; 67 68 69 70 71 Comment comm1 = makeTestComment(true, isFromProfile, "this is comment # 1", "2012-04-02T11:38:23+00:00", "commentId1", testPrfId, 72 "userello"); 73 74 Comment comm2 = makeTestComment(false, isFromProfile, "this is comment # 2", "2011-04-02T11:38:22+00:00", "commentId2", testPrfId, 75 "userino"); 76 77 Comment comm3 = makeTestComment(true, isFromProfile, "this is comment # 3", "2010-05-02T11:38:22+00:00", "commentId3", testPrfId, 78 "userito"); 79 80 Comment[] commar = {comm1, comm2, comm3}; 81 List<Comment> comms = new ArrayList<Comment>(Arrays.asList(commar)); 82 83 84 85 RssCreatorComments instance = new RssCreatorComments(); 86 instance.setLink(href); 87 88 instance.setVersion(3.0); 89 90 Rss result = instance.makeRss(comms); 91 92 assertEquals(Double.toString(result.getVersion()), "3.0"); // now, check if updating version has taken place 93 94 String rfcdate1 = instance.getRFCDateTime("2012-04-02T11:38:23+00:00"); 95 String rfcdate2 = instance.getRFCDateTime("2011-04-02T11:38:22+00:00"); 96 String rfcdate3 = instance.getRFCDateTime("2010-05-02T11:38:22+00:00"); 97 98 List<RssItem> resitems = result.getChannel().getItem(); 99 100 101 compareInputsVsRssItems(href+"&commentId=commentId1", "this is comment # 1", rfcdate1, 102 instance.makeCommentTitle("commentId1", "userello"), resitems.get(0)); 103 compareInputsVsRssItems(href+"&commentId=commentId2", "this is comment # 2", rfcdate2, 104 instance.makeCommentTitle("commentId2", "userino"), 105 resitems.get(1)); 106 compareInputsVsRssItems(href+"&commentId=commentId3", "this is comment # 3", rfcdate3, 107 instance.makeCommentTitle("commentId3", "userito") 108 , resitems.get(2)); 109 110 System.out.println(" "); 111 for (int i=0; i<3; i++) { 112 System.out.print("Rss-item for comment "); 113 System.out.println(i); 114 System.out.println(resitems.get(i).getTitle()); 115 System.out.println(resitems.get(i).getPubDate()); 116 System.out.println(resitems.get(i).getDescription()); 117 System.out.println(resitems.get(i).getLink()); 118 System.out.println(resitems.get(i).getGuid().getValue()); 119 System.out.println(" "); 120 } 121 122 51 public void testMakeRss() throws ParseException { 52 String testPrfId = "p_1234"; 53 String href = "http://catalog.clarin.eu/ds/ComponentRegistry/?item=" + testPrfId + "&view=comments"; 54 boolean isFromProfile = true; 55 56 Comment comm1 = makeTestComment(true, isFromProfile, "this is comment # 1", "2012-04-02T11:38:23+00:00", "commentId1", testPrfId, 57 "userello"); 58 Comment comm2 = makeTestComment(false, isFromProfile, "this is comment # 2", "2011-04-02T11:38:22+00:00", "commentId2", testPrfId, 59 "userino"); 60 Comment comm3 = makeTestComment(true, isFromProfile, "this is comment # 3", "2010-05-02T11:38:22+00:00", "commentId3", testPrfId, 61 "userito"); 62 List<Comment> comms = new ArrayList<Comment>(Arrays.asList(comm1, comm2, comm3)); 63 64 RssCreatorComments instance = new RssCreatorComments(); 65 instance.setLink(href); 66 instance.setVersion(3.0); 67 68 Rss result = instance.makeRss(comms); 69 70 assertEquals(Double.toString(result.getVersion()), "3.0"); // now, check if updating version has taken place 71 72 String rfcdate1 = instance.getRFCDateTime("2012-04-02T11:38:23+00:00"); 73 String rfcdate2 = instance.getRFCDateTime("2011-04-02T11:38:22+00:00"); 74 String rfcdate3 = instance.getRFCDateTime("2010-05-02T11:38:22+00:00"); 75 76 List<RssItem> resitems = result.getChannel().getItem(); 77 78 compareInputsVsRssItems(href + "&commentId=commentId1", "this is comment # 1", rfcdate1, 79 "Comment commentId1\nby userello", resitems.get(0)); 80 compareInputsVsRssItems(href + "&commentId=commentId2", "this is comment # 2", rfcdate2, 81 "Comment commentId2\nby userino", resitems.get(1)); 82 compareInputsVsRssItems(href + "&commentId=commentId3", "this is comment # 3", rfcdate3, 83 "Comment commentId3\nby userito", resitems.get(2)); 123 84 } 124 125 /*@Test126 public void testMakeRssNullComm() {127 128 System.out.println("fromArgToRssItem");129 130 131 Comment comm1 = null;132 133 List<Comment> comms = new ArrayList<Comment>(0);134 comms.add(comm1);135 136 RssCreatorComments instance = new RssCreatorComments();137 Rss result = instance.makeRss(comms);138 139 140 assertEquals(null, result.getChannel().getItem());141 142 }*/143 144 145 85 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/RssMarshallingTest.java
r2257 r2287 1 /*2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */5 1 package clarin.cmdi.componentregistry; 6 2 -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/CMDComponentSetFilenamesToNullTestHelper.java
r2284 r2287 13 13 import java.util.List; 14 14 import javax.xml.bind.JAXBException; 15 import org.junit.Test; 15 16 16 import static org.junit.Assert.*; 17 17 -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java
r2223 r2287 2 2 3 3 import clarin.cmdi.componentregistry.ComponentRegistry; 4 import clarin.cmdi.componentregistry.ComponentRegistryException;5 4 import clarin.cmdi.componentregistry.ComponentRegistryFactory; 6 5 import clarin.cmdi.componentregistry.ComponentStatus; … … 20 19 import com.sun.jersey.multipart.FormDataMultiPart; 21 20 import java.io.ByteArrayInputStream; 21 import java.util.ArrayList; 22 22 import java.util.Date; 23 23 import java.util.List; … … 34 34 35 35 import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM; 36 import java.util.ArrayList;37 36 import static org.junit.Assert.*; 38 37 … … 1143 1142 assertEquals(MDValidator.MISMATCH_ERROR, response.getErrors().get(0)); 1144 1143 } 1145 1146 1147 1144 1148 1145 /** 1149 1146 * creates a tree-like component, whose root has two kids, and the kids have three their own kids each 1150 1147 * the corresponding filenames are: 1151 1148 * "wortel", "nodel-L", "node-R", "leaf-LL", "leaf-LM", "leaf-LR", "leaf-RL", "leaf-RM", "leaf-RR" 1152 * @throws Exception 1149 * 1150 * @throws Exception 1153 1151 */ 1154 @Test 1152 @Test 1155 1153 public void testSetFilenamesToNull() throws Exception { 1156 1157 // helper assists in generating a test component 1158 CMDComponentSetFilenamesToNullTestHelper helper = new CMDComponentSetFilenamesToNullTestHelper(); 1159 1160 // making an (up to ternary) tree of test components 1161 //inductive explaination of the variable names, an example: leaf-LM is the middle child of the nodeL 1162 // the filename is this leaf is "leaf-LM" 1163 1164 // making children of the node L 1165 CMDComponentType leafLR = helper.makeTestComponent("leaf-LR", null); 1166 CMDComponentType leafLM = helper.makeTestComponent("leaf-LM", null); 1167 CMDComponentType leafLL = helper.makeTestComponent("leaf-LL", null); 1168 1169 1170 // making node L 1171 List<CMDComponentType> nodeLchild = (new ArrayList<CMDComponentType>()); 1172 nodeLchild.add(leafLL); nodeLchild.add(leafLM); nodeLchild.add(leafLR); 1173 CMDComponentType nodeL = helper.makeTestComponent("node-L",nodeLchild); 1174 1175 1176 // making children of the node R 1177 CMDComponentType leafRR = helper.makeTestComponent("leaf-RR", null); 1178 CMDComponentType leafRM = helper.makeTestComponent("leaf-RM", null); 1179 CMDComponentType leafRL = helper.makeTestComponent("leaf-RL", null); 1180 1181 // making node R 1182 List<CMDComponentType> nodeRchild = (new ArrayList<CMDComponentType>()); 1183 nodeRchild.add(leafRL); nodeRchild.add(leafRM); nodeRchild.add(leafRR); 1184 CMDComponentType nodeR = helper.makeTestComponent("node-R",nodeRchild); 1185 1186 // making the root, which has children NodeL and nodeR 1187 List<CMDComponentType> wortelchild = (new ArrayList<CMDComponentType>()); 1188 wortelchild.add(nodeL); wortelchild.add(nodeR); 1189 CMDComponentType wortel = helper.makeTestComponent("wortel", wortelchild); 1190 1191 //checking if the test compnent has the expected structure and the expected filenames 1192 //ALSO this checking code below shows the strtucture of the tree 1193 1194 assertEquals(wortel.getCMDComponent().size(), 2); 1195 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().size(), 3); 1196 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().size(), 3); 1197 1198 assertEquals(wortel.getFilename(), "wortel"); 1199 1200 assertEquals(wortel.getCMDComponent().get(0).getFilename(), "node-L"); 1201 assertEquals(wortel.getCMDComponent().get(1).getFilename(), "node-R"); 1202 1203 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(0).getFilename(), "leaf-LL"); 1204 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(1).getFilename(), "leaf-LM"); 1205 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(2).getFilename(), "leaf-LR"); 1206 1207 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(0).getFilename(), "leaf-RL"); 1208 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(1).getFilename(), "leaf-RM"); 1209 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(2).getFilename(), "leaf-RR"); 1210 1211 1212 // the actual job 1213 // nulling the filenames will be called as a method of testrestservice 1214 ComponentRegistryRestService restservice = new ComponentRegistryRestService(); 1215 restservice.setFileNamesToNullCurrent(wortel); 1216 1217 1218 // check if the filenames are nulled 1219 assertEquals(wortel.getFilename(), null); 1220 1221 assertEquals(wortel.getCMDComponent().get(0).getFilename(), null); 1222 assertEquals(wortel.getCMDComponent().get(1).getFilename(), null); 1223 1224 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(0).getFilename(), null); 1225 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(1).getFilename(), null); 1226 assertEquals(wortel.getCMDComponent().get(0).getCMDComponent().get(2).getFilename(), null); 1227 1228 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(0).getFilename(), null); 1229 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(1).getFilename(), null); 1230 assertEquals(wortel.getCMDComponent().get(1).getCMDComponent().get(2).getFilename(), null); 1231 1232 1233 1234 } 1235 1236 1237 1154 1155 // helper assists in generating a test component 1156 CMDComponentSetFilenamesToNullTestHelper helper = new CMDComponentSetFilenamesToNullTestHelper(); 1157 1158 // making an (up to ternary) tree of test components 1159 //inductive explaination of the variable names, an example: leaf-LM is the middle child of the nodeL 1160 // the filename is this leaf is "leaf-LM" 1161 1162 // making children of the node L 1163 CMDComponentType leafLR = helper.makeTestComponent("leaf-LR", null); 1164 CMDComponentType leafLM = helper.makeTestComponent("leaf-LM", null); 1165 CMDComponentType leafLL = helper.makeTestComponent("leaf-LL", null); 1166 1167 1168 // making node L 1169 List<CMDComponentType> nodeLchild = (new ArrayList<CMDComponentType>()); 1170 nodeLchild.add(leafLL); 1171 nodeLchild.add(leafLM); 1172 nodeLchild.add(leafLR); 1173 CMDComponentType nodeL = helper.makeTestComponent("node-L", nodeLchild); 1174 1175 1176 // making children of the node R 1177 CMDComponentType leafRR = helper.makeTestComponent("leaf-RR", null); 1178 CMDComponentType leafRM = helper.makeTestComponent("leaf-RM", null); 1179 CMDComponentType leafRL = helper.makeTestComponent("leaf-RL", null); 1180 1181 // making node R 1182 List<CMDComponentType> nodeRchild = (new ArrayList<CMDComponentType>()); 1183 nodeRchild.add(leafRL); 1184 nodeRchild.add(leafRM); 1185 nodeRchild.add(leafRR); 1186 CMDComponentType nodeR = helper.makeTestComponent("node-R", nodeRchild); 1187 1188 // making the root, which has children NodeL and nodeR 1189 List<CMDComponentType> wortelchild = (new ArrayList<CMDComponentType>()); 1190 wortelchild.add(nodeL); 1191 wortelchild.add(nodeR); 1192 CMDComponentType root = helper.makeTestComponent("wortel", wortelchild); 1193 1194 //checking if the test compnent has the expected structure and the expected filenames 1195 //ALSO this checking code below shows the strtucture of the tree 1196 1197 assertEquals(root.getCMDComponent().size(), 2); 1198 assertEquals(root.getCMDComponent().get(0).getCMDComponent().size(), 3); 1199 assertEquals(root.getCMDComponent().get(1).getCMDComponent().size(), 3); 1200 1201 assertEquals(root.getFilename(), "wortel"); 1202 1203 assertEquals(root.getCMDComponent().get(0).getFilename(), "node-L"); 1204 assertEquals(root.getCMDComponent().get(1).getFilename(), "node-R"); 1205 1206 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(0).getFilename(), "leaf-LL"); 1207 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(1).getFilename(), "leaf-LM"); 1208 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(2).getFilename(), "leaf-LR"); 1209 1210 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(0).getFilename(), "leaf-RL"); 1211 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(1).getFilename(), "leaf-RM"); 1212 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(2).getFilename(), "leaf-RR"); 1213 1214 1215 // the actual job 1216 // nulling the filenames will be called as a method of testrestservice 1217 ComponentRegistryRestService restservice = new ComponentRegistryRestService(); 1218 restservice.setFileNamesToNullCurrent(root); 1219 1220 1221 // check if the filenames are nulled 1222 assertEquals(root.getFilename(), null); 1223 1224 assertEquals(root.getCMDComponent().get(0).getFilename(), null); 1225 assertEquals(root.getCMDComponent().get(1).getFilename(), null); 1226 1227 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(0).getFilename(), null); 1228 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(1).getFilename(), null); 1229 assertEquals(root.getCMDComponent().get(0).getCMDComponent().get(2).getFilename(), null); 1230 1231 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(0).getFilename(), null); 1232 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(1).getFilename(), null); 1233 assertEquals(root.getCMDComponent().get(1).getCMDComponent().get(2).getFilename(), null); 1234 } 1238 1235 } -
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/xmlRssGeneratingRunner.java
r2286 r2287 1 /*2 * To change this template, choose Tools | Templates3 * and open the template in the editor.4 */5 1 package clarin.cmdi.componentregistry.rest; 6 2 … … 30 26 */ 31 27 public class xmlRssGeneratingRunner { 32 33 34 35 ////////////////36 37 public void printIds(List<AbstractDescription> desc){38 28 39 for (AbstractDescription current : desc) { 40 String currentId = current.getId(); 41 System.out.println(currentId); 42 } 43 44 } 45 46 47 private static void printXmlRssToFile(Rss rssObject) throws IOException, JAXBException{ 48 49 String path = RegistryTestHelper.openTestDir("testRss"); 50 String os = MDMarshaller.marshalToString(rssObject); 51 RegistryTestHelper.writeStringToFile(os, path + "testRssResl.xml"); 52 29 public void printIds(List<AbstractDescription> desc) { 30 for (AbstractDescription current : desc) { 31 String currentId = current.getId(); 32 System.out.println(currentId); 33 } 53 34 } 54 55 public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException{56 57 System.out.println("Type 1, or 2, or 3, or 4, if you want to check Rss generaion ");58 System.out.print("for profiles, components, profile comments or component comments respectively: >> ");59 60 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));61 String buffer = null;62 35 63 // read the username from the command-line; need to use try/catch with the 64 // readLine() method 65 try { 66 buffer = br.readLine(); 67 } catch (IOException ioe) { 68 System.out.println("IO error trying get the number"); 69 System.exit(1); 70 } 71 72 int kind=Integer.parseInt(buffer); 73 74 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContextJDBC.xml"); 75 ComponentRegistry registry = ((ComponentRegistryFactory) applicationContext.getBean("componentRegistryFactory")).getPublicRegistry(); 76 77 ComponentRegistryRestService restService = new ComponentRegistryRestService(); 78 Rss rss = null; 79 String baseUri = "http://localhost:8080/ComponentRegistry/"; // used only as a nice URi-example content for the "link"-field 80 // in this test we do not click on link, we just generate an Rss xml-file to validate it 81 // using one of the on-line rss-source vaidators 82 83 if (kind == 1){ // testing Rss for profiles 84 List<ProfileDescription> profs = registry.getProfileDescriptions(); 85 86 System.out.println(profs.size()); 87 Collections.sort(profs, AbstractDescription.COMPARE_ON_DATE); 88 System.out.println(profs.size()); 89 90 System.out.println("check if the profiles are sorted in a proper way, by the dates "); 91 for (ProfileDescription pdesc : profs) { 92 System.out.println(pdesc.getRegistrationDate()); 93 } 94 95 rss = restService.getRss(Integer.toString(profs.size()), profs,"Updates for profiles" , "RSS for public profiles", baseUri, false); 96 System.out.println(rss.getChannel().getItem().size()); 97 98 } 99 100 101 if (kind == 2){ // testing rss for components 102 List<ComponentDescription> comps = registry.getComponentDescriptions(); 103 104 Collections.sort(comps, AbstractDescription.COMPARE_ON_DATE); 105 106 System.out.println("check if the components are sorted in a proper way, by the dates"); 107 for (ComponentDescription cdesc : comps) { 108 System.out.println(cdesc.getRegistrationDate()); 109 } 110 rss = restService.getRss(Integer.toString(comps.size()), comps,"Updates for components" , "RSS for public components", baseUri, false); 111 } 112 113 if (kind == 3){ // testing Rss comments for profiles 114 String profileId = "clarin.eu:cr1:p_1284723009187"; 115 List<Comment> comms = registry.getCommentsInProfile(profileId, null); 116 117 Collections.sort(comms, Comment.COMPARE_ON_DATE); 118 119 System.out.println("check if the comments are sorted in a proper way"); 120 for (Comment comm : comms) { 121 System.out.println(comm.getCommentDate()); 122 } 123 124 rss = restService.getRssOfComments(Integer.toString(comms.size()), comms, "Updates for the profile " + profileId+" comments " , "RSS for profile comments", profileId, baseUri, false); 125 } 126 127 if (kind == 4){ // testing rss comments for components 128 String componentId = "clarin.eu:cr1:c_1288172614011"; 129 List<Comment> comms = registry.getCommentsInComponent(componentId, null); 130 Collections.sort(comms, Comment.COMPARE_ON_DATE); 131 132 System.out.println("check if the comments are sorted in a proper way"); 133 for (Comment comm : comms) { 134 System.out.println(comm.getCommentDate()); 135 } 136 137 rss = restService.getRssOfComments("10", comms, "Updates for the component " +componentId+" comments", "RSS for component comments", "clarin.eu:cr1:p_1284723009187", baseUri, false); 138 } 139 140 printXmlRssToFile(rss); 141 } 142 36 private static void printXmlRssToFile(Rss rssObject) throws IOException, JAXBException { 37 38 String path = RegistryTestHelper.openTestDir("testRss"); 39 String os = MDMarshaller.marshalToString(rssObject); 40 RegistryTestHelper.writeStringToFile(os, path + "testRssResl.xml"); 41 42 } 43 44 public static void main(String args[]) throws ComponentRegistryException, ParseException, IOException, JAXBException { 45 46 System.out.println("Type 1, or 2, or 3, or 4, if you want to check Rss generaion "); 47 System.out.print("for profiles, components, profile comments or component comments respectively: >> "); 48 49 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 50 String buffer = null; 51 52 // read the username from the command-line; need to use try/catch with the 53 // readLine() method 54 try { 55 buffer = br.readLine(); 56 } catch (IOException ioe) { 57 System.out.println("IO error trying get the number"); 58 System.exit(1); 59 } 60 61 int kind = Integer.parseInt(buffer); 62 63 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContextJDBC.xml"); 64 ComponentRegistry registry = ((ComponentRegistryFactory) applicationContext.getBean("componentRegistryFactory")).getPublicRegistry(); 65 66 ComponentRegistryRestService restService = new ComponentRegistryRestService(); 67 Rss rss = null; 68 String baseUri = "http://localhost:8080/ComponentRegistry/"; // used only as a nice URi-example content for the "link"-field 69 // in this test we do not click on link, we just generate an Rss xml-file to validate it 70 // using one of the on-line rss-source vaidators 71 72 if (kind == 1) { // testing Rss for profiles 73 List<ProfileDescription> profs = registry.getProfileDescriptions(); 74 75 System.out.println(profs.size()); 76 Collections.sort(profs, AbstractDescription.COMPARE_ON_DATE); 77 System.out.println(profs.size()); 78 79 System.out.println("check if the profiles are sorted in a proper way, by the dates "); 80 for (ProfileDescription pdesc : profs) { 81 System.out.println(pdesc.getRegistrationDate()); 82 } 83 84 rss = restService.getRss(Integer.toString(profs.size()), profs, "Updates for profiles", "RSS for public profiles", baseUri, false); 85 System.out.println(rss.getChannel().getItem().size()); 86 87 } 88 89 90 if (kind == 2) { // testing rss for components 91 List<ComponentDescription> comps = registry.getComponentDescriptions(); 92 93 Collections.sort(comps, AbstractDescription.COMPARE_ON_DATE); 94 95 System.out.println("check if the components are sorted in a proper way, by the dates"); 96 for (ComponentDescription cdesc : comps) { 97 System.out.println(cdesc.getRegistrationDate()); 98 } 99 rss = restService.getRss(Integer.toString(comps.size()), comps, "Updates for components", "RSS for public components", baseUri, false); 100 } 101 102 if (kind == 3) { // testing Rss comments for profiles 103 String profileId = "clarin.eu:cr1:p_1284723009187"; 104 List<Comment> comms = registry.getCommentsInProfile(profileId, null); 105 106 Collections.sort(comms, Comment.COMPARE_ON_DATE); 107 108 System.out.println("check if the comments are sorted in a proper way"); 109 for (Comment comm : comms) { 110 System.out.println(comm.getCommentDate()); 111 } 112 113 rss = restService.getRssOfComments(Integer.toString(comms.size()), comms, "Updates for the profile " + profileId + " comments ", "RSS for profile comments", profileId, baseUri, false); 114 } 115 116 if (kind == 4) { // testing rss comments for components 117 String componentId = "clarin.eu:cr1:c_1288172614011"; 118 List<Comment> comms = registry.getCommentsInComponent(componentId, null); 119 Collections.sort(comms, Comment.COMPARE_ON_DATE); 120 121 System.out.println("check if the comments are sorted in a proper way"); 122 for (Comment comm : comms) { 123 System.out.println(comm.getCommentDate()); 124 } 125 126 rss = restService.getRssOfComments("10", comms, "Updates for the component " + componentId + " comments", "RSS for component comments", "clarin.eu:cr1:p_1284723009187", baseUri, false); 127 } 128 129 printXmlRssToFile(rss); 130 } 143 131 }
Note: See TracChangeset
for help on using the changeset viewer.