Changeset 2268


Ignore:
Timestamp:
09/28/12 16:32:49 (12 years ago)
Author:
olhsha
Message:

data conversion is fixed. Safari still magnify the items

Location:
ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreator.java

    r2259 r2268  
    11package clarin.cmdi.componentregistry;
    22
     3import clarin.cmdi.componentregistry.model.AbstractDescription;
    34import clarin.cmdi.componentregistry.rss.Category;
    45import clarin.cmdi.componentregistry.rss.Cloud;
     
    1617import java.text.SimpleDateFormat;
    1718import java.util.ArrayList;
     19import java.util.Comparator;
    1820import java.util.Date;
    1921import java.util.List;
     
    2628public abstract class RssCreator<T> { // extends nothing so far, throuw nothing // make it abstract
    2729
    28    
    29     protected String uriForGuid; // MUST
    30    
    31      // all the fields below are not mandatory, no crashes will happen if they are not set
     30   
    3231    private String title;
    3332    private String link;
     
    5049    private SkipDaysList skipDays;
    5150    private double version = 2.0; // of an rss
    52    
    53     ////////////////////
    54    
    55     public RssCreator(String uri){
    56         this.uriForGuid = uri;
    57     }
    58    
     51
    5952   
    6053
     
    8174    }
    8275
    83     public String getTitle(){
     76    public String getTitle() {
    8477        return this.title;
    8578    }
    86    
     79
    8780    /**
    8881     * Sets the value of the link property.
     
    9588    }
    9689
    97     public String getLink(){
     90    public String getLink() {
    9891        return this.link;
    9992    }
    100      
     93
    10194    /**
    10295     * Sets the value of the description property.
     
    329322        return (makeRssChannel(makeListOfRssItems(objs)));
    330323    }
    331    
    332 
    333     protected String getRFCDateTime(String datestring) throws ParseException {
    334 
    335         Date date = DatatypeConverter.parseDateTime(datestring).getTime();
    336         SimpleDateFormat RFC822DATEFORMAT = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z");
    337         return RFC822DATEFORMAT.format(date);
    338     }
    339 
    340    
    341    protected Guid makeGuid(String href){
     324
     325    // Helping stuff
     326    protected Guid makeGuid(String href) {
    342327        Guid result = new Guid();
    343328        // result.setIsPermaLink(null);
     
    345330        return result;
    346331    }
     332
     333    /// Helping stuff: for working with dates
     334    private static Date parseWorks(String dateString) {
     335        Date d = null;
     336        try {
     337            d = AbstractDescription.getDate(dateString);
     338        } catch (ParseException pe) {
     339            return null;
     340        };
     341        return d;
     342    }
     343
     344    protected String getRFCDateTime(String dateString) {
     345
     346        Date date = parseWorks(dateString);
     347
     348        if (date == null) {
     349            return dateString;
     350        } else {
     351            SimpleDateFormat RFC822DATEFORMAT = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z");
     352            return RFC822DATEFORMAT.format(date);
     353        }
     354    }
     355
    347356   
     357    ///////
     358    // returns 1 if ds1 is older (before) than ds2, returns -1 if ds1 is younger (after) than ds2
     359    public static int compareDateStrings(String ds1, String ds2) {
     360
     361        int result = 0;
     362
     363        Date d1 = parseWorks(ds1);
     364        Date d2 = parseWorks(ds2);
     365
     366        if (d1 == null) {
     367            if (d2 == null) {
     368                result = 0;
     369            } else {
     370                result = 1;
     371            }
     372        } else {
     373            if (d2 == null) {
     374                result = -1;
     375            } else {
     376                // cpmparteTo reurns:
     377                // a value less than 0 if d2 is before d1 (d1 is younger than d2);
     378                // a value greater than 0 if d2 is after  d1 (d1 is older than d2)
     379                result = d2.compareTo(d1);
     380            }
     381
     382        }
     383        return result;
     384    }
    348385}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreatorComments.java

    r2256 r2268  
    1616public class RssCreatorComments extends RssCreator<Comment> {
    1717
    18    
    19     private boolean isFromProfile;
    20    
    21     public RssCreatorComments(String uri){
    22         super(uri);
    23     }
    24    
     18   
    2519    // creator method, comment to rssItem, ovverrides the dummy method of the RssCreator class
    2620    // ?? is there a better way than boolean flag to arrange switch beween comment for profiles and commentss for components
    2721   
    28     public void setFlagIsFromProfile(boolean isFromProfile) {
    29         this.isFromProfile = isFromProfile;
    30     }
     22   
    3123   
    3224    @Override 
     
    3527         
    3628        RssItem retval = new RssItem();
    37         String hrefPostfix = "&view=comments&commentId=";
    38         String hrefInfix = "?item=";
    3929       
    40         String descId;
    41         if (isFromProfile) {descId=comm.getProfileDescriptionId();}
    42         else{descId=comm.getComponentDescriptionId();};
    43        
    44        
    45         String link = uriForGuid+hrefInfix+descId+hrefPostfix+comm.getId();
    4630       
    4731                //The content
     
    5034       
    5135        //Guid
    52         retval.setGuid(makeGuid(link));
     36        //retval.setGuid(makeGuid(link));
    5337       
    5438        // link
    55         retval.setLink(link);
     39        retval.setLink(super.getLink()+"&commentId="+comm.getId()+"#");
    5640       
    5741       
     
    7155     protected String  makeCommentTitle(String commentId, String user){
    7256         
    73         return("The comment "+commentId +" by "+user);
     57        return("The comment "+commentId +" by "+user+" ");
    7458           
    7559       }
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/RssCreatorDescriptions.java

    r2256 r2268  
    1414public class RssCreatorDescriptions<T extends AbstractDescription>  extends RssCreator<T> {
    1515   
    16     public RssCreatorDescriptions(String uri){
    17         super(uri);
    18     }
    19    
     16 
    2017    // creator method, desc to rssItem, ovverrides the dummy method of the RssCreatorClass
    2118    @Override
     
    2522
    2623        RssItem retval = new RssItem();
    27         String hrefInfix = "?item=";
    28         String link =  uriForGuid+hrefInfix+desc.getId();
    29          
     24       
    3025        //Description (blah-blah)
    3126        retval.setDescription(desc.getDescription());
     
    3429       
    3530        //Guid
    36         retval.setGuid(makeGuid(link));
     31        //retval.setGuid(makeGuid(link));
    3732       
    3833        // link
    39         retval.setLink(link);
     34        retval.setLink(super.getLink()+"?item="+desc.getId()+"#");
    4035       
    4136        //time-date
     
    5146
    5247    protected String makeDescriptionTitle(String name, String creatorname, String group, String domain){
    53         String retval =  name+"by user"+creatorname+", group "+group+",domain "+domain;
     48        String retval =  name+"by user "+creatorname+", group "+group+",domain "+domain;
    5449       
    5550        return retval;
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/AbstractDescription.java

    r2259 r2268  
    11package clarin.cmdi.componentregistry.model;
    22
    3 import java.text.DateFormat;
     3import clarin.cmdi.componentregistry.RssCreator;
    44import java.text.ParseException;
    55import java.util.Comparator;
    66import java.util.Date;
    7 import javax.xml.bind.DatatypeConverter;
    87
    98import javax.xml.bind.annotation.XmlAccessType;
     
    1615import org.apache.commons.lang.time.DateFormatUtils;
    1716import org.apache.commons.lang.time.DateUtils;
     17import org.slf4j.Logger;
     18import org.slf4j.LoggerFactory;
    1819
    1920@XmlRootElement(name = "description")
     
    3334    private String groupName;
    3435    private int commentsCount;
     36    private final static Logger LOG = LoggerFactory.getLogger(AbstractDescription.class);
    3537
    3638    public void setId(String id) {
    37         this.id = id;
     39        this.id = id;
    3840    }
    3941
    4042    public String getId() {
    41         return id;
     43        return id;
    4244    }
    4345
    4446    public void setDescription(String description) {
    45         this.description = description;
     47        this.description = description;
    4648    }
    4749
    4850    public String getDescription() {
    49         return description;
     51        return description;
    5052    }
    5153
    5254    public void setName(String name) {
    53         this.name = name;
     55        this.name = name;
    5456    }
    5557
    5658    public String getName() {
    57         return name;
     59        return name;
    5860    }
    5961
    6062    public void setRegistrationDate(String registrationDate) {
    61         this.registrationDate = registrationDate;
     63        this.registrationDate = registrationDate;
    6264    }
    6365
    6466    public String getRegistrationDate() {
    65         return registrationDate;
     67        return registrationDate;
    6668    }
    6769
    6870    public void setCreatorName(String creatorName) {
    69         this.creatorName = creatorName;
     71        this.creatorName = creatorName;
    7072    }
    7173
    7274    public String getCreatorName() {
    73         return creatorName;
     75        return creatorName;
    7476    }
    7577
    7678    public void setUserId(String userId) {
    77         this.userId = userId;
     79        this.userId = userId;
    7880    }
    7981
    8082    /**
    81      * MD5 string representation of the user id. Storing the hash because the userId can be the email address which we don't want to make
    82      * public.
     83     * MD5 string representation of the user id. Storing the hash because the
     84     * userId can be the email address which we don't want to make public.
    8385     */
    8486    public String getUserId() {
    85         return userId;
     87        return userId;
    8688    }
    8789
    8890    public void setDomainName(String domainName) {
    89         this.domainName = domainName;
     91        this.domainName = domainName;
    9092    }
    9193
    9294    public String getDomainName() {
    93         return domainName;
     95        return domainName;
    9496    }
    9597
    9698    public void setHref(String href) {
    97         this.href = href;
     99        this.href = href;
    98100    }
    99101
    100102    public String getHref() {
    101         return href;
     103        return href;
    102104    }
    103105
    104106    public void setGroupName(String groupName) {
    105         this.groupName = groupName;
     107        this.groupName = groupName;
    106108    }
    107109
    108110    public String getGroupName() {
    109         return groupName;
     111        return groupName;
    110112    }
    111113
     
    114116     */
    115117    public int getCommentsCount() {
    116         return commentsCount;
     118        return commentsCount;
    117119    }
    118120
     
    121123     */
    122124    public void setCommentsCount(int commentsCount) {
    123         this.commentsCount = commentsCount;
     125        this.commentsCount = commentsCount;
    124126    }
    125127
    126128    @Override
    127129    public String toString() {
    128         return "Name=" + getName() + ", id=" + getId() + ", creatorName=" + getCreatorName() + ", userId=" + getUserId();
     130        return "Name=" + getName() + ", id=" + getId() + ", creatorName=" + getCreatorName() + ", userId=" + getUserId();
    129131    }
    130132
    131133    public boolean isProfile() {
    132         return this instanceof ProfileDescription;
     134        return this instanceof ProfileDescription;
    133135    }
    134136
    135137    public String getType() {
    136         return isProfile() ? "profile" : "component";
     138        return isProfile() ? "profile" : "component";
    137139    }
    138140
    139141    public static String createNewDate() {
    140         return createNewDate(new Date().getTime());
     142        return createNewDate(new Date().getTime());
    141143    }
    142144
    143145    public static String createNewDate(long time) {
    144         return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
     146        return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    145147    }
    146148
    147149    /**
    148150     * Helper method.
    149      * @param userId normal string which will be checked to see if it matches the md5 hash of the stored userId
     151     *
     152     * @param userId normal string which will be checked to see if it matches
     153     * the md5 hash of the stored userId
    150154     */
    151155    public boolean isThisTheOwner(String userId) {
    152         String userHash = DigestUtils.md5Hex(userId);
    153         return userHash.equals(getUserId());
     156        String userHash = DigestUtils.md5Hex(userId);
     157        return userHash.equals(getUserId());
    154158    }
    155159
    156160    public static Date getDate(String registrationDate) throws ParseException {
    157         return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
     161        return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
    158162    }
    159163
    160164    public static String createPublicHref(String href) {
    161         String result = href;
    162         if (href != null) {
    163             int index = href.indexOf("?");
    164             if (index != -1) { //strip off query params the rest should be the public href.
    165                 result = href.substring(0, index);
    166             }
    167         }
    168         return result;
     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;
    169173    }
    170    
    171174    public static final Comparator<? super AbstractDescription> COMPARE_ON_NAME = new Comparator<AbstractDescription>() {
    172 
    173         public int compare(AbstractDescription o1, AbstractDescription o2) {
    174             int result = 0;
    175             if (o1.getName() != null && o2.getName() != null) {
    176                 result = o1.getName().compareToIgnoreCase(o2.getName());
    177             }
    178             if (o1.getId() != null && result == 0) {
    179                 result = o1.getId().compareTo(o2.getId());
    180             }
    181             return result;
    182         }
    183     };
    184    
    185     public static final Comparator<? super AbstractDescription> COMPARE_ON_DATE = new Comparator<AbstractDescription>() {
    186        
    187         //compare two components by the date of registration
    188         // the dates, which are strings accrording to  ISO 8601, compared lexicographically
    189     @Override   
     175        @Override
    190176        public int compare(AbstractDescription o1, AbstractDescription o2) {
    191            
    192177            int result = 0;
    193            
    194             Date d1 = DatatypeConverter.parseDateTime(o1.getRegistrationDate()).getTime();
    195             Date d2 = DatatypeConverter.parseDateTime(o2.getRegistrationDate()).getTime();
    196            
    197             result = d2.compareTo(d1);
    198            
     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            }
    199184            return result;
    200185        }
    201186    };
    202    
     187    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        }
     195    };
    203196}
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/model/Comment.java

    r2259 r2268  
    11package clarin.cmdi.componentregistry.model;
    22
     3import clarin.cmdi.componentregistry.RssCreator;
    34import java.text.DateFormat;
    45import java.text.ParseException;
     
    1213import org.apache.commons.lang.time.DateFormatUtils;
    1314import org.apache.commons.lang.time.DateUtils;
     15import org.slf4j.Logger;
     16import org.slf4j.LoggerFactory;
    1417
    1518/**
     
    3134    @XmlTransient // this prevents userId from being serialized to XML and thus exposed (which is useless and undesirable)
    3235    private String userId;
     36    private final static Logger LOG = LoggerFactory.getLogger(Comment.class);
    3337
    3438    public void setComment(String comment) {
    35         this.comments = comment;
     39        this.comments = comment;
    3640    }
    3741
    3842    public String getComment() {
    39         return comments;
     43        return comments;
    4044    }
    4145
    4246    public void setCommentDate(String commentDate) {
    43         this.commentDate = commentDate;
     47        this.commentDate = commentDate;
    4448    }
    4549
    4650    public String getCommentDate() {
    47         return commentDate;
     51        return commentDate;
    4852    }
    4953
    5054    public void setId(String commentId) {
    51         this.id = commentId;
     55        this.id = commentId;
    5256    }
    5357
    5458    public String getId() {
    55         return id;
     59        return id;
    5660    }
    5761
    5862    public String getComponentDescriptionId() {
    59         return componentDescriptionId;
     63        return componentDescriptionId;
    6064    }
    6165
    6266    public void setComponentDescriptionId(String ComponentDescriptionId) {
    63         this.componentDescriptionId = ComponentDescriptionId;
     67        this.componentDescriptionId = ComponentDescriptionId;
    6468    }
    6569
    6670    public void setProfileDescriptionId(String profileDescriptionId) {
    67         this.profileDescriptionId = profileDescriptionId;
     71        this.profileDescriptionId = profileDescriptionId;
    6872    }
    6973
    7074    public String getProfileDescriptionId() {
    71         return profileDescriptionId;
     75        return profileDescriptionId;
    7276    }
    7377
    7478    public void setUserId(String userId) {
    75         this.userId = userId;
     79        this.userId = userId;
    7680    }
    7781
    7882    public String getUserId() {
    79         return userId;
     83        return userId;
    8084    }
    8185
     
    8589     */
    8690    public String getUserName() {
    87         return userName;
     91        return userName;
    8892    }
    8993
     
    9296     */
    9397    public void setUserName(String userName) {
    94         this.userName = userName;
     98        this.userName = userName;
    9599    }
    96100
     
    99103     */
    100104    public boolean isCanDelete() {
    101         return canDelete;
     105        return canDelete;
    102106    }
    103107
     
    106110     */
    107111    public void setCanDelete(boolean canDelete) {
    108         this.canDelete = canDelete;
     112        this.canDelete = canDelete;
    109113    }
    110114
    111115    public static Date getDate(String registrationDate) throws ParseException {
    112         return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
     116        return DateUtils.parseDate(registrationDate, new String[]{DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()});
    113117    }
    114118
    115    
    116    
    117119    /*
    118120     * Helper method to set the Date
    119121     */
    120122    public static String createNewDate() {
    121         return createNewDate(new Date().getTime());
     123        return createNewDate(new Date().getTime());
    122124    }
    123125
     
    127129     */
    128130    public static String createNewDate(long time) {
    129         return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
     131        return DateFormatUtils.formatUTC(time, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());
    130132    }
    131133
    132134    public static Comment createANewComment() {
    133         Comment com = new Comment();
    134         com.setCommentDate(createNewDate());
    135         return com;
     135        Comment com = new Comment();
     136        com.setCommentDate(createNewDate());
     137        return com;
    136138    }
    137139   
    138    
    139140    public static final Comparator<Comment> COMPARE_ON_DATE = new Comparator<Comment>() {
    140        
    141141        //compare two commments by the date of registration
    142         // the dates, which are strings accrording to  ISO 8601, compared lexicographically
    143     @Override   
    144     public int compare(Comment o1, Comment o2) {
    145            
    146             int result = 0;
    147            
    148             Date d1 = DatatypeConverter.parseDateTime(o1.getCommentDate()).getTime();
    149             Date d2 = DatatypeConverter.parseDateTime(o2.getCommentDate()).getTime();
    150            
    151             result = d2.compareTo(d1);
    152            
    153             return result;
     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) {
     145
     146            return (RssCreator.compareDateStrings(o1.getCommentDate(), o2.getCommentDate()));
    154147        }
    155148    };
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java

    r2259 r2268  
    3535import java.util.Arrays;
    3636import java.util.Collections;
     37import java.util.Date;
    3738import java.util.List;
    3839import javax.servlet.ServletContext;
     
    5657import javax.ws.rs.core.StreamingOutput;
    5758import javax.ws.rs.core.UriInfo;
     59import javax.xml.bind.DatatypeConverter;
    5860import javax.xml.bind.JAXBException;
    5961import org.slf4j.Logger;
     
    8789     * Converts userspace boolean to component status. Temporary solution!!!
    8890     *
    89      * TODO: Replace all calls to getRegistry that use this by calls using ComponentStatus
     91     * TODO: Replace all calls to getRegistry that use this by calls using
     92     * ComponentStatus
    9093     *
    9194     * @param userSpace
    9295     * @return
    93      * @deprecated All calls should go directly to {@link #getRegistry(clarin.cmdi.componentregistry.ComponentStatus)}
     96     * @deprecated All calls should go directly to
     97     * {@link #getRegistry(clarin.cmdi.componentregistry.ComponentStatus)}
    9498     */
    9599    @Deprecated
    96100    private static ComponentStatus getStatus(boolean userSpace) {
    97         if (userSpace) {
    98             return ComponentStatus.DEVELOPMENT;
    99         } else {
    100             return ComponentStatus.PUBLIC;
    101         }
     101        if (userSpace) {
     102            return ComponentStatus.DEVELOPMENT;
     103        } else {
     104            return ComponentStatus.PUBLIC;
     105        }
    102106    }
    103107
    104108    private ComponentRegistry getRegistry(ComponentStatus status) {
    105         Principal userPrincipal = security.getUserPrincipal();
    106         UserCredentials userCredentials = getUserCredentials(userPrincipal);
    107         return getRegistry(status, null, userCredentials);
     109        Principal userPrincipal = security.getUserPrincipal();
     110        UserCredentials userCredentials = getUserCredentials(userPrincipal);
     111        return getRegistry(status, null, userCredentials);
    108112    }
    109113
    110114    private ComponentRegistry getRegistry(ComponentStatus status, Owner owner, UserCredentials userCredentials) {
    111         try {
    112             return componentRegistryFactory.getComponentRegistry(status, owner, userCredentials);
    113         } catch (UserUnauthorizedException uuEx) {
    114             //TODO: Throw actual exception and catch nicely
    115             throw new RuntimeException("Cannot access requested registry", uuEx);
    116         }
     115        try {
     116            return componentRegistryFactory.getComponentRegistry(status, owner, userCredentials);
     117        } catch (UserUnauthorizedException uuEx) {
     118            //TODO: Throw actual exception and catch nicely
     119            throw new RuntimeException("Cannot access requested registry", uuEx);
     120        }
    117121    }
    118122
     
    123127     */
    124128    private Principal checkAndGetUserPrincipal() throws UserUnauthorizedException {
    125         Principal principal = security.getUserPrincipal();
    126         if (principal == null) {
    127             throw new UserUnauthorizedException("no user principal found.");
    128         }
    129         return principal;
     129        Principal principal = security.getUserPrincipal();
     130        if (principal == null) {
     131            throw new UserUnauthorizedException("no user principal found.");
     132        }
     133        return principal;
    130134    }
    131135
    132136    private UserCredentials getUserCredentials(Principal userPrincipal) {
    133         UserCredentials userCredentials = null;
    134         if (userPrincipal != null) {
    135             userCredentials = new UserCredentials(userPrincipal);
    136         }
    137         return userCredentials;
     137        UserCredentials userCredentials = null;
     138        if (userPrincipal != null) {
     139            userCredentials = new UserCredentials(userPrincipal);
     140        }
     141        return userCredentials;
    138142    }
    139143
     
    142146    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    143147    public List<ComponentDescription> getRegisteredComponents(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    144         long start = System.currentTimeMillis();
    145         List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions();
    146         LOG.info("Releasing " + components.size() + " registered components into the world (" + (System.currentTimeMillis() - start)
    147                 + " millisecs)");
    148         return components;
     148        long start = System.currentTimeMillis();
     149        List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions();
     150        LOG.info("Releasing " + components.size() + " registered components into the world (" + (System.currentTimeMillis() - start)
     151                + " millisecs)");
     152        return components;
    149153    }
    150154
     
    153157    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    154158    public List<ProfileDescription> getRegisteredProfiles(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace,
    155             @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor) throws ComponentRegistryException {
    156         long start = System.currentTimeMillis();
    157         List<ProfileDescription> profiles;
    158         if (metadataEditor) {
    159             profiles = getRegistry(getStatus(userspace)).getProfileDescriptionsForMetadaEditor();
    160         } else {
    161             profiles = getRegistry(getStatus(userspace)).getProfileDescriptions();
    162         }
    163 
    164         LOG.info("Releasing " + profiles.size() + " registered profiles into the world (" + (System.currentTimeMillis() - start)
    165                 + " millisecs)");
    166         return profiles;
     159            @QueryParam(METADATA_EDITOR_PARAM) @DefaultValue("false") boolean metadataEditor) throws ComponentRegistryException {
     160        long start = System.currentTimeMillis();
     161        List<ProfileDescription> profiles;
     162        if (metadataEditor) {
     163            profiles = getRegistry(getStatus(userspace)).getProfileDescriptionsForMetadaEditor();
     164        } else {
     165            profiles = getRegistry(getStatus(userspace)).getProfileDescriptions();
     166        }
     167
     168        LOG.info("Releasing " + profiles.size() + " registered profiles into the world (" + (System.currentTimeMillis() - start)
     169                + " millisecs)");
     170        return profiles;
    167171    }
    168172
     
    171175    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    172176    public Response getRegisteredComponent(@PathParam("componentId") String componentId,
    173             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    174         LOG.info("Component with id: " + componentId + " is requested.");
    175         CMDComponentSpec mdComponent = getRegistry(getStatus(userspace)).getMDComponent(componentId);
    176         if (mdComponent == null) {
    177             return Response.status(Status.NOT_FOUND).build();
    178         } else {
    179             return Response.ok(mdComponent).build();
    180         }
     177            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
     178        LOG.info("Component with id: " + componentId + " is requested.");
     179        CMDComponentSpec mdComponent = getRegistry(getStatus(userspace)).getMDComponent(componentId);
     180        if (mdComponent == null) {
     181            return Response.status(Status.NOT_FOUND).build();
     182        } else {
     183            return Response.ok(mdComponent).build();
     184        }
    181185    }
    182186
     
    185189    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
    186190    public Response getRegisteredComponentRawType(@PathParam("componentId") final String componentId, @PathParam("rawType") String rawType) {
    187         LOG.info("Component with id: " + componentId + " and rawType:" + rawType + " is requested.");
    188         StreamingOutput result = null;
    189         try {
    190             final ComponentRegistry registry = findRegistry(componentId, new ComponentClosure());
    191             if (registry == null) {
    192                 return Response.status(Status.NOT_FOUND).entity("Id: " + componentId + " is not registered, cannot create data.").build();
    193             }
    194             ComponentDescription desc = registry.getComponentDescription(componentId);
    195             checkAndThrowDescription(desc, componentId);
    196             String fileName = desc.getName() + "." + rawType;
    197             if ("xml".equalsIgnoreCase(rawType)) {
    198                 result = new StreamingOutput() {
    199                     @Override
    200                     public void write(OutputStream output) throws IOException, WebApplicationException {
    201                         try {
    202                             registry.getMDComponentAsXml(componentId, output);
    203                         } catch (ComponentRegistryException e) {
    204                             LOG.info("Could not retrieve component", e);
    205                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    206                         }
    207                     }
    208                 };
    209             } else if ("xsd".equalsIgnoreCase(rawType)) {
    210                 result = new StreamingOutput() {
    211                     @Override
    212                     public void write(OutputStream output) throws IOException, WebApplicationException {
    213                         try {
    214                             registry.getMDComponentAsXsd(componentId, output);
    215                         } catch (ComponentRegistryException e) {
    216                             LOG.info("Could not retrieve component", e);
    217                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    218                         }
    219 
    220                     }
    221                 };
    222             } else {
    223                 throw new WebApplicationException(Response.serverError().entity(
    224                         "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
    225             }
    226             return createDownloadResponse(result, fileName);
    227         } catch (ComponentRegistryException e) {
    228             LOG.info("Could not retrieve component", e);
    229             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    230         }
     191        LOG.info("Component with id: " + componentId + " and rawType:" + rawType + " is requested.");
     192        StreamingOutput result = null;
     193        try {
     194            final ComponentRegistry registry = findRegistry(componentId, new ComponentClosure());
     195            if (registry == null) {
     196                return Response.status(Status.NOT_FOUND).entity("Id: " + componentId + " is not registered, cannot create data.").build();
     197            }
     198            ComponentDescription desc = registry.getComponentDescription(componentId);
     199            checkAndThrowDescription(desc, componentId);
     200            String fileName = desc.getName() + "." + rawType;
     201            if ("xml".equalsIgnoreCase(rawType)) {
     202                result = new StreamingOutput() {
     203                    @Override
     204                    public void write(OutputStream output) throws IOException, WebApplicationException {
     205                        try {
     206                            registry.getMDComponentAsXml(componentId, output);
     207                        } catch (ComponentRegistryException e) {
     208                            LOG.info("Could not retrieve component", e);
     209                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
     210                        }
     211                    }
     212                };
     213            } else if ("xsd".equalsIgnoreCase(rawType)) {
     214                result = new StreamingOutput() {
     215                    @Override
     216                    public void write(OutputStream output) throws IOException, WebApplicationException {
     217                        try {
     218                            registry.getMDComponentAsXsd(componentId, output);
     219                        } catch (ComponentRegistryException e) {
     220                            LOG.info("Could not retrieve component", e);
     221                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
     222                        }
     223
     224                    }
     225                };
     226            } else {
     227                throw new WebApplicationException(Response.serverError().entity(
     228                        "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
     229            }
     230            return createDownloadResponse(result, fileName);
     231        } catch (ComponentRegistryException e) {
     232            LOG.info("Could not retrieve component", e);
     233            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     234        }
    231235    }
    232236
    233237    public ComponentRegistry findRegistry(String id, RegistryClosure<? extends AbstractDescription> clos) throws ComponentRegistryException {
    234         AbstractDescription desc = null;
    235         ComponentRegistry result = getRegistry(getStatus(false));
    236         desc = clos.getDescription(result, id);
    237         if (desc == null) {
    238             List<ComponentRegistry> userRegs = componentRegistryFactory.getAllUserRegistries();
    239             for (ComponentRegistry reg : userRegs) {
    240                 desc = clos.getDescription(reg, id);
    241                 if (desc != null) {
    242                     result = reg;
    243                     break;
    244                 }
    245             }
    246         }
    247         return result;
     238        AbstractDescription desc = null;
     239        ComponentRegistry result = getRegistry(getStatus(false));
     240        desc = clos.getDescription(result, id);
     241        if (desc == null) {
     242            List<ComponentRegistry> userRegs = componentRegistryFactory.getAllUserRegistries();
     243            for (ComponentRegistry reg : userRegs) {
     244                desc = clos.getDescription(reg, id);
     245                if (desc != null) {
     246                    result = reg;
     247                    break;
     248                }
     249            }
     250        }
     251        return result;
    248252    }
    249253
     
    252256    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    253257    public Response getRegisteredProfile(@PathParam("profileId") String profileId,
    254             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    255         LOG.info("Profile with id: " + profileId + " is requested.");
    256         CMDComponentSpec mdProfile = getRegistry(getStatus(userspace)).getMDProfile(profileId);
    257         if (mdProfile == null) {
    258             return Response.status(Status.NOT_FOUND).build();
    259         } else {
    260             return Response.ok(mdProfile).build();
    261         }
     258            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
     259        LOG.info("Profile with id: " + profileId + " is requested.");
     260        CMDComponentSpec mdProfile = getRegistry(getStatus(userspace)).getMDProfile(profileId);
     261        if (mdProfile == null) {
     262            return Response.status(Status.NOT_FOUND).build();
     263        } else {
     264            return Response.ok(mdProfile).build();
     265        }
    262266    }
    263267
     
    266270    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    267271    public List<AbstractDescription> getComponentUsage(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("true") boolean userspace) throws ComponentRegistryException {
    268         try {
    269             final long start = System.currentTimeMillis();
    270             ComponentRegistry registry = getRegistry(getStatus(userspace));
    271             List<ComponentDescription> components = registry.getUsageInComponents(componentId);
    272             List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
    273 
    274             LOG.info("Found " + components.size() + " components and " + profiles.size() + " profiles that use component " + componentId
    275                     + " (" + (System.currentTimeMillis() - start) + " millisecs)");
    276 
    277             List<AbstractDescription> usages = new ArrayList<AbstractDescription>(components.size() + profiles.size());
    278             usages.addAll(components);
    279             usages.addAll(profiles);
    280 
    281             return usages;
    282         } catch (ComponentRegistryException e) {
    283             LOG.info("Could not retrieve profile usage", e);
    284             throw e;
    285         }
     272        try {
     273            final long start = System.currentTimeMillis();
     274            ComponentRegistry registry = getRegistry(getStatus(userspace));
     275            List<ComponentDescription> components = registry.getUsageInComponents(componentId);
     276            List<ProfileDescription> profiles = registry.getUsageInProfiles(componentId);
     277
     278            LOG.info("Found " + components.size() + " components and " + profiles.size() + " profiles that use component " + componentId
     279                    + " (" + (System.currentTimeMillis() - start) + " millisecs)");
     280
     281            List<AbstractDescription> usages = new ArrayList<AbstractDescription>(components.size() + profiles.size());
     282            usages.addAll(components);
     283            usages.addAll(profiles);
     284
     285            return usages;
     286        } catch (ComponentRegistryException e) {
     287            LOG.info("Could not retrieve profile usage", e);
     288            throw e;
     289        }
    286290    }
    287291
     
    290294    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    291295    public List<Comment> getCommentsFromProfile(@PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    292         long start = System.currentTimeMillis();
    293         final Principal principal = security.getUserPrincipal();
    294         List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal);
    295         LOG.info("Releasing " + comments.size() + " registered comments in Profile into the world (" + (System.currentTimeMillis() - start)
    296                 + " millisecs)");
    297         return comments;
     296        long start = System.currentTimeMillis();
     297        final Principal principal = security.getUserPrincipal();
     298        List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal);
     299        LOG.info("Releasing " + comments.size() + " registered comments in Profile into the world (" + (System.currentTimeMillis() - start)
     300                + " millisecs)");
     301        return comments;
    298302    }
    299303
     
    302306    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    303307    public List<Comment> getCommentsFromComponent(@PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    304         long start = System.currentTimeMillis();
    305         final Principal principal = security.getUserPrincipal();
    306         List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal);
    307         LOG.info("Releasing " + comments.size() + " registered comments in Component into the world (" + (System.currentTimeMillis() - start)
    308                 + " millisecs)");
    309         return comments;
     308        long start = System.currentTimeMillis();
     309        final Principal principal = security.getUserPrincipal();
     310        List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal);
     311        LOG.info("Releasing " + comments.size() + " registered comments in Component into the world (" + (System.currentTimeMillis() - start)
     312                + " millisecs)");
     313        return comments;
    310314    }
    311315
     
    314318    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    315319    public Comment getSpecifiedCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    316         LOG.info(" Comments of component with id" + commentId + " are requested.");
    317         final Principal principal = security.getUserPrincipal();
    318         return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(profileId, commentId, principal);
     320        LOG.info(" Comments of component with id" + commentId + " are requested.");
     321        final Principal principal = security.getUserPrincipal();
     322        return getRegistry(getStatus(userspace)).getSpecifiedCommentInProfile(profileId, commentId, principal);
    319323    }
    320324
     
    323327    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    324328    public Comment getSpecifiedCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    325         LOG.info(" Comments of component with id" + commentId + " are requested.");
    326         final Principal principal = security.getUserPrincipal();
    327         return getRegistry(getStatus(userspace)).getSpecifiedCommentInComponent(componentId, commentId, principal);
     329        LOG.info(" Comments of component with id" + commentId + " are requested.");
     330        final Principal principal = security.getUserPrincipal();
     331        return getRegistry(getStatus(userspace)).getSpecifiedCommentInComponent(componentId, commentId, principal);
    328332    }
    329333
    330334    /**
    331335     *
    332      * Purely helper method for my front-end (FLEX) which only does post/get requests. The query param is checked and the "proper" method is
    333      * called.
     336     * Purely helper method for my front-end (FLEX) which only does post/get
     337     * requests. The query param is checked and the "proper" method is called.
    334338     *
    335339     * @param profileId
     
    340344    @Path("/profiles/{profileId}")
    341345    public Response manipulateRegisteredProfile(@PathParam("profileId") String profileId, @FormParam("method") String method,
    342             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    343         if ("delete".equalsIgnoreCase(method)) {
    344             return deleteRegisteredProfile(profileId, userspace);
    345         } else {
    346             return Response.ok().build();
    347         }
     346            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     347        if ("delete".equalsIgnoreCase(method)) {
     348            return deleteRegisteredProfile(profileId, userspace);
     349        } else {
     350            return Response.ok().build();
     351        }
    348352    }
    349353
     
    351355    @Path("/profiles/{profileId}/comments/{commentId}")
    352356    public Response manipulateCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId, @FormParam("method") String method,
    353             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    354         if ("delete".equalsIgnoreCase(method)) {
    355             return deleteCommentFromProfile(profileId, commentId, userspace);
    356         } else {
    357             return Response.ok().build();
    358         }
     357            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     358        if ("delete".equalsIgnoreCase(method)) {
     359            return deleteCommentFromProfile(profileId, commentId, userspace);
     360        } else {
     361            return Response.ok().build();
     362        }
    359363    }
    360364
     
    362366    @Path("/components/{componentId}/comments/{commentId}")
    363367    public Response manipulateCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId, @FormParam("method") String method,
    364             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    365         if ("delete".equalsIgnoreCase(method)) {
    366             return deleteCommentFromComponent(componentId, commentId, userspace);
    367         } else {
    368             return Response.ok().build();
    369         }
     368            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     369        if ("delete".equalsIgnoreCase(method)) {
     370            return deleteCommentFromComponent(componentId, commentId, userspace);
     371        } else {
     372            return Response.ok().build();
     373        }
    370374    }
    371375
     
    374378    @Consumes("multipart/form-data")
    375379    public Response publishRegisteredProfile(@PathParam("profileId") String profileId, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    376             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    377             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    378         try {
    379             Principal principal = checkAndGetUserPrincipal();
    380             ProfileDescription desc = getRegistry(getStatus(true)).getProfileDescription(profileId);
    381             if (desc != null) {
    382                 updateDescription(desc, name, description, domainName, group);
    383                 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
    384             } else {
    385                 LOG.error("Update of nonexistent id (" + profileId + ") failed.");
    386                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    387             }
    388         } catch (ComponentRegistryException e) {
    389             LOG.info("Could not retrieve component", e);
    390             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    391         } catch (UserUnauthorizedException ex) {
    392             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    393         }
     380            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     381            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     382        try {
     383            Principal principal = checkAndGetUserPrincipal();
     384            ProfileDescription desc = getRegistry(getStatus(true)).getProfileDescription(profileId);
     385            if (desc != null) {
     386                updateDescription(desc, name, description, domainName, group);
     387                return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
     388            } else {
     389                LOG.error("Update of nonexistent id (" + profileId + ") failed.");
     390                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
     391            }
     392        } catch (ComponentRegistryException e) {
     393            LOG.info("Could not retrieve component", e);
     394            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     395        } catch (UserUnauthorizedException ex) {
     396            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     397        }
    394398    }
    395399
     
    398402    @Consumes("multipart/form-data")
    399403    public Response updateRegisteredProfile(@PathParam("profileId") String profileId,
    400             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    401             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    402             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    403         try {
    404             Principal principal = checkAndGetUserPrincipal();
    405             UserCredentials userCredentials = getUserCredentials(principal);
    406             ProfileDescription desc = getRegistry(getStatus(userspace)).getProfileDescription(profileId);
    407             if (desc != null) {
    408                 updateDescription(desc, name, description, domainName, group);
    409                 return register(input, desc, userCredentials, userspace, new UpdateAction(principal));
    410             } else {
    411                 LOG.error("Update of nonexistent id (" + profileId + ") failed.");
    412                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    413             }
    414         } catch (ComponentRegistryException e) {
    415             LOG.info("Could not retrieve component", e);
    416             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    417         } catch (UserUnauthorizedException ex) {
    418             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    419         }
     404            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
     405            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     406            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     407        try {
     408            Principal principal = checkAndGetUserPrincipal();
     409            UserCredentials userCredentials = getUserCredentials(principal);
     410            ProfileDescription desc = getRegistry(getStatus(userspace)).getProfileDescription(profileId);
     411            if (desc != null) {
     412                updateDescription(desc, name, description, domainName, group);
     413                return register(input, desc, userCredentials, userspace, new UpdateAction(principal));
     414            } else {
     415                LOG.error("Update of nonexistent id (" + profileId + ") failed.");
     416                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
     417            }
     418        } catch (ComponentRegistryException e) {
     419            LOG.info("Could not retrieve component", e);
     420            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     421        } catch (UserUnauthorizedException ex) {
     422            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     423        }
    420424
    421425    }
     
    423427    /**
    424428     *
    425      * Purely helper method for my front-end (FLEX) which van only do post/get requests. The query param is checked and the "proper" method
    426      * is called.
     429     * Purely helper method for my front-end (FLEX) which van only do post/get
     430     * requests. The query param is checked and the "proper" method is called.
    427431     *
    428432     * @param componentId
     
    433437    @Path("/components/{componentId}")
    434438    public Response manipulateRegisteredComponent(@PathParam("componentId") String componentId, @FormParam("method") String method,
    435             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    436         if ("delete".equalsIgnoreCase(method)) {
    437             return deleteRegisteredComponent(componentId, userspace);
    438         } else {
    439             return Response.ok().build();
    440         }
     439            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     440        if ("delete".equalsIgnoreCase(method)) {
     441            return deleteRegisteredComponent(componentId, userspace);
     442        } else {
     443            return Response.ok().build();
     444        }
    441445    }
    442446
     
    445449    @Consumes("multipart/form-data")
    446450    public Response publishRegisteredComponent(@PathParam("componentId") String componentId,
    447             @FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    448             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
    449             @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    450         try {
    451             Principal principal = checkAndGetUserPrincipal();
    452             // TODO: Get status from parameter
    453             ComponentDescription desc = getRegistry(getStatus(true)).getComponentDescription(componentId);
    454             if (desc != null) {
    455                 updateDescription(desc, name, description, domainName, group);
    456                 return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
    457             } else {
    458                 LOG.error("Update of nonexistent id (" + componentId + ") failed.");
    459                 return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
    460             }
    461         } catch (ComponentRegistryException e) {
    462             LOG.info("Could not retrieve component", e);
    463             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    464         } catch (UserUnauthorizedException ex) {
    465             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    466         }
     451            @FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
     452            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
     453            @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     454        try {
     455            Principal principal = checkAndGetUserPrincipal();
     456            // TODO: Get status from parameter
     457            ComponentDescription desc = getRegistry(getStatus(true)).getComponentDescription(componentId);
     458            if (desc != null) {
     459                updateDescription(desc, name, description, domainName, group);
     460                return register(input, desc, getUserCredentials(principal), true, new PublishAction(principal));
     461            } else {
     462                LOG.error("Update of nonexistent id (" + componentId + ") failed.");
     463                return Response.serverError().entity("Invalid id, cannot update nonexistent profile").build();
     464            }
     465        } catch (ComponentRegistryException e) {
     466            LOG.info("Could not retrieve component", e);
     467            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     468        } catch (UserUnauthorizedException ex) {
     469            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     470        }
    467471    }
    468472
     
    471475    @Consumes("multipart/form-data")
    472476    public Response updateRegisteredComponent(@PathParam("componentId") String componentId,
    473             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
    474             @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
    475             @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
    476         try {
    477             Principal principal = checkAndGetUserPrincipal();
    478             ComponentDescription desc = getRegistry(getStatus(userspace)).getComponentDescription(componentId);
    479             if (desc != null) {
    480                 updateDescription(desc, name, description, domainName, group);
    481                 return register(input, desc, getUserCredentials(principal), userspace, new UpdateAction(principal));
    482             } else {
    483                 LOG.error("Update of nonexistent id (" + componentId + ") failed.");
    484                 return Response.serverError().entity("Invalid id, cannot update nonexistent component").build();
    485             }
    486         } catch (ComponentRegistryException e) {
    487             LOG.info("Could not retrieve component", e);
    488             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    489         } catch (UserUnauthorizedException ex) {
    490             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    491         }
     477            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @FormDataParam(DATA_FORM_FIELD) InputStream input,
     478            @FormDataParam(NAME_FORM_FIELD) String name, @FormDataParam(DESCRIPTION_FORM_FIELD) String description,
     479            @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName) {
     480        try {
     481            Principal principal = checkAndGetUserPrincipal();
     482            ComponentDescription desc = getRegistry(getStatus(userspace)).getComponentDescription(componentId);
     483            if (desc != null) {
     484                updateDescription(desc, name, description, domainName, group);
     485                return register(input, desc, getUserCredentials(principal), userspace, new UpdateAction(principal));
     486            } else {
     487                LOG.error("Update of nonexistent id (" + componentId + ") failed.");
     488                return Response.serverError().entity("Invalid id, cannot update nonexistent component").build();
     489            }
     490        } catch (ComponentRegistryException e) {
     491            LOG.info("Could not retrieve component", e);
     492            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     493        } catch (UserUnauthorizedException ex) {
     494            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     495        }
    492496    }
    493497
    494498    private void updateDescription(AbstractDescription desc, String name, String description, String domainName, String group) {
    495         desc.setName(name);
    496         desc.setDescription(description);
    497         desc.setDomainName(domainName);
    498         desc.setGroupName(group);
    499         desc.setRegistrationDate(AbstractDescription.createNewDate());
     499        desc.setName(name);
     500        desc.setDescription(description);
     501        desc.setDomainName(domainName);
     502        desc.setGroupName(group);
     503        desc.setRegistrationDate(AbstractDescription.createNewDate());
    500504    }
    501505
     
    503507    @Path("/components/{componentId}")
    504508    public Response deleteRegisteredComponent(@PathParam("componentId") String componentId,
    505             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    506         try {
    507             Principal principal = checkAndGetUserPrincipal();
    508             ComponentRegistry registry = getRegistry(getStatus(userspace));
    509             LOG.info("Component with id: " + componentId + " set for deletion.");
    510             registry.deleteMDComponent(componentId, principal, false);
    511         } catch (DeleteFailedException e) {
    512             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    513             return Response.status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    514         } catch (ComponentRegistryException e) {
    515             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    516             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    517         } catch (IOException e) {
    518             LOG.info("Component with id: " + componentId + " deletion failed.", e);
    519             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    520         } catch (UserUnauthorizedException e) {
    521             LOG.info("Component with id: " + componentId + " deletion failed: " + e.getMessage());
    522             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    523         }
    524         LOG.info("Component with id: " + componentId + " deleted.");
    525         return Response.ok().build();
     509            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     510        try {
     511            Principal principal = checkAndGetUserPrincipal();
     512            ComponentRegistry registry = getRegistry(getStatus(userspace));
     513            LOG.info("Component with id: " + componentId + " set for deletion.");
     514            registry.deleteMDComponent(componentId, principal, false);
     515        } catch (DeleteFailedException e) {
     516            LOG.info("Component with id: " + componentId + " deletion failed.", e);
     517            return Response.status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
     518        } catch (ComponentRegistryException e) {
     519            LOG.info("Component with id: " + componentId + " deletion failed.", e);
     520            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     521        } catch (IOException e) {
     522            LOG.info("Component with id: " + componentId + " deletion failed.", e);
     523            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     524        } catch (UserUnauthorizedException e) {
     525            LOG.info("Component with id: " + componentId + " deletion failed: " + e.getMessage());
     526            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
     527        }
     528        LOG.info("Component with id: " + componentId + " deleted.");
     529        return Response.ok().build();
    526530    }
    527531
     
    529533    @Path("/profiles/{profileId}")
    530534    public Response deleteRegisteredProfile(@PathParam("profileId") String profileId,
    531             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    532         try {
    533             Principal principal = checkAndGetUserPrincipal();
    534             LOG.info("Profile with id: " + profileId + " set for deletion.");
    535             getRegistry(getStatus(userspace)).deleteMDProfile(profileId, principal);
    536         } catch (DeleteFailedException e) {
    537             LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
    538             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    539         } catch (ComponentRegistryException e) {
    540             LOG.info("Could not retrieve component", e);
    541             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    542         } catch (IOException e) {
    543             LOG.info("Profile with id: " + profileId + " deletion failed.", e);
    544             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    545         } catch (UserUnauthorizedException e) {
    546             LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
    547             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    548         }
    549         LOG.info("Profile with id: " + profileId + " deleted.");
    550         return Response.ok().build();
     535            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     536        try {
     537            Principal principal = checkAndGetUserPrincipal();
     538            LOG.info("Profile with id: " + profileId + " set for deletion.");
     539            getRegistry(getStatus(userspace)).deleteMDProfile(profileId, principal);
     540        } catch (DeleteFailedException e) {
     541            LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
     542            return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
     543        } catch (ComponentRegistryException e) {
     544            LOG.info("Could not retrieve component", e);
     545            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     546        } catch (IOException e) {
     547            LOG.info("Profile with id: " + profileId + " deletion failed.", e);
     548            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     549        } catch (UserUnauthorizedException e) {
     550            LOG.info("Profile with id: " + profileId + " deletion failed: " + e.getMessage());
     551            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
     552        }
     553        LOG.info("Profile with id: " + profileId + " deleted.");
     554        return Response.ok().build();
    551555    }
    552556
     
    554558    @Path("/profiles/{profileId}/comments/{commentId}")
    555559    public Response deleteCommentFromProfile(@PathParam("profileId") String profileId, @PathParam("commentId") String commentId,
    556             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    557         try {
    558             final Principal principal = checkAndGetUserPrincipal();
    559             final ComponentRegistry registry = getRegistry(getStatus(userspace));
    560             final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId, principal);
    561             if (comment != null && profileId.equals(comment.getProfileDescriptionId())) {
    562                 LOG.info("Comment with id: " + commentId + " set for deletion.");
    563                 registry.deleteComment(commentId, principal);
    564             } else {
    565                 throw new ComponentRegistryException("Comment not found for specified profile");
    566             }
    567         } catch (DeleteFailedException e) {
    568             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    569             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    570         } catch (ComponentRegistryException e) {
    571             LOG.info("Could not retrieve component", e);
    572             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    573         } catch (IOException e) {
    574             LOG.info("Comment with id: " + commentId + " deletion failed.", e);
    575             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    576         } catch (UserUnauthorizedException e) {
    577             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    578             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    579         }
    580         LOG.info("Comment with id: " + commentId + " deleted.");
    581         return Response.ok().build();
     560            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     561        try {
     562            final Principal principal = checkAndGetUserPrincipal();
     563            final ComponentRegistry registry = getRegistry(getStatus(userspace));
     564            final Comment comment = registry.getSpecifiedCommentInProfile(profileId, commentId, principal);
     565            if (comment != null && profileId.equals(comment.getProfileDescriptionId())) {
     566                LOG.info("Comment with id: " + commentId + " set for deletion.");
     567                registry.deleteComment(commentId, principal);
     568            } else {
     569                throw new ComponentRegistryException("Comment not found for specified profile");
     570            }
     571        } catch (DeleteFailedException e) {
     572            LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
     573            return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
     574        } catch (ComponentRegistryException e) {
     575            LOG.info("Could not retrieve component", e);
     576            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     577        } catch (IOException e) {
     578            LOG.info("Comment with id: " + commentId + " deletion failed.", e);
     579            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     580        } catch (UserUnauthorizedException e) {
     581            LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
     582            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
     583        }
     584        LOG.info("Comment with id: " + commentId + " deleted.");
     585        return Response.ok().build();
    582586    }
    583587
     
    585589    @Path("/components/{componentId}/comments/{commentId}")
    586590    public Response deleteCommentFromComponent(@PathParam("componentId") String componentId, @PathParam("commentId") String commentId,
    587             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    588         try {
    589             final Principal principal = checkAndGetUserPrincipal();
    590             final ComponentRegistry registry = getRegistry(getStatus(userspace));
    591             final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId, principal);
    592             if (comment != null && componentId.equals(comment.getComponentDescriptionId())) {
    593                 LOG.info("Comment with id: " + commentId + " set for deletion.");
    594                 registry.deleteComment(commentId, principal);
    595             } else {
    596                 throw new ComponentRegistryException("Comment not found for specified component");
    597             }
    598         } catch (DeleteFailedException e) {
    599             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    600             return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
    601         } catch (ComponentRegistryException e) {
    602             LOG.info("Could not retrieve component", e);
    603             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    604         } catch (IOException e) {
    605             LOG.info("Comment with id: " + commentId + " deletion failed.", e);
    606             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    607         } catch (UserUnauthorizedException e) {
    608             LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
    609             return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
    610         }
    611         LOG.info("Comment with id: " + commentId + " deleted.");
    612         return Response.ok().build();
     591            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     592        try {
     593            final Principal principal = checkAndGetUserPrincipal();
     594            final ComponentRegistry registry = getRegistry(getStatus(userspace));
     595            final Comment comment = registry.getSpecifiedCommentInComponent(componentId, commentId, principal);
     596            if (comment != null && componentId.equals(comment.getComponentDescriptionId())) {
     597                LOG.info("Comment with id: " + commentId + " set for deletion.");
     598                registry.deleteComment(commentId, principal);
     599            } else {
     600                throw new ComponentRegistryException("Comment not found for specified component");
     601            }
     602        } catch (DeleteFailedException e) {
     603            LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
     604            return Response.serverError().status(Status.FORBIDDEN).entity("" + e.getMessage()).build();
     605        } catch (ComponentRegistryException e) {
     606            LOG.info("Could not retrieve component", e);
     607            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     608        } catch (IOException e) {
     609            LOG.info("Comment with id: " + commentId + " deletion failed.", e);
     610            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     611        } catch (UserUnauthorizedException e) {
     612            LOG.info("Comment with id: " + commentId + " deletion failed: " + e.getMessage());
     613            return Response.serverError().status(Status.UNAUTHORIZED).entity("" + e.getMessage()).build();
     614        }
     615        LOG.info("Comment with id: " + commentId + " deleted.");
     616        return Response.ok().build();
    613617    }
    614618
     
    617621    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
    618622    public Response getRegisteredProfileRawType(@PathParam("profileId") final String profileId, @PathParam("rawType") String rawType) {
    619         LOG.info("Profile with id: " + profileId + " and rawType:" + rawType + " is requested.");
    620         StreamingOutput result = null;
    621         try {
    622             final ComponentRegistry registry = findRegistry(profileId, new ProfileClosure());
    623             if (registry == null) {
    624                 return Response.status(Status.NOT_FOUND).entity("Id: " + profileId + " is not registered, cannot create data.").build();
    625             }
    626             ProfileDescription desc = registry.getProfileDescription(profileId);
    627             checkAndThrowDescription(desc, profileId);
    628             String fileName = desc.getName() + "." + rawType;
    629 
    630             if ("xml".equalsIgnoreCase(rawType)) {
    631                 result = new StreamingOutput() {
    632                     @Override
    633                     public void write(OutputStream output) throws IOException, WebApplicationException {
    634                         try {
    635                             registry.getMDProfileAsXml(profileId, output);
    636                         } catch (ComponentRegistryException e) {
    637                             LOG.warn("Could not retrieve component", e);
    638                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    639                         }
    640                     }
    641                 };
    642             } else if ("xsd".equalsIgnoreCase(rawType)) {
    643                 result = new StreamingOutput() {
    644                     @Override
    645                     public void write(OutputStream output) throws IOException, WebApplicationException {
    646                         try {
    647                             registry.getMDProfileAsXsd(profileId, output);
    648                         } catch (ComponentRegistryException e) {
    649                             LOG.warn("Could not retrieve component", e);
    650                             throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
    651                         }
    652                     }
    653                 };
    654             } else {
    655                 throw new WebApplicationException(Response.serverError().entity(
    656                         "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
    657             }
    658             return createDownloadResponse(result, fileName);
    659         } catch (ComponentRegistryException e) {
    660             LOG.info("Could not retrieve component", e);
    661             return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
    662         }
     623        LOG.info("Profile with id: " + profileId + " and rawType:" + rawType + " is requested.");
     624        StreamingOutput result = null;
     625        try {
     626            final ComponentRegistry registry = findRegistry(profileId, new ProfileClosure());
     627            if (registry == null) {
     628                return Response.status(Status.NOT_FOUND).entity("Id: " + profileId + " is not registered, cannot create data.").build();
     629            }
     630            ProfileDescription desc = registry.getProfileDescription(profileId);
     631            checkAndThrowDescription(desc, profileId);
     632            String fileName = desc.getName() + "." + rawType;
     633
     634            if ("xml".equalsIgnoreCase(rawType)) {
     635                result = new StreamingOutput() {
     636                    @Override
     637                    public void write(OutputStream output) throws IOException, WebApplicationException {
     638                        try {
     639                            registry.getMDProfileAsXml(profileId, output);
     640                        } catch (ComponentRegistryException e) {
     641                            LOG.warn("Could not retrieve component", e);
     642                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
     643                        }
     644                    }
     645                };
     646            } else if ("xsd".equalsIgnoreCase(rawType)) {
     647                result = new StreamingOutput() {
     648                    @Override
     649                    public void write(OutputStream output) throws IOException, WebApplicationException {
     650                        try {
     651                            registry.getMDProfileAsXsd(profileId, output);
     652                        } catch (ComponentRegistryException e) {
     653                            LOG.warn("Could not retrieve component", e);
     654                            throw new WebApplicationException(e, Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build());
     655                        }
     656                    }
     657                };
     658            } else {
     659                throw new WebApplicationException(Response.serverError().entity(
     660                        "unsupported rawType: " + rawType + " (only xml or xsd are supported)").build());
     661            }
     662            return createDownloadResponse(result, fileName);
     663        } catch (ComponentRegistryException e) {
     664            LOG.info("Could not retrieve component", e);
     665            return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build();
     666        }
    663667    }
    664668
    665669    private void checkAndThrowDescription(AbstractDescription desc, String id) {
    666         if (desc == null) {
    667             throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build());
    668         }
     670        if (desc == null) {
     671            throw new WebApplicationException(Response.serverError().entity("Incorrect id:" + id + "cannot handle request").build());
     672        }
    669673    }
    670674
    671675    private Response createDownloadResponse(StreamingOutput result, String fileName) {
    672         //Making response so it triggers browsers native save as dialog.
    673         Response response = Response.ok().type("application/x-download").header("Content-Disposition",
    674                 "attachment; filename=\"" + fileName + "\"").entity(result).build();
    675         return response;
     676        //Making response so it triggers browsers native save as dialog.
     677        Response response = Response.ok().type("application/x-download").header("Content-Disposition",
     678                "attachment; filename=\"" + fileName + "\"").entity(result).build();
     679        return response;
    676680
    677681    }
     
    682686    @Consumes("multipart/form-data")
    683687    public Response registerProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    684             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
    685             @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    686         try {
    687             Principal principal = checkAndGetUserPrincipal();
    688             UserCredentials userCredentials = getUserCredentials(principal);
    689             ProfileDescription desc = createNewProfileDescription();
    690             desc.setCreatorName(userCredentials.getDisplayName());
    691             desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
    692             desc.setName(name);
    693             desc.setDescription(description);
    694             desc.setGroupName(group);
    695             desc.setDomainName(domainName);
    696             LOG.info("Trying to register Profile: " + desc);
    697             return register(input, desc, userCredentials, userspace, new NewAction());
    698         } catch (UserUnauthorizedException ex) {
    699             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    700         }
     688            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group, @FormDataParam(DOMAIN_FORM_FIELD) String domainName,
     689            @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     690        try {
     691            Principal principal = checkAndGetUserPrincipal();
     692            UserCredentials userCredentials = getUserCredentials(principal);
     693            ProfileDescription desc = createNewProfileDescription();
     694            desc.setCreatorName(userCredentials.getDisplayName());
     695            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
     696            desc.setName(name);
     697            desc.setDescription(description);
     698            desc.setGroupName(group);
     699            desc.setDomainName(domainName);
     700            LOG.info("Trying to register Profile: " + desc);
     701            return register(input, desc, userCredentials, userspace, new NewAction());
     702        } catch (UserUnauthorizedException ex) {
     703            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     704        }
    701705    }
    702706
     
    706710    @Consumes("multipart/form-data")
    707711    public Response registerComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input, @FormDataParam(NAME_FORM_FIELD) String name,
    708             @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
    709             @FormDataParam(DOMAIN_FORM_FIELD) String domainName, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
    710         try {
    711             Principal principal = checkAndGetUserPrincipal();
    712             UserCredentials userCredentials = getUserCredentials(principal);
    713             ComponentDescription desc = createNewComponentDescription();
    714             desc.setCreatorName(userCredentials.getDisplayName());
    715             desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
    716             desc.setName(name);
    717             desc.setDescription(description);
    718             desc.setGroupName(group);
    719             desc.setDomainName(domainName);
    720             LOG.info("Trying to register Component: " + desc);
    721             return register(input, desc, userCredentials, userspace, new NewAction());
    722         } catch (UserUnauthorizedException ex) {
    723             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    724         }
     712            @FormDataParam(DESCRIPTION_FORM_FIELD) String description, @FormDataParam(GROUP_FORM_FIELD) String group,
     713            @FormDataParam(DOMAIN_FORM_FIELD) String domainName, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) {
     714        try {
     715            Principal principal = checkAndGetUserPrincipal();
     716            UserCredentials userCredentials = getUserCredentials(principal);
     717            ComponentDescription desc = createNewComponentDescription();
     718            desc.setCreatorName(userCredentials.getDisplayName());
     719            desc.setUserId(userCredentials.getPrincipalName()); // Hash used to be created here, now Id is constructed by impl
     720            desc.setName(name);
     721            desc.setDescription(description);
     722            desc.setGroupName(group);
     723            desc.setDomainName(domainName);
     724            LOG.info("Trying to register Component: " + desc);
     725            return register(input, desc, userCredentials, userspace, new NewAction());
     726        } catch (UserUnauthorizedException ex) {
     727            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     728        }
    725729    }
    726730
     
    730734    @Consumes("multipart/form-data")
    731735    public Response registerCommentInComponent(@FormDataParam(DATA_FORM_FIELD) InputStream input,
    732             @PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    733         try {
    734             Principal principal = checkAndGetUserPrincipal();
    735             UserCredentials userCredentials = getUserCredentials(principal);
    736             if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
    737                 throw new UserUnauthorizedException("Cannot materialize authenticated user");
    738             }
    739             // TODO: Add user/group param
    740             ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
    741             ComponentDescription description = registry.getComponentDescription(componentId);
    742             if (description != null) {
    743                 LOG.info("Trying to register comment to " + componentId);
    744                 return registerComment(input, registry, userspace, description, principal, userCredentials);
    745             } else {
    746                 LOG.error("Attempt to post comment on nonexistent component id (" + componentId + ") failed.");
    747                 return Response.serverError().entity("Invalid id, cannot comment on nonexistent component").build();
    748             }
    749         } catch (UserUnauthorizedException ex) {
    750             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    751         }
     736            @PathParam("componentId") String componentId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
     737        try {
     738            Principal principal = checkAndGetUserPrincipal();
     739            UserCredentials userCredentials = getUserCredentials(principal);
     740            if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
     741                throw new UserUnauthorizedException("Cannot materialize authenticated user");
     742            }
     743            // TODO: Add user/group param
     744            ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
     745            ComponentDescription description = registry.getComponentDescription(componentId);
     746            if (description != null) {
     747                LOG.info("Trying to register comment to " + componentId);
     748                return registerComment(input, registry, userspace, description, principal, userCredentials);
     749            } else {
     750                LOG.error("Attempt to post comment on nonexistent component id (" + componentId + ") failed.");
     751                return Response.serverError().entity("Invalid id, cannot comment on nonexistent component").build();
     752            }
     753        } catch (UserUnauthorizedException ex) {
     754            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     755        }
    752756    }
    753757
     
    757761    @Consumes("multipart/form-data")
    758762    public Response registerCommentInProfile(@FormDataParam(DATA_FORM_FIELD) InputStream input,
    759             @PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
    760         try {
    761             Principal principal = checkAndGetUserPrincipal();
    762             UserCredentials userCredentials = getUserCredentials(principal);
    763             if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
    764                 throw new UserUnauthorizedException("Cannot materialize authenticated user");
    765             }
    766             // TODO: Add user/group param
    767             ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
    768             ProfileDescription description = registry.getProfileDescription(profileId);
    769             if (description != null) {
    770                 LOG.info("Trying to register comment to " + profileId);
    771                 return registerComment(input, registry, userspace, description, principal, userCredentials);
    772             } else {
    773                 LOG.error("Attempt to post comment on nonexistent profile id (" + profileId + ") failed.");
    774                 return Response.serverError().entity("Invalid id, cannot comment on nonexistent profile").build();
    775             }
    776         } catch (UserUnauthorizedException ex) {
    777             return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
    778         }
     763            @PathParam("profileId") String profileId, @QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace) throws ComponentRegistryException {
     764        try {
     765            Principal principal = checkAndGetUserPrincipal();
     766            UserCredentials userCredentials = getUserCredentials(principal);
     767            if (null == componentRegistryFactory.getOrCreateUser(userCredentials)) {
     768                throw new UserUnauthorizedException("Cannot materialize authenticated user");
     769            }
     770            // TODO: Add user/group param
     771            ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
     772            ProfileDescription description = registry.getProfileDescription(profileId);
     773            if (description != null) {
     774                LOG.info("Trying to register comment to " + profileId);
     775                return registerComment(input, registry, userspace, description, principal, userCredentials);
     776            } else {
     777                LOG.error("Attempt to post comment on nonexistent profile id (" + profileId + ") failed.");
     778                return Response.serverError().entity("Invalid id, cannot comment on nonexistent profile").build();
     779            }
     780        } catch (UserUnauthorizedException ex) {
     781            return Response.status(Status.UNAUTHORIZED).entity(ex.getMessage()).build();
     782        }
    779783    }
    780784
     
    783787    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    784788    public Response pingSession() {
    785         boolean stillActive = false;
    786         Principal userPrincipal = security.getUserPrincipal();
    787         LOG.info("ping by user: " + (userPrincipal == null ? "null" : userPrincipal.getName()));
    788         if (request != null) {
    789             if (userPrincipal != null && !ComponentRegistryFactory.ANONYMOUS_USER.equals(userPrincipal.getName())) {
    790                 stillActive = !((HttpServletRequest) request).getSession().isNew();
    791             }
    792         }
    793         return Response.ok().entity("<session stillActive=\"" + stillActive + "\"/>").build();
     789        boolean stillActive = false;
     790        Principal userPrincipal = security.getUserPrincipal();
     791        LOG.info("ping by user: " + (userPrincipal == null ? "null" : userPrincipal.getName()));
     792        if (request != null) {
     793            if (userPrincipal != null && !ComponentRegistryFactory.ANONYMOUS_USER.equals(userPrincipal.getName())) {
     794                stillActive = !((HttpServletRequest) request).getSession().isNew();
     795            }
     796        }
     797        return Response.ok().entity("<session stillActive=\"" + stillActive + "\"/>").build();
    794798    }
    795799
    796800    private Response register(InputStream input, AbstractDescription desc, UserCredentials userCredentials, boolean userspace,
    797             RegisterAction action) {
    798         try {
    799             // TODO: Add user/group param
    800             ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
    801             DescriptionValidator descriptionValidator = new DescriptionValidator(desc);
    802             MDValidator validator = new MDValidator(input, desc, registry, getRegistry(getStatus(true)), componentRegistryFactory.getPublicRegistry());
    803             RegisterResponse response = new RegisterResponse();
    804             response.setIsInUserSpace(userspace);
    805             validate(response, descriptionValidator, validator);
    806             if (response.getErrors().isEmpty()) {
    807 
    808                 CMDComponentSpec spec = validator.getCMDComponentSpec();
    809 
    810                 // Olha: removing filename from spec before it gets extended!!! recursion over all the components
    811                 setFileNamesFromListToNull(spec.getCMDComponent());
    812 
    813 
    814 
    815                 try {
    816 
    817 
    818                     // Expand to check for recursion
    819                     registry.getExpander().expandNestedComponent(spec.getCMDComponent(), desc.getId());
    820 
    821 
    822 
    823                     // Add profile
    824 
    825 
    826                     int returnCode = action.execute(desc, spec, response, registry);
    827                     if (returnCode == 0) {
    828                         response.setRegistered(true);
    829                         response.setDescription(desc);
    830                     } else {
    831                         response.setRegistered(false);
    832                         response.addError("Unable to register at this moment. Internal server error.");
    833                     }
    834                 } catch (ComponentRegistryException ex) {
    835                     // Recursion detected
    836                     response.setRegistered(false);
    837                     response.addError("Error while expanding specification. " + ex.getMessage());
    838                 }
    839             } else {
    840                 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
    841                 response.setRegistered(false);
    842             }
    843             response.setIsProfile(desc.isProfile());
    844             return Response.ok(response).build();
    845         } finally {
    846             try {
    847                 input.close();//either we read the input or there was an exception, we need to close it.
    848             } catch (IOException e) {
    849                 LOG.error("Error when closing inputstream: ", e);
    850             }
    851         }
     801            RegisterAction action) {
     802        try {
     803            // TODO: Add user/group param
     804            ComponentRegistry registry = getRegistry(getStatus(userspace), null, userCredentials);
     805            DescriptionValidator descriptionValidator = new DescriptionValidator(desc);
     806            MDValidator validator = new MDValidator(input, desc, registry, getRegistry(getStatus(true)), componentRegistryFactory.getPublicRegistry());
     807            RegisterResponse response = new RegisterResponse();
     808            response.setIsInUserSpace(userspace);
     809            validate(response, descriptionValidator, validator);
     810            if (response.getErrors().isEmpty()) {
     811
     812                CMDComponentSpec spec = validator.getCMDComponentSpec();
     813
     814                // Olha: removing filename from spec before it gets extended!!! recursion over all the components
     815                setFileNamesFromListToNull(spec.getCMDComponent());
     816
     817
     818
     819                try {
     820
     821
     822                    // Expand to check for recursion
     823                    registry.getExpander().expandNestedComponent(spec.getCMDComponent(), desc.getId());
     824
     825
     826
     827                    // Add profile
     828
     829
     830                    int returnCode = action.execute(desc, spec, response, registry);
     831                    if (returnCode == 0) {
     832                        response.setRegistered(true);
     833                        response.setDescription(desc);
     834                    } else {
     835                        response.setRegistered(false);
     836                        response.addError("Unable to register at this moment. Internal server error.");
     837                    }
     838                } catch (ComponentRegistryException ex) {
     839                    // Recursion detected
     840                    response.setRegistered(false);
     841                    response.addError("Error while expanding specification. " + ex.getMessage());
     842                }
     843            } else {
     844                LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
     845                response.setRegistered(false);
     846            }
     847            response.setIsProfile(desc.isProfile());
     848            return Response.ok(response).build();
     849        } finally {
     850            try {
     851                input.close();//either we read the input or there was an exception, we need to close it.
     852            } catch (IOException e) {
     853                LOG.error("Error when closing inputstream: ", e);
     854            }
     855        }
    852856    }
    853857
    854858    private Response registerComment(InputStream input, ComponentRegistry registry, boolean userspace,
    855             AbstractDescription description, Principal principal, UserCredentials userCredentials) {
    856         try {
    857             CommentValidator validator = new CommentValidator(input, description);
    858             CommentResponse response = new CommentResponse();
    859             response.setIsInUserSpace(userspace);
    860             validateComment(response, validator);
    861             if (response.getErrors().isEmpty()) {
    862                 Comment com = validator.getCommentSpec();
    863                 //int returnCode = action.executeComment(com, response, registry, principal.getName());
    864 
    865                 // If user name is left empty, fill it using the user's display name
    866                 if (null == com.getUserName() || "".equals(com.getUserName())) {
    867                     if (userCredentials != null) {
    868                         com.setUserName(userCredentials.getDisplayName());
    869                     } else {
    870                         com.setUserName(principal.getName());
    871                     }
    872                 }
    873 
    874                 int returnCode = registry.registerComment(com, principal.getName());
    875                 if (returnCode == 0) {
    876                     response.setRegistered(true);
    877                     response.setComment(com);
    878                 } else {
    879                     response.setRegistered(false);
    880                     response.addError("Unable to register at this moment. Internal server error.");
    881                 }
    882             } else {
    883                 LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
    884                 response.setRegistered(false);
    885             }
    886             return Response.ok(response).build();
    887         } catch (ComponentRegistryException ex) {
    888             LOG.error("Error while inserting comment: ", ex);
    889             return Response.serverError().entity(ex.getMessage()).build();
    890         } finally {
    891             try {
    892                 input.close();//either we read the input or there was an exception, we need to close it.
    893             } catch (IOException e) {
    894                 LOG.error("Error when closing inputstream: ", e);
    895                 return Response.serverError().build();
    896             }
    897         }
     859            AbstractDescription description, Principal principal, UserCredentials userCredentials) {
     860        try {
     861            CommentValidator validator = new CommentValidator(input, description);
     862            CommentResponse response = new CommentResponse();
     863            response.setIsInUserSpace(userspace);
     864            validateComment(response, validator);
     865            if (response.getErrors().isEmpty()) {
     866                Comment com = validator.getCommentSpec();
     867                //int returnCode = action.executeComment(com, response, registry, principal.getName());
     868
     869                // If user name is left empty, fill it using the user's display name
     870                if (null == com.getUserName() || "".equals(com.getUserName())) {
     871                    if (userCredentials != null) {
     872                        com.setUserName(userCredentials.getDisplayName());
     873                    } else {
     874                        com.setUserName(principal.getName());
     875                    }
     876                }
     877
     878                int returnCode = registry.registerComment(com, principal.getName());
     879                if (returnCode == 0) {
     880                    response.setRegistered(true);
     881                    response.setComment(com);
     882                } else {
     883                    response.setRegistered(false);
     884                    response.addError("Unable to register at this moment. Internal server error.");
     885                }
     886            } else {
     887                LOG.info("Registration failed with validation errors:" + Arrays.toString(response.getErrors().toArray()));
     888                response.setRegistered(false);
     889            }
     890            return Response.ok(response).build();
     891        } catch (ComponentRegistryException ex) {
     892            LOG.error("Error while inserting comment: ", ex);
     893            return Response.serverError().entity(ex.getMessage()).build();
     894        } finally {
     895            try {
     896                input.close();//either we read the input or there was an exception, we need to close it.
     897            } catch (IOException e) {
     898                LOG.error("Error when closing inputstream: ", e);
     899                return Response.serverError().build();
     900            }
     901        }
    898902    }
    899903
    900904    private ComponentDescription createNewComponentDescription() {
    901         ComponentDescription desc = ComponentDescription.createNewDescription();
    902         desc.setHref(createXlink(desc.getId()));
    903         return desc;
     905        ComponentDescription desc = ComponentDescription.createNewDescription();
     906        desc.setHref(createXlink(desc.getId()));
     907        return desc;
    904908    }
    905909
    906910    private ProfileDescription createNewProfileDescription() {
    907         ProfileDescription desc = ProfileDescription.createNewDescription();
    908         desc.setHref(createXlink(desc.getId()));
    909         return desc;
     911        ProfileDescription desc = ProfileDescription.createNewDescription();
     912        desc.setHref(createXlink(desc.getId()));
     913        return desc;
    910914    }
    911915
    912916    private String createXlink(String id) {
    913         URI uri = uriInfo.getRequestUriBuilder().path(id).build();
    914         return uri.toString();
     917        URI uri = uriInfo.getRequestUriBuilder().path(id).build();
     918        return uri.toString();
    915919    }
    916920
    917921    /**
    918922     *
    919      * @return The application's base URI as configured in the "componentRegistryServiceRootUrl" context parameter.
    920      * If correctly configured, it should look something like "http://catalog.clarin.eu/ds/ComponentRegistry".
    921      * <em>Be aware that this can also be null if configured incorrectly!</em>
     923     * @return The application's base URI as configured in the
     924     * "componentRegistryServiceRootUrl" context parameter. If correctly
     925     * configured, it should look something like
     926     * "http://catalog.clarin.eu/ds/ComponentRegistry". <em>Be aware that this
     927     * can also be null if configured incorrectly!</em>
    922928     *
    923929     * @see #APPLICATION_BASE_URL_PARAM
    924930     */
    925931    private String getApplicationBaseURI() {
    926         return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
     932        return servletContext.getInitParameter(APPLICATION_BASE_URL_PARAM);
    927933    }
    928934
    929935    private void validate(RegisterResponse response, Validator... validators) {
    930         for (Validator validator : validators) {
    931             if (!validator.validate()) {
    932                 for (String error : validator.getErrorMessages()) {
    933                     response.addError(error);
    934                 }
    935             }
    936         }
     936        for (Validator validator : validators) {
     937            if (!validator.validate()) {
     938                for (String error : validator.getErrorMessages()) {
     939                    response.addError(error);
     940                }
     941            }
     942        }
    937943    }
    938944
    939945    private void validateComment(CommentResponse response, Validator... validators) {
    940         for (Validator validator : validators) {
    941             if (!validator.validate()) {
    942                 for (String error : validator.getErrorMessages()) {
    943                     response.addError(error);
    944                 }
    945             }
    946         }
     946        for (Validator validator : validators) {
     947            if (!validator.validate()) {
     948                for (String error : validator.getErrorMessages()) {
     949                    response.addError(error);
     950                }
     951            }
     952        }
    947953    }
    948954
     
    951957     */
    952958    public void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory) {
    953         this.componentRegistryFactory = componentRegistryFactory;
     959        this.componentRegistryFactory = componentRegistryFactory;
    954960    }
    955961
     
    960966    public void setFileNamesFromListToNull(List<CMDComponentType> listofcomponents) {
    961967
    962         for (CMDComponentType currentcomponent : listofcomponents) {
    963             setFileNamesToNullCurrent(currentcomponent);
    964         }
     968        for (CMDComponentType currentcomponent : listofcomponents) {
     969            setFileNamesToNullCurrent(currentcomponent);
     970        }
    965971
    966972    }
     
    971977    public void setFileNamesToNullCurrent(CMDComponentType currentcomponent) {
    972978
    973         currentcomponent.setFilename(null);
    974         setFileNamesFromListToNull(currentcomponent.getCMDComponent());
     979        currentcomponent.setFilename(null);
     980        setFileNamesFromListToNull(currentcomponent.getCMDComponent());
    975981
    976982    }
     
    980986     *
    981987     */
    982    
    983      private <T extends AbstractDescription> Rss getRss(boolean userspace,String limit, List<T> descs, String kindofdesc) throws ComponentRegistryException, ParseException {
    984        
    985         String baseUri = getApplicationBaseURI()+"/";
    986         RssCreatorDescriptions rssCreator = new RssCreatorDescriptions(baseUri);
    987         rssCreator.setVersion(2.0);
     988    private <T extends AbstractDescription> Rss getRss(String limit, List<T> descs,
     989            String link, String description, String title) throws ComponentRegistryException, ParseException {
     990
    988991       
     992        RssCreatorDescriptions rssCreator = new RssCreatorDescriptions();
    989993       
     994        rssCreator.setLink(link);
     995        rssCreator.setDescription(description);
     996        rssCreator.setTitle(title);
     997
     998        Collections.sort(descs, AbstractDescription.COMPARE_ON_DATE);
     999
    9901000        int limitInt = Integer.parseInt(limit);
     1001
     1002        if (descs.size() < limitInt) {
     1003            limitInt = descs.size();
     1004        };
     1005        List<T> sublist = descs.subList(0, limitInt);
     1006
     1007        Rss rss = rssCreator.makeRss(sublist);
     1008
     1009        return rss;
     1010    }
     1011    ////////////////////////////////////////////////
     1012
     1013    @GET
     1014    @Path("/components/rss")
     1015    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
     1016    public Rss getRssComponent(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException {
     1017
     1018        List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions();
    9911019       
    992         if (descs.size()<limitInt) {limitInt = descs.size();};
    993         List<T> sublist = descs.subList(0, limitInt);
    994         Collections.sort(sublist, AbstractDescription.COMPARE_ON_DATE);
     1020        String title;
     1021         if (userspace) { title= "Workspace components";}
     1022         else {title= "Workspace components";
     1023       }
     1024         String link= getApplicationBaseURI() + "/";
     1025         String description = "Updates for components";
    9951026       
     1027        Rss rss = getRss(limit, components, link, description, title);
     1028
     1029        LOG.info("Releasing " + limit + "most recent registered components into the world sorted by their registration date-and-time");
     1030
     1031
     1032        return rss;
     1033    }
     1034
     1035    ////////////////////////////////////////////////
     1036    @GET
     1037    @Path("/profiles/rss")
     1038    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
     1039    public Rss getRssProfile(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException {
     1040
    9961041       
    997         if (userspace)   {rssCreator.setTitle("Workspace "+kindofdesc);}
    998         else {rssCreator.setTitle("Public "+kindofdesc);}
     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= "Workspace profiles";
     1049       }
     1050         String link= getApplicationBaseURI() + "/";
     1051         String description = "Updates for profiles";
     1052       
     1053        Rss rss = getRss(limit, profiles, link, description, title);
     1054       
     1055
     1056        LOG.info("Releasing " + limit + "most recent registered profiles into the world sorted by their registration date-and-time");
     1057        return rss;
     1058    }
     1059
     1060    /* auxiliary debigging piece of code for grabbing Id-s of profiles and comments
     1061     *
     1062     List<ProfileDescription> lprfaux = getRegisteredProfiles(userspace, true);
     1063       
    9991064         
    1000         Rss rss =rssCreator.makeRss(sublist);
    1001 
    1002         return rss;
    1003     }
    1004     ////////////////////////////////////////////////
    1005 
    1006     @GET
    1007     @Path("/components/rss")
    1008     @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    1009     public Rss getRssComponent(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException {
    1010    
    1011        List<ComponentDescription> components = getRegistry(getStatus(userspace)).getComponentDescriptions();
    1012       Rss rss = getRss(userspace, limit, components, "components");
     1065     for (ProfileDescription currentProfile : lprfaux) {
     1066     String currentProfileId = currentProfile.getId();
     1067     LOG.debug(currentProfileId);
     1068           
     1069     }
     1070     *
     1071     List<ComponentDescription> lcmaux = getRegisteredProfiles(userspace, true);
    10131072       
    1014       LOG.info("Releasing " + limit + "most recent registered components into the world sorted by their registration date-and-time");
    1015        
     1073         
     1074     for (ProfileDescription currentProfile : lprfaux) {
     1075     String currentProfileId = currentProfile.getId();
     1076     LOG.debug(currentProfileId);
     1077           
     1078     }
     1079     *
    10161080       
    1017        return rss;
    1018     }
    1019 
    1020     ////////////////////////////////////////////////
    1021     @GET
    1022     @Path("/profiles/rss")
    1023     @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    1024     public Rss getRssProfile(@QueryParam(USERSPACE_PARAM) @DefaultValue("false") boolean userspace, @QueryParam(NUMBER_OF_RSSITEMS) @DefaultValue("20") String limit) throws ComponentRegistryException, ParseException {
    1025 
    1026         //http://www.clarin.eu/cmdi/profiles
    1027 
    1028         // ?? How to get rid of the deprecated stuff ??
    1029         List<ProfileDescription> profiles = getRegistry(getStatus(userspace)).getProfileDescriptions();
    1030         Rss rss = getRss(userspace, limit, profiles, "profiles");
    1031 
    1032         LOG.info("Releasing " + limit + "most recent registered profiles into the world sorted by their registration date-and-time");
    1033         return rss;
    1034     }
    1035 
     1081     */
    10361082    ///////////////////////////////////////////////////////////
    1037     @GET
    1038     @Path("/profiles/{profileId}/comments/rss")
    1039     @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    1040     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 {
    1041 
    1042 
    1043         // ?? this is for debugging. But, anyway, how to get all the profiles without the need to type them in?
    1044         // what if a user do not remember his/her id of profile?
    1045         // grabbing all registered profile names from the register and outputting them  on the tomcat terminal */
    1046         /*List<ProfileDescription> lprfaux = getRegisteredProfiles(userspace, true);
    1047        
    1048         for (ProfileDescription currentProfile : lprfaux) {
    1049             String currentProfileId = currentProfile.getId();
    1050             LOG.debug(currentProfileId);
    1051         }
    1052         */
    1053         // end of grabbing */
    1054 
    1055 
    1056 
    1057         final Principal principal = security.getUserPrincipal();
    1058         List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal);
    1059 
    1060         String baseUri = getApplicationBaseURI()+"/";
    1061        
    1062        
     1083    private Rss getRssOfComments(String limit, List<Comment> comments, String description,
     1084            String title, String link) throws ComponentRegistryException, ParseException, IOException, JAXBException {
     1085
     1086        Collections.sort(comments, Comment.COMPARE_ON_DATE);
     1087
    10631088        int limitInt = Integer.parseInt(limit);
    1064        
    1065         if (comments.size()<limitInt) {limitInt = comments.size();};
     1089        if (comments.size() < limitInt) {
     1090            limitInt = comments.size();
     1091        };
    10661092        List<Comment> sublist = comments.subList(0, limitInt);
    1067         Collections.sort(sublist, Comment.COMPARE_ON_DATE);
    1068        
    1069         for (Comment comm: sublist){
    1070             LOG.debug(comm.getCommentDate());
    1071         }
    1072          
    1073         RssCreatorComments instance = new RssCreatorComments(baseUri);
    1074         instance.setFlagIsFromProfile(true);
    1075         instance.setDescription("Update of comments for current profile");
    1076        
    1077         String hrefPostfix = "&view=comments";
    1078         String hrefInfix = "?item=";
    1079         instance.setLink(baseUri+hrefInfix+profileId+hrefPostfix);
    1080        
    1081         String title="Comments feed for the profile \""+
    1082                 getRegistry(getStatus(userspace)).getProfileDescription(profileId).getName()+
    1083                 "\" ";
     1093
     1094
     1095        // debug stuff, to see if the dates are sorted with the latest on the top
     1096        for (Comment comm : sublist) {
     1097            String dt = comm.getCommentDate();
     1098            LOG.debug(dt);
     1099        }
     1100        //
     1101
     1102
     1103
     1104        RssCreatorComments instance = new RssCreatorComments();
     1105
     1106        instance.setDescription(description);
     1107        instance.setLink(link);
    10841108        instance.setTitle(title);
    1085        
    1086        
     1109
    10871110        Rss result = instance.makeRss(sublist);
    10881111       
    1089         // testing stuff
    1090         String path=openTestDir("testRss");
     1112         // testing stuff
     1113        String path = openTestDir("testRss");
    10911114        String os = MDMarshaller.marshalToString(result);
    10921115        writeStringToFile(os, path + "testRssResl.xml");
    10931116        //end of testing stuff
     1117
     1118        // debugging stuff
     1119        LOG.debug("The amount of items: " + Integer.toString(result.getChannel().getItem().size()));
     1120        LOG.debug("The amount of comments: " + Integer.toString(comments.size()));
     1121        // end of debugging stuff
     1122
     1123
     1124
     1125        return result;
     1126
     1127    }
     1128
     1129    ///////////////////////////////////////////////////////
     1130    @GET
     1131    @Path("/profiles/{profileId}/comments/rss")
     1132    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
     1133    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 {
     1134
     1135
     1136        final Principal principal = security.getUserPrincipal();
     1137        List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInProfile(profileId, principal);
     1138
     1139        String baseUri = getApplicationBaseURI() + "/";
     1140        String link = baseUri + "?item=" + profileId + "&view=comments";
     1141
     1142        String title = "Comments feed for the profile \""
     1143                + getRegistry(getStatus(userspace)).getProfileDescription(profileId).getName()
     1144                + "\" ";
     1145
     1146        Rss result = getRssOfComments(limit, comments, "Update of comments for current profile",
     1147                title, link);
     1148
     1149       
     1150        return result;
     1151    }
     1152
     1153    //////////////////////////////
     1154    @GET
     1155    @Path("/components/{componentId}/comments/rss")
     1156    @Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
     1157    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 {
     1158
     1159        //debigging piece
     1160        List<ComponentDescription> lcmaux = getRegisteredComponents(userspace);
     1161
     1162
     1163        for (ComponentDescription current : lcmaux) {
     1164            String currentId = current.getId();
     1165            LOG.debug(currentId);
     1166        }
    10941167       
    1095         // debugging stuff
    1096         LOG.debug("The amount of items: "+Integer.toString(result.getChannel().getItem().size()));
    1097         LOG.debug("The amount of comments: "+Integer.toString(comments.size()));
    1098         // end of debugging stuff
    1099        
    1100 
    1101         return result;
     1168        //end of debug
     1169
     1170        final Principal principal = security.getUserPrincipal();
     1171        List<Comment> comments = getRegistry(getStatus(userspace)).getCommentsInComponent(componentId, principal);
     1172
     1173        String baseUri = getApplicationBaseURI() + "/";
     1174        String link = baseUri + "?item=" + componentId + "&view=comments";
     1175        String title = "Comments feed for the component \""
     1176                + getRegistry(getStatus(userspace)).getComponentDescription(componentId).getName()
     1177                + "\" ";
     1178
     1179        Rss result = getRssOfComments(limit, comments, "Update of comments for current component",
     1180                title, link);
     1181
     1182
     1183
     1184        return result;
    11021185    }
    11031186
     
    11061189    /**
    11071190     *
    1108      * @param bytes is an array of bytes to be written in the file filename (from scratch!)
    1109      * @param filename is the name of the file where the array "bytes" is to be written to
     1191     * @param bytes is an array of bytes to be written in the file filename
     1192     * (from scratch!)
     1193     * @param filename is the name of the file where the array "bytes" is to be
     1194     * written to
    11101195     * @throws IOException
    11111196     * @throws JAXBException
     
    11131198    public static void writeBytesToFile(byte[] bytes, String filename) throws IOException, JAXBException {
    11141199
    1115         File file = new File(filename);
    1116         FileOutputStream fop = new FileOutputStream(file);
    1117 
    1118         fop.write(bytes);
    1119 
    1120         fop.flush();
    1121         fop.close();
     1200        File file = new File(filename);
     1201        FileOutputStream fop = new FileOutputStream(file);
     1202
     1203        fop.write(bytes);
     1204
     1205        fop.flush();
     1206        fop.close();
    11221207
    11231208
     
    11261211    /**
    11271212     *
    1128      * @param str is a string which is to be written into the filename (from scratch!)
     1213     * @param str is a string which is to be written into the filename (from
     1214     * scratch!)
    11291215     * @param filename is a filename where the string is to be written to
    11301216     * @throws IOException
     
    11331219    public static void writeStringToFile(String str, String filename) throws IOException, JAXBException {
    11341220
    1135         writeBytesToFile(str.getBytes(), filename);
     1221        writeBytesToFile(str.getBytes(), filename);
    11361222
    11371223
     
    11401226    /**
    11411227     *
    1142      * @param os is an output stream which is to be written into the filename (from scratch!)
     1228     * @param os is an output stream which is to be written into the filename
     1229     * (from scratch!)
    11431230     * @param filename is a filename where the stream is to be written to
    11441231     * @throws IOException
     
    11471234    public static void writeStreamToFile(ByteArrayOutputStream os, String filename) throws IOException, JAXBException {
    11481235
    1149         writeBytesToFile(os.toByteArray(), filename);
     1236        writeBytesToFile(os.toByteArray(), filename);
    11501237
    11511238
     
    11541241    /**
    11551242     *
    1156      * @param cdesc is a component which is to be written into the filename (from scratch!)
     1243     * @param cdesc is a component which is to be written into the filename
     1244     * (from scratch!)
    11571245     * @param filename is a filename where the component is to be written to
    11581246     * @throws IOException
     
    11621250
    11631251
    1164         ByteArrayOutputStream os = new ByteArrayOutputStream();
    1165         MDMarshaller.marshal(cdesc, os);
    1166 
    1167         writeStreamToFile(os, filename);
     1252        ByteArrayOutputStream os = new ByteArrayOutputStream();
     1253        MDMarshaller.marshal(cdesc, os);
     1254
     1255        writeStreamToFile(os, filename);
    11681256
    11691257    }
     
    11721260     * opens a temporary sub-directory dirName in /target/
    11731261     *
    1174      * @param dirName is the name of the temporary subdirectory which is to be opened
     1262     * @param dirName is the name of the temporary subdirectory which is to be
     1263     * opened
    11751264     * @return the absolute part for this directory
    11761265     */
    11771266    public static String openTestDir(String dirName) {
    11781267
    1179         File testDir = new File("target/" + dirName);
    1180 
    1181 
    1182         testDir.mkdir();
    1183 
    1184         System.out.println(dirName);
    1185         //String retval = new File(testDir, dirName).getAbsolutePath();
    1186         String retval = new File(testDir, "/").getAbsolutePath();
    1187 
    1188         return (retval);
     1268        File testDir = new File("target/" + dirName);
     1269
     1270
     1271        testDir.mkdir();
     1272
     1273        System.out.println(dirName);
     1274        //String retval = new File(testDir, dirName).getAbsolutePath();
     1275        String retval = new File(testDir, "/").getAbsolutePath();
     1276
     1277        return (retval);
    11891278
    11901279    }
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/RssCreatorCommentsTest.java

    r2259 r2268  
    9090       
    9191       
    92         RssCreatorComments instance = new RssCreatorComments(hrefPrefix);
     92        RssCreatorComments instance = new RssCreatorComments();
    9393        assertEquals(Double.toString(instance.getVersion()) , "2.0"); // check if the default version is set properly
    9494       
    95         instance.setFlagIsFromProfile(isFromProfile);
     95       
    9696        instance.setVersion(3.0);
    9797       
  • ComponentRegistry/branches/ComponentRegistry-1.13.0-olha/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/RssCreatorDescriptionsTest.java

    r2256 r2268  
    4848    private void createTestDescription(AbstractDescription desc, int commentcount, String creatorname,
    4949            String description, String domainname, String groupname,
    50             String name, String date, String id) {
     50            String name, String date, String href, String id) {
    5151       
    5252        desc.setId(id);
     
    5858        desc.setName(name);
    5959        desc.setRegistrationDate(date);
    60         desc.setHref(null);
     60        desc.setHref(href+id);
    6161
    6262    }
     
    6464    private ProfileDescription createTestProfileDescription(int commentcount, String creatorname,
    6565            String description, String domainname, String groupname,
    66             String name, boolean editorFlag, String date, String id) {
     66            String name, boolean editorFlag, String date, String href, String id) {
    6767
    6868        ProfileDescription pdesc = ProfileDescription.createNewDescription();
    6969
    70         createTestDescription(pdesc, commentcount, creatorname, description, domainname, groupname, name, date, id);
     70        createTestDescription(pdesc, commentcount, creatorname, description, domainname, groupname, name, date, href, id);
    7171
    7272        pdesc.setShowInEditor(editorFlag);
     
    7979    private ComponentDescription createTestComponentDescription(int commentcount, String creatorname,
    8080            String description, String domainname, String groupname,
    81             String name, String date, String id) {
     81            String name, String date, String href, String id) {
    8282
    8383        ComponentDescription cdesc = ComponentDescription.createNewDescription();
    8484
    85         createTestDescription(cdesc, commentcount, creatorname, description, domainname, groupname, name, date, id);
     85        createTestDescription(cdesc, commentcount, creatorname, description, domainname, groupname, name, date, href, id);
    8686
    8787        return cdesc;
     
    9494       
    9595        assertEquals(description, item.getDescription());
    96         assertEquals(href, item.getGuid().getValue()  );
     96        //assertEquals(href, item.getGuid().getValue()  );
    9797        assertEquals(href, item.getLink());
    9898        assertEquals(date, item.getPubDate());
     
    108108
    109109       
    110         String hrefPrefix = "http://catalog.clarin.eu/ds/ComponentRegistry/";
    111         String hrefInfix="?item=";
     110        String link = "http://catalog.clarin.eu/ds/ComponentRegistry/profiles";
     111        String href =  link+"?item=";
    112112       
    113113        ProfileDescription desc1 = createTestProfileDescription(23, "Useratti",
    114                 "description-1", "domainname-1", "groupname-1", "name-1", true, "2001-01-01", "p_1");
     114                "description-1", "domainname-1", "groupname-1", "name-1", true, "2001-01-01", href,"p_1");
    115115
    116116        ProfileDescription desc2 = createTestProfileDescription(23, "Usereno",
    117                 "description-2", "domainname-2", "groupname-2", "name-2", false, "2001-01-02", "p_2");
     117                "description-2", "domainname-2", "groupname-2", "name-2", false, "2001-01-02", href, "p_2");
    118118
    119119        ProfileDescription desc3 = createTestProfileDescription(23, "Userio",
    120                 "description-3", "domainname-3", "groupname-3", "name-3", true, "2001-01-03", "p_3");
     120                "description-3", "domainname-3", "groupname-3", "name-3", true, "2001-01-03", href, "p_3");
    121121
    122122        List<ProfileDescription> descriptions = Arrays.asList(desc1, desc2, desc3);
    123123
    124         RssCreatorDescriptions instance = new RssCreatorDescriptions(hrefPrefix);
     124        RssCreatorDescriptions instance = new RssCreatorDescriptions();
    125125       
    126126       
     
    129129        instance.setVersion(2.0);
    130130       
    131         instance.setLink(null);
     131        instance.setLink(link);
    132132        instance.setCategory(null);
    133133        instance.setCloud(null);
     
    158158        // String creatorname, String description, String href, String date, String nametitle, RssItem item
    159159       
    160         String href =  hrefPrefix+hrefInfix;
     160       
    161161
    162162        compareRssVsValues("description-1", href+"p_1", "2001-01-01",
     
    182182        assertEquals("engl", result.getChannel().getLanguage());
    183183        assertEquals("today", result.getChannel().getLastBuildDate());
    184         assertEquals(null, result.getChannel().getLink());
     184        assertEquals(link, result.getChannel().getLink());
    185185        assertEquals("twan", result.getChannel().getManagingEditor());
    186186        assertEquals("publication date", result.getChannel().getPubDate());
Note: See TracChangeset for help on using the changeset viewer.