Changeset 2287


Ignore:
Timestamp:
10/05/12 11:47:03 (12 years ago)
Author:
twagoo
Message:

Some cleaning up and refactoring after code review

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  
    22
    33import clarin.cmdi.componentregistry.model.AbstractDescription;
    4 import clarin.cmdi.componentregistry.rest.ComponentRegistryRestService;
    54import clarin.cmdi.componentregistry.rss.Category;
    65import clarin.cmdi.componentregistry.rss.Cloud;
     
    98import clarin.cmdi.componentregistry.rss.Rss;
    109import clarin.cmdi.componentregistry.rss.RssChannel;
    11 
    1210import clarin.cmdi.componentregistry.rss.RssItem;
    1311import clarin.cmdi.componentregistry.rss.SkipDaysList;
     
    1816import java.text.SimpleDateFormat;
    1917import java.util.ArrayList;
    20 import java.util.Comparator;
    2118import java.util.Date;
    2219import java.util.List;
    23 import javax.xml.bind.DatatypeConverter;
    24 import org.slf4j.Logger;
    25 import org.slf4j.LoggerFactory;
    2620
    2721/**
     
    3125public abstract class RssCreator<T> { // extends nothing so far, throuw nothing // make it abstract
    3226
    33    
    3427    private String title;
    3528    private String link;
     
    5447    private double version = 2.0; // of an rss
    5548
    56    
    57 
    5849    public double getVersion() {
    59         return (version);
     50        return (version);
    6051    }
    6152
     
    6556     */
    6657    public void setVersion(double version) {
    67         this.version = version;
     58        this.version = version;
    6859    }
    6960
     
    7566     */
    7667    public void setTitle(String value) {
    77         this.title = value;
     68        this.title = value;
    7869    }
    7970
    8071    public String getTitle() {
    81         return this.title;
     72        return this.title;
    8273    }
    8374
     
    8980     */
    9081    public void setLink(String value) {
    91         this.link = value;
     82        this.link = value;
    9283    }
    9384
    9485    public String getLink() {
    95         return this.link;
     86        return this.link;
    9687    }
    9788   
     
    110101     */
    111102    public void setDescription(String value) {
    112         this.description = value;
     103        this.description = value;
    113104    }
    114105
     
    120111     */
    121112    public void setLanguage(String value) {
    122         this.language = value;
     113        this.language = value;
    123114    }
    124115
     
    130121     */
    131122    public void setCopyright(String value) {
    132         this.copyright = value;
     123        this.copyright = value;
    133124    }
    134125
     
    140131     */
    141132    public void setManagingEditor(String value) {
    142         this.managingEditor = value;
     133        this.managingEditor = value;
    143134    }
    144135
     
    150141     */
    151142    public void setWebMaster(String value) {
    152         this.webMaster = value;
     143        this.webMaster = value;
    153144    }
    154145
     
    160151     */
    161152    public void setPubDate(String value) {
    162         this.pubDate = value;
     153        this.pubDate = value;
    163154    }
    164155
     
    170161     */
    171162    public void setLastBuildDate(String value) {
    172         this.lastBuildDate = value;
     163        this.lastBuildDate = value;
    173164    }
    174165
     
    180171     */
    181172    public void setCategory(Category value) {
    182         this.category = value;
     173        this.category = value;
    183174    }
    184175
     
    190181     */
    191182    public void setGenerator(String value) {
    192         this.generator = value;
     183        this.generator = value;
    193184    }
    194185
     
    200191     */
    201192    public void setDocs(String value) {
    202         this.docs = value;
     193        this.docs = value;
    203194    }
    204195
     
    210201     */
    211202    public void setCloud(Cloud value) {
    212         this.cloud = value;
     203        this.cloud = value;
    213204    }
    214205
     
    220211     */
    221212    public void setTtl(BigInteger value) {
    222         this.ttl = value;
     213        this.ttl = value;
    223214    }
    224215
     
    230221     */
    231222    public void setImage(Image value) {
    232         this.image = value;
     223        this.image = value;
    233224    }
    234225
     
    240231     */
    241232    public void setRating(String value) {
    242         this.rating = value;
     233        this.rating = value;
    243234    }
    244235
     
    250241     */
    251242    public void setTextInput(TextInput value) {
    252         this.textInput = value;
     243        this.textInput = value;
    253244    }
    254245
     
    260251     */
    261252    public void setSkipHours(SkipHoursList value) {
    262         this.skipHours = value;
     253        this.skipHours = value;
    263254    }
    264255
     
    270261     */
    271262    public void setSkipDays(SkipDaysList value) {
    272         this.skipDays = value;
     263        this.skipDays = value;
    273264    }
    274265
     
    276267    protected abstract RssItem fromArgToRssItem(T obj) throws ParseException;
    277268
    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     */
    279275    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 items
     276        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     */
    320316    private List<RssItem> makeListOfRssItems(List<T> objs) throws ParseException {
    321         List<RssItem> listOfItems = new ArrayList<RssItem>();
     317        List<RssItem> listOfItems = new ArrayList<RssItem>();
    322318
    323319        for (T currentObj : objs) {
    324 
    325320            RssItem currentItem = fromArgToRssItem(currentObj);
    326             listOfItems.add(currentItem);
    327         }
    328 
    329         return listOfItems;
     321            listOfItems.add(currentItem);
     322        }
     323
     324        return listOfItems;
    330325    }
    331326
    332327    public Rss makeRss(List<T> objs) throws ParseException {
    333         return (makeRssChannel(makeListOfRssItems(objs)));
     328        return (makeRssChannel(makeListOfRssItems(objs)));
    334329    }
    335330
    336331    // Helping stuff
    337332    protected Guid makeGuid(String href) {
    338         Guid result = new Guid();
    339         // result.setIsPermaLink(null);
    340         result.setValue(href);
    341         return result;
     333        Guid result = new Guid();
     334        // result.setIsPermaLink(null);
     335        result.setValue(href);
     336        return result;
    342337    }
    343338
    344339    /// Helping stuff: for working with dates
    345340    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        }
    353346    }
    354347
    355348    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        }
    395386    }
    396387}
  • 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 | Templates
    3  * and open the template in the editor.
    4  */
    51package clarin.cmdi.componentregistry;
    62
    7 import clarin.cmdi.componentregistry.model.AbstractDescription;
    83import clarin.cmdi.componentregistry.model.Comment;
    94import clarin.cmdi.componentregistry.rss.RssItem;
     
    1611public class RssCreatorComments extends RssCreator<Comment> {
    1712
    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();
    2623
    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;
    5331    }
    54    
    55      protected String  makeCommentTitle(String commentId, String user){
    56          
    57         return("Comment "+commentId +"\n by "+user+" ");
    58            
    59        }
    60    
    6132}
  • 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 | Templates
    3  * and open the template in the editor.
    4  */
    51package clarin.cmdi.componentregistry;
    62
    73import clarin.cmdi.componentregistry.model.AbstractDescription;
    84import clarin.cmdi.componentregistry.rss.RssItem;
    9 import org.slf4j.Logger;
    10 import org.slf4j.LoggerFactory;
    115
    126/**
     
    148 * @author olhsha
    159 */
    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
     10public 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
    2119    protected RssItem fromArgToRssItem(T desc) {
    2220
    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();
    2429
    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;
    4937    }
    5038
    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);
    5842    }
    5943}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/AbstractDescription.java

    r2268 r2287  
    55import java.util.Comparator;
    66import java.util.Date;
    7 
    87import javax.xml.bind.annotation.XmlAccessType;
    98import javax.xml.bind.annotation.XmlAccessorType;
     
    1110import javax.xml.bind.annotation.XmlRootElement;
    1211import javax.xml.bind.annotation.XmlSeeAlso;
    13 
    1412import org.apache.commons.codec.digest.DigestUtils;
    1513import org.apache.commons.lang.time.DateFormatUtils;
     
    3432    private String groupName;
    3533    private int commentsCount;
    36     private final static Logger LOG = LoggerFactory.getLogger(AbstractDescription.class);
    3734
    3835    public void setId(String id) {
    39         this.id = id;
     36        this.id = id;
    4037    }
    4138
    4239    public String getId() {
    43         return id;
     40        return id;
    4441    }
    4542
    4643    public void setDescription(String description) {
    47         this.description = description;
     44        this.description = description;
    4845    }
    4946
    5047    public String getDescription() {
    51         return description;
     48        return description;
    5249    }
    5350
    5451    public void setName(String name) {
    55         this.name = name;
     52        this.name = name;
    5653    }
    5754
    5855    public String getName() {
    59         return name;
     56        return name;
    6057    }
    6158
    6259    public void setRegistrationDate(String registrationDate) {
    63         this.registrationDate = registrationDate;
     60        this.registrationDate = registrationDate;
    6461    }
    6562
    6663    public String getRegistrationDate() {
    67         return registrationDate;
     64        return registrationDate;
    6865    }
    6966
    7067    public void setCreatorName(String creatorName) {
    71         this.creatorName = creatorName;
     68        this.creatorName = creatorName;
    7269    }
    7370
    7471    public String getCreatorName() {
    75         return creatorName;
     72        return creatorName;
    7673    }
    7774
    7875    public void setUserId(String userId) {
    79         this.userId = userId;
     76        this.userId = userId;
    8077    }
    8178
     
    8582     */
    8683    public String getUserId() {
    87         return userId;
     84        return userId;
    8885    }
    8986
    9087    public void setDomainName(String domainName) {
    91         this.domainName = domainName;
     88        this.domainName = domainName;
    9289    }
    9390
    9491    public String getDomainName() {
    95         return domainName;
     92        return domainName;
    9693    }
    9794
    9895    public void setHref(String href) {
    99         this.href = href;
     96        this.href = href;
    10097    }
    10198
    10299    public String getHref() {
    103         return href;
     100        return href;
    104101    }
    105102
    106103    public void setGroupName(String groupName) {
    107         this.groupName = groupName;
     104        this.groupName = groupName;
    108105    }
    109106
    110107    public String getGroupName() {
    111         return groupName;
     108        return groupName;
    112109    }
    113110
     
    116113     */
    117114    public int getCommentsCount() {
    118         return commentsCount;
     115        return commentsCount;
    119116    }
    120117
     
    123120     */
    124121    public void setCommentsCount(int commentsCount) {
    125         this.commentsCount = commentsCount;
     122        this.commentsCount = commentsCount;
    126123    }
    127124
    128125    @Override
    129126    public String toString() {
    130         return "Name=" + getName() + ", id=" + getId() + ", creatorName=" + getCreatorName() + ", userId=" + getUserId();
     127        return "Name=" + getName() + ", id=" + getId() + ", creatorName=" + getCreatorName() + ", userId=" + getUserId();
    131128    }
    132129
    133130    public boolean isProfile() {
    134         return this instanceof ProfileDescription;
     131        return this instanceof ProfileDescription;
    135132    }
    136133
    137134    public String getType() {
    138         return isProfile() ? "profile" : "component";
     135        return isProfile() ? "profile" : "component";
    139136    }
    140137
    141138    public static String createNewDate() {
    142         return createNewDate(new Date().getTime());
     139        return createNewDate(new Date().getTime());
    143140    }
    144141
    145142    public static String createNewDate(long time) {
    146         return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
     143        return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    147144    }
    148145
     
    154151     */
    155152    public boolean isThisTheOwner(String userId) {
    156         String userHash = DigestUtils.md5Hex(userId);
    157         return userHash.equals(getUserId());
     153        String userHash = DigestUtils.md5Hex(userId);
     154        return userHash.equals(getUserId());
    158155    }
    159156
    160157    public static Date getDate(String registrationDate) throws ParseException {
    161         return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
    162     }
    163 
     158        return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
     159    }
     160   
    164161    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     */
    174174    public static final Comparator<? super AbstractDescription> COMPARE_ON_NAME = new Comparator<AbstractDescription>() {
    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         }
     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        }
    186186    };
     187    /**
     188     * Compares two descriptions by the their value as returned by {@link AbstractDescription#getRegistrationDate() () }
     189     */
    187190    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        }
    195199    };
    196200}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/Comment.java

    r2268 r2287  
    22
    33import clarin.cmdi.componentregistry.RssCreator;
    4 import java.text.DateFormat;
    54import java.text.ParseException;
    65import java.util.Comparator;
    76import java.util.Date;
    8 import javax.xml.bind.DatatypeConverter;
    97import javax.xml.bind.annotation.XmlAccessType;
    108import javax.xml.bind.annotation.XmlAccessorType;
     
    1311import org.apache.commons.lang.time.DateFormatUtils;
    1412import org.apache.commons.lang.time.DateUtils;
    15 import org.slf4j.Logger;
    16 import org.slf4j.LoggerFactory;
    1713
    1814/**
     
    3430    @XmlTransient // this prevents userId from being serialized to XML and thus exposed (which is useless and undesirable)
    3531    private String userId;
    36     private final static Logger LOG = LoggerFactory.getLogger(Comment.class);
    3732
    3833    public void setComment(String comment) {
    39         this.comments = comment;
     34        this.comments = comment;
    4035    }
    4136
    4237    public String getComment() {
    43         return comments;
     38        return comments;
    4439    }
    4540
    4641    public void setCommentDate(String commentDate) {
    47         this.commentDate = commentDate;
     42        this.commentDate = commentDate;
    4843    }
    4944
    5045    public String getCommentDate() {
    51         return commentDate;
     46        return commentDate;
    5247    }
    5348
    5449    public void setId(String commentId) {
    55         this.id = commentId;
     50        this.id = commentId;
    5651    }
    5752
    5853    public String getId() {
    59         return id;
     54        return id;
    6055    }
    6156
    6257    public String getComponentDescriptionId() {
    63         return componentDescriptionId;
     58        return componentDescriptionId;
    6459    }
    6560
    6661    public void setComponentDescriptionId(String ComponentDescriptionId) {
    67         this.componentDescriptionId = ComponentDescriptionId;
     62        this.componentDescriptionId = ComponentDescriptionId;
    6863    }
    6964
    7065    public void setProfileDescriptionId(String profileDescriptionId) {
    71         this.profileDescriptionId = profileDescriptionId;
     66        this.profileDescriptionId = profileDescriptionId;
    7267    }
    7368
    7469    public String getProfileDescriptionId() {
    75         return profileDescriptionId;
     70        return profileDescriptionId;
    7671    }
    7772
    7873    public void setUserId(String userId) {
    79         this.userId = userId;
     74        this.userId = userId;
    8075    }
    8176
    8277    public String getUserId() {
    83         return userId;
     78        return userId;
    8479    }
    8580
     
    8984     */
    9085    public String getUserName() {
    91         return userName;
     86        return userName;
    9287    }
    9388
     
    9691     */
    9792    public void setUserName(String userName) {
    98         this.userName = userName;
     93        this.userName = userName;
    9994    }
    10095
     
    10398     */
    10499    public boolean isCanDelete() {
    105         return canDelete;
     100        return canDelete;
    106101    }
    107102
     
    110105     */
    111106    public void setCanDelete(boolean canDelete) {
    112         this.canDelete = canDelete;
     107        this.canDelete = canDelete;
    113108    }
    114109
    115110    public static Date getDate(String registrationDate) throws ParseException {
    116         return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
     111        return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
    117112    }
    118113
     
    121116     */
    122117    public static String createNewDate() {
    123         return createNewDate(new Date().getTime());
     118        return createNewDate(new Date().getTime());
    124119    }
    125120
     
    129124     */
    130125    public static String createNewDate(long time) {
    131         return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
     126        return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    132127    }
    133128
    134129    public static Comment createANewComment() {
    135         Comment com = new Comment();
    136         com.setCommentDate(createNewDate());
    137         return com;
     130        Comment com = new Comment();
     131        com.setCommentDate(createNewDate());
     132        return com;
    138133    }
    139    
     134    /**
     135     * Compares two commments by their value as returned by {@link Comment#getCommentDate() }
     136     */
    140137    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) {
    145143
    146             return (RssCreator.compareDateStrings(o1.getCommentDate(), o2.getCommentDate()));
    147         }
     144            return (RssCreator.compareDateStrings(o1.getCommentDate(), o2.getCommentDate()));
     145        }
    148146    };
    149147}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/ComponentDescription.java

    r2221 r2287  
    11package clarin.cmdi.componentregistry.model;
    2 
    3 import java.io.Serializable;
    4 import java.util.Comparator;
    5 
    6 import javax.xml.bind.annotation.XmlRootElement;
    72
    83import clarin.cmdi.componentregistry.ComponentRegistry;
    94import clarin.cmdi.componentregistry.IdSequence;
     5import java.io.Serializable;
     6import java.util.Comparator;
     7import javax.xml.bind.annotation.XmlRootElement;
    108
    119@XmlRootElement(name = "componentDescription")
     
    1412    private static final long serialVersionUID = 1L;
    1513    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        }
    3029    };
    31    
    3230
    3331    public static ComponentDescription createNewDescription() {
    34         String id = ComponentRegistry.REGISTRY_ID + "c_" + IdSequence.get();
    35         ComponentDescription desc = new ComponentDescription();
    36         desc.setId(id);
    37         desc.setRegistrationDate(createNewDate());
    38         return desc;
     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;
    3937    }
    4038}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java

    r2286 r2287  
    66import clarin.cmdi.componentregistry.ComponentStatus;
    77import clarin.cmdi.componentregistry.DeleteFailedException;
    8 import clarin.cmdi.componentregistry.MDMarshaller;
    98import clarin.cmdi.componentregistry.Owner;
    109import clarin.cmdi.componentregistry.RssCreatorComments;
     
    2322import com.sun.jersey.multipart.FormDataParam;
    2423import com.sun.jersey.spi.inject.Inject;
    25 import java.io.ByteArrayOutputStream;
    26 import java.io.File;
    27 import java.io.FileOutputStream;
    2824import java.io.IOException;
    2925import java.io.InputStream;
     
    9793    @Deprecated
    9894    private static ComponentStatus getStatus(boolean userSpace) {
    99         if (userSpace) {
    100             return ComponentStatus.DEVELOPMENT;
    101         } else {
    102             return ComponentStatus.PUBLIC;
    103         }
     95        if (userSpace) {
     96            return ComponentStatus.DEVELOPMENT;
     97        } else {
     98            return ComponentStatus.PUBLIC;
     99        }
    104100    }
    105101
    106102    private ComponentRegistry getRegistry(ComponentStatus status) {
    107         Principal userPrincipal = security.getUserPrincipal();
    108         UserCredentials userCredentials = getUserCredentials(userPrincipal);
    109         return getRegistry(status, null, userCredentials);
     103        Principal userPrincipal = security.getUserPrincipal();
     104        UserCredentials userCredentials = getUserCredentials(userPrincipal);
     105        return getRegistry(status, null, userCredentials);
    110106    }
    111107
    112108    private ComponentRegistry getRegistry(ComponentStatus status, Owner owner, UserCredentials userCredentials) {
    113         try {
    114             return componentRegistryFactory.getComponentRegistry(status, owner, userCredentials);
    115         } catch (UserUnauthorizedException uuEx) {
    116             //TODO: Throw actual exception and catch nicely
    117             throw new RuntimeException("Cannot access requested registry", uuEx);
    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        }
    119115    }
    120116
     
    125121     */
    126122    private Principal checkAndGetUserPrincipal() throws UserUnauthorizedException {
    127         Principal principal = security.getUserPrincipal();
    128         if (principal == null) {
    129             throw new UserUnauthorizedException("no user principal found.");
    130         }
    131         return principal;
     123        Principal principal = security.getUserPrincipal();
     124        if (principal == null) {
     125            throw new UserUnauthorizedException("no user principal found.");
     126        }
     127        return principal;
    132128    }
    133129
    134130    private UserCredentials getUserCredentials(Principal userPrincipal) {
    135         UserCredentials userCredentials = null;
    136         if (userPrincipal != null) {
    137             userCredentials = new UserCredentials(userPrincipal);
    138         }
    139         return userCredentials;
     131        UserCredentials userCredentials = null;
     132        if (userPrincipal != null) {
     133            userCredentials = new UserCredentials(userPrincipal);
     134        }
     135        return userCredentials;
    140136    }
    141137
     
    144140    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    145141    public List<ComponentDescription> getRegisteredComponents(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    146         long start = System.currentTimeMillis();
    147         List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions();
    148         LOG.info("Releasing " + components.size() + " registered components into the world (" + (System.currentTimeMillis() - start)
    149                 + " millisecs)");
    150         return components;
     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;
    151147    }
    152148
     
    155151    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    156152    public List<ProfileDescription> getRegisteredProfiles(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    157             @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor) throws ComponentRegistryException {
    158         long start = System.currentTimeMillis();
    159         List<ProfileDescription> profiles;
    160         if (metadataEditor) {
    161             profiles = getRegistry(getStatus(userspace)).getProfileDescriptionsForMetadaEditor();
    162         } else {
    163             profiles = getRegistry(getStatus(userspace)).getProfileDescriptions();
    164         }
    165 
    166         LOG.info("Releasing " + profiles.size() + " registered profiles into the world (" + (System.currentTimeMillis() - start)
    167                 + " millisecs)");
    168         return profiles;
     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;
    169165    }
    170166
     
    173169    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    174170    public Response getRegisteredComponent(@PathParam("componentId") String componentId,
    175             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    176         LOG.info("Component with id: " + componentId + " is requested.");
    177         CMDComponentSpec mdComponent = getRegistry(getStatus(userspace)).getMDComponent(componentId);
    178         if (mdComponent == null) {
    179             return Response.status(Status.NOT_FOUND).build();
    180         } else {
    181             return Response.ok(mdComponent).build();
    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        }
    183179    }
    184180
     
    187183    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
    188184    public Response getRegisteredComponentRawType(@PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) {
    189         LOG.info("Component with id: " + componentId + " and rawType:" + rawType + " is requested.");
    190         StreamingOutput result = null;
    191         try {
    192             final ComponentRegistry registry = findRegistry(componentId, new ComponentClosure());
    193             if (registry == null) {
    194                 return Response.status(Status.NOT_FOUND).entity("Id: " + componentId + " is not registered, cannot create data.").build();
    195             }
    196             ComponentDescription desc = registry.getComponentDescription(componentId);
    197             checkAndThrowDescription(desc, componentId);
    198             String fileName = desc.getName() + "." + rawType;
    199             if ("xml".equalsIgnoreCase(rawType)) {
    200                 result = new StreamingOutput() {
    201                     @Override
    202                     public void write(OutputStream output) throws IOException, WebApplicationException {
    203                         try {
    204                             registry.getMDComponentAsXml(componentId, output);
    205                         } catch (ComponentRegistryException e) {
    206                             LOG.info("Could not retrieve component", e);
    207                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    208                         }
    209                     }
    210                 };
    211             } else if ("xsd".equalsIgnoreCase(rawType)) {
    212                 result = new StreamingOutput() {
    213                     @Override
    214                     public void write(OutputStream output) throws IOException, WebApplicationException {
    215                         try {
    216                             registry.getMDComponentAsXsd(componentId, output);
    217                         } catch (ComponentRegistryException e) {
    218                             LOG.info("Could not retrieve component", e);
    219                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    220                         }
    221 
    222                     }
    223                 };
    224             } else {
    225                 throw new WebApplicationException(Response.serverError().entity(
    226                         "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
    227             }
    228             return createDownloadResponse(result, fileName);
    229         } catch (ComponentRegistryException e) {
    230             LOG.info("Could not retrieve component", e);
    231             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    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        }
    233229    }
    234230
    235231    public ComponentRegistry findRegistry(String id, RegistryClosure<? extends AbstractDescription> clos) throws ComponentRegistryException {
    236         AbstractDescription desc = null;
    237         ComponentRegistry result = getRegistry(getStatus(false));
    238         desc = clos.getDescription(result, id);
    239         if (desc == null) {
    240             List<ComponentRegistry> userRegs = componentRegistryFactory.getAllUserRegistries();
    241             for (ComponentRegistry reg : userRegs) {
    242                 desc = clos.getDescription(reg, id);
    243                 if (desc != null) {
    244                     result = reg;
    245                     break;
    246                 }
    247             }
    248         }
    249         return result;
     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;
    250246    }
    251247
     
    254250    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    255251    public Response getRegisteredProfile(@PathParam("profileId") String profileId,
    256             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    257         LOG.info("Profile with id: " + profileId + " is requested.");
    258         CMDComponentSpec mdProfile = getRegistry(getStatus(userspace)).getMDProfile(profileId);
    259         if (mdProfile == null) {
    260             return Response.status(Status.NOT_FOUND).build();
    261         } else {
    262             return Response.ok(mdProfile).build();
    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        }
    264260    }
    265261
     
    268264    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    269265    public List<AbstractDescription> getComponentUsage(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("true") boolean userspace) throws ComponentRegistryException {
    270         try {
    271             final long start = System.currentTimeMillis();
    272             ComponentRegistry registry = getRegistry(getStatus(userspace));
    273             List<ComponentDescription> components = registry.getUsageInComponents(componentId);
    274             List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
    275 
    276             LOG.info("Found " + components.size() + " components and " + profiles.size() + " profiles that use component " + componentId
    277                     + " (" + (System.currentTimeMillis() - start) + " millisecs)");
    278 
    279             List<AbstractDescription> usages = new ArrayList<AbstractDescription>(components.size() + profiles.size());
    280             usages.addAll(components);
    281             usages.addAll(profiles);
    282 
    283             return usages;
    284         } catch (ComponentRegistryException e) {
    285             LOG.info("Could not retrieve profile usage", e);
    286             throw e;
    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        }
    288284    }
    289285
     
    292288    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    293289    public List<Comment> getCommentsFromProfile(@PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    294         long start = System.currentTimeMillis();
    295         final Principal principal = security.getUserPrincipal();
    296         List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal);
    297         LOG.info("Releasing " + comments.size() + " registered comments in Profile into the world (" + (System.currentTimeMillis() - start)
    298                 + " millisecs)");
    299         return comments;
     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;
    300296    }
    301297
     
    304300    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    305301    public List<Comment> getCommentsFromComponent(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    306         long start = System.currentTimeMillis();
    307         final Principal principal = security.getUserPrincipal();
    308         List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal);
    309         LOG.info("Releasing " + comments.size() + " registered comments in Component into the world (" + (System.currentTimeMillis() - start)
    310                 + " millisecs)");
    311         return comments;
     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;
    312308    }
    313309
     
    316312    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    317313    public Comment getSpecifiedCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    318         LOG.info(" Comments of component with id" + commentId + " are requested.");
    319         final Principal principal = security.getUserPrincipal();
    320         return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(profileId, commentId, principal);
     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);
    321317    }
    322318
     
    325321    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    326322    public Comment getSpecifiedCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    327         LOG.info(" Comments of component with id" + commentId + " are requested.");
    328         final Principal principal = security.getUserPrincipal();
    329         return getRegistry(getStatus(userspace)).getSpecifiedCommentInComponent(componentId, commentId, principal);
     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);
    330326    }
    331327
     
    342338    @Path("/profiles/{profileId}")
    343339    public Response manipulateRegisteredProfile(@PathParam("profileId") String profileId, @FormParam("method") String method,
    344             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    345         if ("delete".equalsIgnoreCase(method)) {
    346             return deleteRegisteredProfile(profileId, userspace);
    347         } else {
    348             return Response.ok().build();
    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        }
    350346    }
    351347
     
    353349    @Path("/profiles/{profileId}/comments/{commentId}")
    354350    public Response manipulateCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @FormParam("method") String method,
    355             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    356         if ("delete".equalsIgnoreCase(method)) {
    357             return deleteCommentFromProfile(profileId, commentId, userspace);
    358         } else {
    359             return Response.ok().build();
    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        }
    361357    }
    362358
     
    364360    @Path("/components/{componentId}/comments/{commentId}")
    365361    public Response manipulateCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @FormParam("method") String method,
    366             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    367         if ("delete".equalsIgnoreCase(method)) {
    368             return deleteCommentFromComponent(componentId, commentId, userspace);
    369         } else {
    370             return Response.ok().build();
    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        }
    372368    }
    373369
     
    376372    @Consumes("multipart/form-data")
    377373    public Response publishRegisteredProfile(@PathParam("profileId") String profileId, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    378             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    379             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    380         try {
    381             Principal principal = checkAndGetUserPrincipal();
    382             ProfileDescription desc = getRegistry(getStatus(true)).getProfileDescription(profileId);
    383             if (desc != null) {
    384                 updateDescription(desc, name, description, domainName, group);
    385                 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
    386             } else {
    387                 LOG.error("Update of nonexistent id (" + profileId + ") failed.");
    388                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    389             }
    390         } catch (ComponentRegistryException e) {
    391             LOG.info("Could not retrieve component", e);
    392             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    393         } catch (UserUnauthorizedException ex) {
    394             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    396392    }
    397393
     
    400396    @Consumes("multipart/form-data")
    401397    public Response updateRegisteredProfile(@PathParam("profileId") String profileId,
    402             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    403             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    404             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    405         try {
    406             Principal principal = checkAndGetUserPrincipal();
    407             UserCredentials userCredentials = getUserCredentials(principal);
    408             ProfileDescription desc = getRegistry(getStatus(userspace)).getProfileDescription(profileId);
    409             if (desc != null) {
    410                 updateDescription(desc, name, description, domainName, group);
    411                 return register(input, desc, userCredentials, userspace, new UpdateAction(principal));
    412             } else {
    413                 LOG.error("Update of nonexistent id (" + profileId + ") failed.");
    414                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    415             }
    416         } catch (ComponentRegistryException e) {
    417             LOG.info("Could not retrieve component", e);
    418             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    419         } catch (UserUnauthorizedException ex) {
    420             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    422418
    423419    }
     
    435431    @Path("/components/{componentId}")
    436432    public Response manipulateRegisteredComponent(@PathParam("componentId") String componentId, @FormParam("method") String method,
    437             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    438         if ("delete".equalsIgnoreCase(method)) {
    439             return deleteRegisteredComponent(componentId, userspace);
    440         } else {
    441             return Response.ok().build();
    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        }
    443439    }
    444440
     
    447443    @Consumes("multipart/form-data")
    448444    public Response publishRegisteredComponent(@PathParam("componentId") String componentId,
    449             @FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    450             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
    451             @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    452         try {
    453             Principal principal = checkAndGetUserPrincipal();
    454             // TODO: Get status from parameter
    455             ComponentDescription desc = getRegistry(getStatus(true)).getComponentDescription(componentId);
    456             if (desc != null) {
    457                 updateDescription(desc, name, description, domainName, group);
    458                 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
    459             } else {
    460                 LOG.error("Update of nonexistent id (" + componentId + ") failed.");
    461                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    462             }
    463         } catch (ComponentRegistryException e) {
    464             LOG.info("Could not retrieve component", e);
    465             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    466         } catch (UserUnauthorizedException ex) {
    467             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    469465    }
    470466
     
    473469    @Consumes("multipart/form-data")
    474470    public Response updateRegisteredComponent(@PathParam("componentId") String componentId,
    475             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    476             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    477             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    478         try {
    479             Principal principal = checkAndGetUserPrincipal();
    480             ComponentDescription desc = getRegistry(getStatus(userspace)).getComponentDescription(componentId);
    481             if (desc != null) {
    482                 updateDescription(desc, name, description, domainName, group);
    483                 return register(input, desc, getUserCredentials(principal), userspace, new UpdateAction(principal));
    484             } else {
    485                 LOG.error("Update of nonexistent id (" + componentId + ") failed.");
    486                 return Response.serverError().entity("Invalid id, cannot update nonexistent component").build();
    487             }
    488         } catch (ComponentRegistryException e) {
    489             LOG.info("Could not retrieve component", e);
    490             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    491         } catch (UserUnauthorizedException ex) {
    492             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    494490    }
    495491
    496492    private void updateDescription(AbstractDescription desc, String name, String description, String domainName, String group) {
    497         desc.setName(name);
    498         desc.setDescription(description);
    499         desc.setDomainName(domainName);
    500         desc.setGroupName(group);
    501         desc.setRegistrationDate(AbstractDescription.createNewDate());
     493        desc.setName(name);
     494        desc.setDescription(description);
     495        desc.setDomainName(domainName);
     496        desc.setGroupName(group);
     497        desc.setRegistrationDate(AbstractDescription.createNewDate());
    502498    }
    503499
     
    505501    @Path("/components/{componentId}")
    506502    public Response deleteRegisteredComponent(@PathParam("componentId") String componentId,
    507             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    508         try {
    509             Principal principal = checkAndGetUserPrincipal();
    510             ComponentRegistry registry = getRegistry(getStatus(userspace));
    511             LOG.info("Component with id: " + componentId + " set for deletion.");
    512             registry.deleteMDComponent(componentId, principal, false);
    513         } catch (DeleteFailedException e) {
    514             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    515             return Response.status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    516         } catch (ComponentRegistryException e) {
    517             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    518             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    519         } catch (IOException e) {
    520             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    521             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    522         } catch (UserUnauthorizedException e) {
    523             LOG.info("Component with id: " + componentId + " deletion failed: " + e.getMessage());
    524             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    525         }
    526         LOG.info("Component with id: " + componentId + " deleted.");
    527         return Response.ok().build();
     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();
    528524    }
    529525
     
    531527    @Path("/profiles/{profileId}")
    532528    public Response deleteRegisteredProfile(@PathParam("profileId") String profileId,
    533             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    534         try {
    535             Principal principal = checkAndGetUserPrincipal();
    536             LOG.info("Profile with id: " + profileId + " set for deletion.");
    537             getRegistry(getStatus(userspace)).deleteMDProfile(profileId, principal);
    538         } catch (DeleteFailedException e) {
    539             LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
    540             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    541         } catch (ComponentRegistryException e) {
    542             LOG.info("Could not retrieve component", e);
    543             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    544         } catch (IOException e) {
    545             LOG.info("Profile with id: " + profileId + " deletion failed.", e);
    546             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    547         } catch (UserUnauthorizedException e) {
    548             LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
    549             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    550         }
    551         LOG.info("Profile with id: " + profileId + " deleted.");
    552         return Response.ok().build();
     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();
    553549    }
    554550
     
    556552    @Path("/profiles/{profileId}/comments/{commentId}")
    557553    public Response deleteCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId,
    558             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    559         try {
    560             final Principal principal = checkAndGetUserPrincipal();
    561             final ComponentRegistry registry = getRegistry(getStatus(userspace));
    562             final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId, principal);
    563             if (comment != null && profileId.equals(comment.getProfileDescriptionId())) {
    564                 LOG.info("Comment with id: " + commentId + " set for deletion.");
    565                 registry.deleteComment(commentId, principal);
    566             } else {
    567                 throw new ComponentRegistryException("Comment not found for specified profile");
    568             }
    569         } catch (DeleteFailedException e) {
    570             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    571             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    572         } catch (ComponentRegistryException e) {
    573             LOG.info("Could not retrieve component", e);
    574             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    575         } catch (IOException e) {
    576             LOG.info("Comment with id: " + commentId + " deletion failed.", e);
    577             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    578         } catch (UserUnauthorizedException e) {
    579             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    580             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    581         }
    582         LOG.info("Comment with id: " + commentId + " deleted.");
    583         return Response.ok().build();
     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();
    584580    }
    585581
     
    587583    @Path("/components/{componentId}/comments/{commentId}")
    588584    public Response deleteCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId,
    589             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    590         try {
    591             final Principal principal = checkAndGetUserPrincipal();
    592             final ComponentRegistry registry = getRegistry(getStatus(userspace));
    593             final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId, principal);
    594             if (comment != null && componentId.equals(comment.getComponentDescriptionId())) {
    595                 LOG.info("Comment with id: " + commentId + " set for deletion.");
    596                 registry.deleteComment(commentId, principal);
    597             } else {
    598                 throw new ComponentRegistryException("Comment not found for specified component");
    599             }
    600         } catch (DeleteFailedException e) {
    601             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    602             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    603         } catch (ComponentRegistryException e) {
    604             LOG.info("Could not retrieve component", e);
    605             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    606         } catch (IOException e) {
    607             LOG.info("Comment with id: " + commentId + " deletion failed.", e);
    608             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    609         } catch (UserUnauthorizedException e) {
    610             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    611             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    612         }
    613         LOG.info("Comment with id: " + commentId + " deleted.");
    614         return Response.ok().build();
     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();
    615611    }
    616612
     
    619615    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
    620616    public Response getRegisteredProfileRawType(@PathParam("profileId") final String profileId, @PathParam("rawType") String rawType) {
    621         LOG.info("Profile with id: " + profileId + " and rawType:" + rawType + " is requested.");
    622         StreamingOutput result = null;
    623         try {
    624             final ComponentRegistry registry = findRegistry(profileId, new ProfileClosure());
    625             if (registry == null) {
    626                 return Response.status(Status.NOT_FOUND).entity("Id: " + profileId + " is not registered, cannot create data.").build();
    627             }
    628             ProfileDescription desc = registry.getProfileDescription(profileId);
    629             checkAndThrowDescription(desc, profileId);
    630             String fileName = desc.getName() + "." + rawType;
    631 
    632             if ("xml".equalsIgnoreCase(rawType)) {
    633                 result = new StreamingOutput() {
    634                     @Override
    635                     public void write(OutputStream output) throws IOException, WebApplicationException {
    636                         try {
    637                             registry.getMDProfileAsXml(profileId, output);
    638                         } catch (ComponentRegistryException e) {
    639                             LOG.warn("Could not retrieve component", e);
    640                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    641                         }
    642                     }
    643                 };
    644             } else if ("xsd".equalsIgnoreCase(rawType)) {
    645                 result = new StreamingOutput() {
    646                     @Override
    647                     public void write(OutputStream output) throws IOException, WebApplicationException {
    648                         try {
    649                             registry.getMDProfileAsXsd(profileId, output);
    650                         } catch (ComponentRegistryException e) {
    651                             LOG.warn("Could not retrieve component", e);
    652                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    653                         }
    654                     }
    655                 };
    656             } else {
    657                 throw new WebApplicationException(Response.serverError().entity(
    658                         "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
    659             }
    660             return createDownloadResponse(result, fileName);
    661         } catch (ComponentRegistryException e) {
    662             LOG.info("Could not retrieve component", e);
    663             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    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        }
    665661    }
    666662
    667663    private void checkAndThrowDescription(AbstractDescription desc, String id) {
    668         if (desc == null) {
    669             throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build());
    670         }
     664        if (desc == null) {
     665            throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build());
     666        }
    671667    }
    672668
    673669    private Response createDownloadResponse(StreamingOutput result, String fileName) {
    674         //Making response so it triggers browsers native save as dialog.
    675         Response response = Response.ok().type("application/x-download").header("Content-Disposition",
    676                 "attachment; filename=\"" + fileName + "\"").entity(result).build();
    677         return response;
     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;
    678674
    679675    }
     
    684680    @Consumes("multipart/form-data")
    685681    public Response registerProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    686             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
    687             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    688         try {
    689             Principal principal = checkAndGetUserPrincipal();
    690             UserCredentials userCredentials = getUserCredentials(principal);
    691             ProfileDescription desc = createNewProfileDescription();
    692             desc.setCreatorName(userCredentials.getDisplayName());
    693             desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
    694             desc.setName(name);
    695             desc.setDescription(description);
    696             desc.setGroupName(group);
    697             desc.setDomainName(domainName);
    698             LOG.info("Trying to register Profile: " + desc);
    699             return register(input, desc, userCredentials, userspace, new NewAction());
    700         } catch (UserUnauthorizedException ex) {
    701             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    703699    }
    704700
     
    708704    @Consumes("multipart/form-data")
    709705    public Response registerComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    710             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
    711             @FormDataParam(DOMAIN_FORM_FIELD) String domainName, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    712         try {
    713             Principal principal = checkAndGetUserPrincipal();
    714             UserCredentials userCredentials = getUserCredentials(principal);
    715             ComponentDescription desc = createNewComponentDescription();
    716             desc.setCreatorName(userCredentials.getDisplayName());
    717             desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
    718             desc.setName(name);
    719             desc.setDescription(description);
    720             desc.setGroupName(group);
    721             desc.setDomainName(domainName);
    722             LOG.info("Trying to register Component: " + desc);
    723             return register(input, desc, userCredentials, userspace, new NewAction());
    724         } catch (UserUnauthorizedException ex) {
    725             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    727723    }
    728724
     
    732728    @Consumes("multipart/form-data")
    733729    public Response registerCommentInComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input,
    734             @PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    735         try {
    736             Principal principal = checkAndGetUserPrincipal();
    737             UserCredentials userCredentials = getUserCredentials(principal);
    738             if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
    739                 throw new UserUnauthorizedException("Cannot materialize authenticated user");
    740             }
    741             // TODO: Add user/group param
    742             ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
    743             ComponentDescription description = registry.getComponentDescription(componentId);
    744             if (description != null) {
    745                 LOG.info("Trying to register comment to " + componentId);
    746                 return registerComment(input, registry, userspace, description, principal, userCredentials);
    747             } else {
    748                 LOG.error("Attempt to post comment on nonexistent component id (" + componentId + ") failed.");
    749                 return Response.serverError().entity("Invalid id, cannot comment on nonexistent component").build();
    750             }
    751         } catch (UserUnauthorizedException ex) {
    752             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    754750    }
    755751
     
    759755    @Consumes("multipart/form-data")
    760756    public Response registerCommentInProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input,
    761             @PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    762         try {
    763             Principal principal = checkAndGetUserPrincipal();
    764             UserCredentials userCredentials = getUserCredentials(principal);
    765             if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
    766                 throw new UserUnauthorizedException("Cannot materialize authenticated user");
    767             }
    768             // TODO: Add user/group param
    769             ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
    770             ProfileDescription description = registry.getProfileDescription(profileId);
    771             if (description != null) {
    772                 LOG.info("Trying to register comment to " + profileId);
    773                 return registerComment(input, registry, userspace, description, principal, userCredentials);
    774             } else {
    775                 LOG.error("Attempt to post comment on nonexistent profile id (" + profileId + ") failed.");
    776                 return Response.serverError().entity("Invalid id, cannot comment on nonexistent profile").build();
    777             }
    778         } catch (UserUnauthorizedException ex) {
    779             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    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        }
    781777    }
    782778
     
    785781    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    786782    public Response pingSession() {
    787         boolean stillActive = false;
    788         Principal userPrincipal = security.getUserPrincipal();
    789         LOG.info("ping by user: " + (userPrincipal == null ? "null" : userPrincipal.getName()));
    790         if (request != null) {
    791             if (userPrincipal != null && !ComponentRegistryFactory.ANONYMOUS_USER.equals(userPrincipal.getName())) {
    792                 stillActive = !((HttpServletRequest) request).getSession().isNew();
    793             }
    794         }
    795         return Response.ok().entity("<session stillActive=\"" + stillActive + "\"/>").build();
     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();
    796792    }
    797793
    798794    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        }
    854842    }
    855843
    856844    private Response registerComment(InputStream input, ComponentRegistry registry, boolean userspace,
    857             AbstractDescription description, Principal principal, UserCredentials userCredentials) {
    858         try {
    859             CommentValidator validator = new CommentValidator(input, description);
    860             CommentResponse response = new CommentResponse();
    861             response.setIsInUserSpace(userspace);
    862             validateComment(response, validator);
    863             if (response.getErrors().isEmpty()) {
    864                 Comment com = validator.getCommentSpec();
    865                 //int returnCode = action.executeComment(com, response, registry, principal.getName());
    866 
    867                 // If user name is left empty, fill it using the user's display name
    868                 if (null == com.getUserName() || "".equals(com.getUserName())) {
    869                     if (userCredentials != null) {
    870                         com.setUserName(userCredentials.getDisplayName());
    871                     } else {
    872                         com.setUserName(principal.getName());
    873                     }
    874                 }
    875 
    876                 int returnCode = registry.registerComment(com, principal.getName());
    877                 if (returnCode == 0) {
    878                     response.setRegistered(true);
    879                     response.setComment(com);
    880                 } else {
    881                     response.setRegistered(false);
    882                     response.addError("Unable to register at this moment. Internal server error.");
    883                 }
    884             } else {
    885                 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
    886                 response.setRegistered(false);
    887             }
    888             return Response.ok(response).build();
    889         } catch (ComponentRegistryException ex) {
    890             LOG.error("Error while inserting comment: ", ex);
    891             return Response.serverError().entity(ex.getMessage()).build();
    892         } finally {
    893             try {
    894                 input.close();//either we read the input or there was an exception, we need to close it.
    895             } catch (IOException e) {
    896                 LOG.error("Error when closing inputstream: ", e);
    897                 return Response.serverError().build();
    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        }
    900888    }
    901889
    902890    private ComponentDescription createNewComponentDescription() {
    903         ComponentDescription desc = ComponentDescription.createNewDescription();
    904         desc.setHref(createXlink(desc.getId()));
    905         return desc;
     891        ComponentDescription desc = ComponentDescription.createNewDescription();
     892        desc.setHref(createXlink(desc.getId()));
     893        return desc;
    906894    }
    907895
    908896    private ProfileDescription createNewProfileDescription() {
    909         ProfileDescription desc = ProfileDescription.createNewDescription();
    910         desc.setHref(createXlink(desc.getId()));
    911         return desc;
     897        ProfileDescription desc = ProfileDescription.createNewDescription();
     898        desc.setHref(createXlink(desc.getId()));
     899        return desc;
    912900    }
    913901
    914902    private String createXlink(String id) {
    915         URI uri = uriInfo.getRequestUriBuilder().path(id).build();
    916         return uri.toString();
     903        URI uri = uriInfo.getRequestUriBuilder().path(id).build();
     904        return uri.toString();
    917905    }
    918906
     
    928916     */
    929917    private String getApplicationBaseURI() {
    930         return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
     918        return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
    931919    }
    932920
    933921    private void validate(RegisterResponse response, Validator... validators) {
    934         for (Validator validator : validators) {
    935             if (!validator.validate()) {
    936                 for (String error : validator.getErrorMessages()) {
    937                     response.addError(error);
    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        }
    941929    }
    942930
    943931    private void validateComment(CommentResponse response, Validator... validators) {
    944         for (Validator validator : validators) {
    945             if (!validator.validate()) {
    946                 for (String error : validator.getErrorMessages()) {
    947                     response.addError(error);
    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        }
    951939    }
    952940
     
    955943     */
    956944    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
    961948    /*
     949     * Two muchually recursive methods below are used to set filenames of components (and their child components) to null
    962950     * @param List<CMDComponentType> listofcomponents the list of components whose filenames (and the children's names) are to be set to null
    963951     */
    964952    public void setFileNamesFromListToNull(List<CMDComponentType> listofcomponents) {
    965953
    966         for (CMDComponentType currentcomponent : listofcomponents) {
    967             setFileNamesToNullCurrent(currentcomponent);
    968         }
     954        for (CMDComponentType currentcomponent : listofcomponents) {
     955            setFileNamesToNullCurrent(currentcomponent);
     956        }
    969957
    970958    }
     
    974962     */
    975963    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
    985980     */
    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    }
    10141008
    10151009    @GET
     
    10171011    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    10181012    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
    10371022    @GET
    10381023    @Path("/profiles/rss")
    10391024    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    10401025    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
    10631049     */
    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
    10911074    @GET
    10921075    @Path("/profiles/{profileId}/comments/rss")
    10931076    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    10941077    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
    11131089    @GET
    11141090    @Path("/components/{componentId}/comments/rss")
    11151091    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    11161092    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    }
    11351103}
  • 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 | Templates
    3  * and open the template in the editor.
    4  */
    51package clarin.cmdi.componentregistry;
    62
    73import clarin.cmdi.componentregistry.model.Comment;
    8 import clarin.cmdi.componentregistry.model.ProfileDescription;
    94import clarin.cmdi.componentregistry.rss.Rss;
    105import clarin.cmdi.componentregistry.rss.RssItem;
     
    149import java.util.List;
    1510import org.junit.Test;
     11
    1612import static org.junit.Assert.*;
     13
    1714/**
    1815 *
     
    2017 */
    2118public 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;
    4236    }
    43    
     37
    4438    /**
    45      * 
     39     *
    4640     */
    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
    5748    }
    58            
    59            
    60    
     49
    6150    @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));
    12384    }
    124    
    125     /*@Test
    126     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    
    14585}
  • 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 | Templates
    3  * and open the template in the editor.
    4  */
    51package clarin.cmdi.componentregistry;
    62
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/CMDComponentSetFilenamesToNullTestHelper.java

    r2284 r2287  
    1313import java.util.List;
    1414import javax.xml.bind.JAXBException;
    15 import org.junit.Test;
     15
    1616import static org.junit.Assert.*;
    1717
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java

    r2223 r2287  
    22
    33import clarin.cmdi.componentregistry.ComponentRegistry;
    4 import clarin.cmdi.componentregistry.ComponentRegistryException;
    54import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    65import clarin.cmdi.componentregistry.ComponentStatus;
     
    2019import com.sun.jersey.multipart.FormDataMultiPart;
    2120import java.io.ByteArrayInputStream;
     21import java.util.ArrayList;
    2222import java.util.Date;
    2323import java.util.List;
     
    3434
    3535import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
    36 import java.util.ArrayList;
    3736import static org.junit.Assert.*;
    3837
     
    11431142        assertEquals(MDValidator.MISMATCH_ERROR, response.getErrors().get(0));
    11441143    }
    1145    
    1146    
    1147    
     1144
    11481145    /**
    11491146     * creates a tree-like component, whose root has two kids, and the kids have three their own kids each
    11501147     * the corresponding filenames are:
    11511148     * "wortel", "nodel-L", "node-R", "leaf-LL", "leaf-LM", "leaf-LR", "leaf-RL", "leaf-RM", "leaf-RR"
    1152      * @throws Exception
     1149     *
     1150     * @throws Exception
    11531151     */
    1154     @Test 
     1152    @Test
    11551153    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    }
    12381235}
  • 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 | Templates
    3  * and open the template in the editor.
    4  */
    51package clarin.cmdi.componentregistry.rest;
    62
     
    3026 */
    3127public class xmlRssGeneratingRunner {
    32      
    33    
    34    
    35  ////////////////   
    36    
    37  public void  printIds(List<AbstractDescription> desc){
    3828
    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        }
    5334    }
    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;
    6235
    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    }
    143131}
Note: See TracChangeset for help on using the changeset viewer.