Changeset 3449


Ignore:
Timestamp:
08/20/13 15:32:37 (11 years ago)
Author:
George.Georgovassilis@mpi.nl
Message:

#360 Refactoring of transaction handling, tests and application context

Location:
ComponentRegistry/trunk/ComponentRegistry
Files:
16 added
10 deleted
30 edited

Legend:

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

    r2808 r3449  
    11
    2 <project xmlns="http://maven.apache.org/POM/4.0.0"
    3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    5     <modelVersion>4.0.0</modelVersion>
    6     <parent>
     2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
     4        <modelVersion>4.0.0</modelVersion>
     5        <parent>
     6                <groupId>clarin.cmdi</groupId>
     7                <artifactId>componentRegistry.parent</artifactId>
     8                <version>1.0</version>
     9        </parent>
    710        <groupId>clarin.cmdi</groupId>
    8         <artifactId>componentRegistry.parent</artifactId>
    9         <version>1.0</version>
    10     </parent>
    11     <groupId>clarin.cmdi</groupId>
    12     <artifactId>ComponentRegistry</artifactId>
    13     <packaging>${packaging}</packaging>
    14     <version>${ComponentRegistry.version}</version>
    15     <name>ComponentRegistry</name>
    16     <description>
     11        <artifactId>ComponentRegistry</artifactId>
     12        <packaging>${packaging}</packaging>
     13        <version>${ComponentRegistry.version}</version>
     14        <name>ComponentRegistry</name>
     15        <description>
    1716        ComponentRegistry is part of the clarin metadata infrastructure (cmdi).
    1817        The goal of the ComponentRegistry will be to register and make searchable Metadata Components and Profiles.
    1918    </description>
    20     <ciManagement>
    21         <system>hudson</system>
    22         <url>http://lux16.mpi.nl/jenkins/job/ComponentRegistry/</url>
    23     </ciManagement>
    24     <scm>
    25         <connection>scm:svn:http://svn.clarin.eu/ComponentRegistry/trunk/ComponentRegistry</connection>
    26         <developerConnection>scm:svn:http://svn.clarin.eu/ComponentRegistry/trunk/ComponentRegistry</developerConnection>
    27         <url>http://trac.clarin.eu/browser/ComponentRegistry</url>
    28     </scm>
    29 
    30     <dependencies>
    31         <dependency>
    32             <groupId>junit</groupId>
    33             <artifactId>junit</artifactId>
    34             <version>4.11</version>
    35             <scope>test</scope>
    36         </dependency>
    37         <dependency>
    38             <groupId>net.sf.saxon</groupId>
    39             <artifactId>Saxon-HE</artifactId>
    40             <version>9.4</version>
    41         </dependency>                                                 
    42         <dependency>
    43             <groupId>javax.servlet</groupId>
    44             <artifactId>servlet-api</artifactId>
    45             <version>2.5</version>
    46             <scope>provided</scope>
    47         </dependency>
    48         <dependency>
    49             <groupId>commons-codec</groupId>
    50             <artifactId>commons-codec</artifactId>
    51             <version>1.3</version>
    52         </dependency>
    53         <dependency>
    54             <groupId>commons-io</groupId>
    55             <artifactId>commons-io</artifactId>
    56             <version>1.4</version>
    57         </dependency>
    58         <dependency>
    59             <groupId>commons-lang</groupId>
    60             <artifactId>commons-lang</artifactId>
    61             <version>2.5</version>
    62         </dependency>
    63         <dependency>
    64             <groupId>commons-fileupload</groupId>
    65             <artifactId>commons-fileupload</artifactId>
    66             <version>1.2.1</version>
    67         </dependency>
    68         <dependency>
    69             <groupId>commons-collections</groupId>
    70             <artifactId>commons-collections</artifactId>
    71             <version>3.2.1</version>
    72         </dependency>
    73         <dependency>
    74             <groupId>xml-resolver</groupId>
    75             <artifactId>xml-resolver</artifactId>
    76             <version>1.2</version>
    77         </dependency>
    78         <dependency>
    79             <groupId>org.slf4j</groupId>
    80             <artifactId>slf4j-log4j12</artifactId>
    81             <version>1.7.2</version>
    82         </dependency>
    83         <dependency>
    84             <groupId>org.slf4j</groupId>
    85             <artifactId>jcl-over-slf4j</artifactId>
    86             <version>1.7.2</version>
    87         </dependency>
    88         <dependency>
    89             <groupId>com.sun.jersey.contribs</groupId>
    90             <artifactId>jersey-multipart</artifactId>
    91             <version>1.12</version>
    92         </dependency>
    93         <dependency>
    94             <groupId>com.sun.jersey</groupId>
    95             <artifactId>jersey-bundle</artifactId>
    96             <version>1.12</version>
    97             <exclusions>
    98                 <!--
    99     Jersey has dependencies with different group ids therefore maven cannot resolve the conflict and gives me both
    100     jars (two of stax and two of jaxb-impl). Excluding them manually to overcome the problem
    101   -->
    102                 <exclusion>
    103                     <groupId>stax</groupId>
    104                     <artifactId>stax-api</artifactId>
    105                 </exclusion>
    106             </exclusions>
    107         </dependency>
    108         <dependency>
    109             <groupId>com.sun.jersey.jersey-test-framework</groupId>
    110             <artifactId>jersey-test-framework-grizzly</artifactId>
    111             <version>1.12</version>
    112             <scope>test</scope>
    113         </dependency>
    114         <dependency>
    115             <groupId>com.sun.grizzly</groupId>
    116             <artifactId>grizzly-servlet-webserver</artifactId>
    117             <version>1.9.19</version>
    118             <scope>test</scope>
    119         </dependency>
    120         <dependency>
    121             <groupId>com.sun.xml.stream</groupId>
    122             <artifactId>sjsxp</artifactId>
    123             <version>1.0.1</version>
    124         </dependency>
    125         <dependency>
    126             <groupId>de.mpg.mpgaai</groupId>
    127             <artifactId>mpgaai-jaas</artifactId>
    128             <version>1.3.2</version>
    129             <exclusions>
    130                 <exclusion>
    131                     <groupId>commons-logging</groupId>
    132                     <artifactId>commons-logging</artifactId>
    133                 </exclusion>
    134             </exclusions>
    135         </dependency>
    136         <dependency>
    137             <groupId>de.mpg.mpgaai</groupId>
    138             <artifactId>mpgaai-shhaa</artifactId>
    139             <version>1.0.3</version>
    140             <exclusions>
    141                 <exclusion>
    142                     <groupId>commons-logging</groupId>
    143                     <artifactId>commons-logging</artifactId>
    144                 </exclusion>
    145             </exclusions>
    146         </dependency>
    147         <dependency>
    148             <groupId>org.apache.wicket</groupId>
    149             <artifactId>wicket</artifactId>
    150             <version>1.4.8</version>
    151         </dependency>
    152         <dependency>
    153             <groupId>org.apache.wicket</groupId>
    154             <artifactId>wicket-extensions</artifactId>
    155             <version>1.4.8</version>
    156         </dependency>
    157 
    158         <!-- Spring framework -->
    159 
    160         <dependency>
    161             <groupId>org.apache.wicket</groupId>
    162             <artifactId>wicket-spring</artifactId>
    163             <version>1.4.8</version>
    164             <exclusions>
    165                 <exclusion>
    166                     <groupId>org.springframework</groupId>
    167                     <artifactId>spring</artifactId>
    168                 </exclusion>
    169             </exclusions>
    170         </dependency>
    171         <dependency>
    172             <groupId>com.sun.jersey.contribs</groupId>
    173             <artifactId>jersey-spring</artifactId>
    174             <version>1.12</version>
    175             <exclusions>
    176                 <exclusion>
    177                     <groupId>commons-logging</groupId>
    178                     <artifactId>commons-logging</artifactId>
    179                 </exclusion>
    180             </exclusions>
    181         </dependency>
    182         <dependency>
    183             <groupId>org.springframework</groupId>
    184             <artifactId>spring-tx</artifactId>
    185             <version>3.0.0.RELEASE</version>
    186         </dependency>
    187         <dependency>
    188             <groupId>org.springframework</groupId>
    189             <artifactId>spring-jdbc</artifactId>
    190             <version>3.0.0.RELEASE</version>
    191         </dependency>
    192         <dependency>
    193             <groupId>org.springframework</groupId>
    194             <artifactId>spring-test</artifactId>
    195             <version>3.0.0.RELEASE</version>
    196             <scope>test</scope>
    197         </dependency>
    198 
    199         <!-- Database -->
    200 
    201         <dependency>
    202             <groupId>commons-dbcp</groupId>
    203             <artifactId>commons-dbcp</artifactId>
    204             <version>1.4</version>
    205         </dependency>
    206         <dependency>
    207             <groupId>postgresql</groupId>
    208             <artifactId>postgresql</artifactId>
    209             <version>8.4-701.jdbc3</version>
    210         </dependency>
    211         <dependency>
    212             <groupId>hsqldb</groupId>
    213             <artifactId>hsqldb</artifactId>
    214             <version>1.8.0.10</version>
    215             <scope>test</scope>
    216         </dependency>
    217         <dependency>
    218             <groupId>clarin.cmdi</groupId>
    219             <artifactId>cmd-validate</artifactId>
    220             <version>1.1</version>
    221         </dependency>
    222         <dependency>
    223             <groupId>org.slf4j</groupId>
    224             <artifactId>jul-to-slf4j</artifactId>
    225             <version>1.7.2</version>
    226         </dependency>
    227     </dependencies>
    228 
    229     <properties>
    230         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    231         <packaging>war</packaging>
    232         <!-- Properties to configure ComponentRegistry override on commandline with -D or change here -->
    233         <serviceRootUrl>http://localhost:8080/${project.artifactId}</serviceRootUrl>
    234         <!-- Will be inserted in context.xml -->
    235         <webXmlPath>src/main/webapp/WEB-INF/web-test.xml</webXmlPath>
    236         <!-- non-shib web.xml -->
    237         <isocatSearchUrl>http://www.isocat.org/rest/user/guest/search</isocatSearchUrl>
    238         <ComponentRegistrySwfName>${project.artifactId}-${ComponentBrowserGui.version}</ComponentRegistrySwfName>
    239         <flexDebug>0</flexDebug>
    240     </properties>
    241 
    242     <profiles>
    243         <profile>
    244             <id>lux16</id>
    245             <properties>
    246                 <serviceRootUrl>http://lux16.mpi.nl/ds/ComponentRegistry</serviceRootUrl>
     19
     20        <properties>
     21                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     22                <packaging>war</packaging>
     23                <!-- Properties to configure ComponentRegistry override on commandline
     24                        with -D or change here -->
     25                <serviceRootUrl>http://localhost:8080/${project.artifactId}</serviceRootUrl>
    24726                <!-- Will be inserted in context.xml -->
    248                 <shibLI>http://lux16.mpi.nl/Shibboleth.sso/DS</shibLI>
    249                 <!-- Shibboleth login URI for SHHAA -->
    250                 <shibLO>http://lux16.mpi.nl/Shibboleth.sso/Logout</shibLO>
    251                 <!-- Shibboleth logout URI for SHHAA -->
    252                 <webXmlPath>src/main/webapp/WEB-INF/web-shib.xml</webXmlPath>
    253                 <!-- web.xml for shibboleth authentication -->
    254             </properties>
    255         </profile>
    256         <profile>
    257             <id>clarin</id>
    258             <properties>
    259                 <serviceRootUrl>http://catalog.clarin.eu/ds/ComponentRegistry</serviceRootUrl>
    260                 <!-- Will be inserted in context.xml -->
    261                 <shibLI>https://catalog.clarin.eu/Shibboleth.sso/DiscoJuice</shibLI>
    262                 <!-- Shibboleth login URI for SHHAA -->
    263                 <shibLO>https://catalog.clarin.eu/Shibboleth.sso/Logout</shibLO>
    264                 <!-- Shibboleth logout URI for SHHAA -->
    265                 <webXmlPath>src/main/webapp/WEB-INF/web-shib.xml</webXmlPath>
    266                 <!-- web.xml for shibboleth authentication -->
    267             </properties>
    268         </profile>
    269     </profiles>
    270 
    271     <build>
    272         <filters>
    273             <filter>properties/flexindex.properties</filter>
    274         </filters>
    275         <resources>
    276             <resource>
    277                 <filtering>false</filtering>
    278                 <directory>src/generated/jaxb/components</directory>
    279             </resource>
    280             <resource>
    281                 <filtering>false</filtering>
    282                 <directory>src/generated/jaxb/rss</directory>
    283             </resource>
    284             <resource>
    285                 <filtering>true</filtering>
    286                 <directory>src/main/resources</directory>
    287             </resource>
    288             <resource>
    289                 <filtering>false</filtering>
    290                 <directory>src/main/java</directory>
    291                 <includes>
    292                     <include>**/*.html</include>
    293                 </includes>
    294             </resource>
    295         </resources>
    296         <testResources>
    297             <testResource>
    298                 <directory>src/test/resources</directory>
    299             </testResource>
    300         </testResources>
    301         <plugins>
    302             <plugin>
    303                 <groupId>org.apache.maven.plugins</groupId>
    304                 <artifactId>maven-compiler-plugin</artifactId>
    305                 <configuration>
    306                     <source>1.6</source>
    307                     <target>1.6</target>
    308                 </configuration>
    309             </plugin>
    310             <plugin>
    311                 <groupId>org.apache.maven.plugins</groupId>
    312                 <artifactId>maven-war-plugin</artifactId>
    313                 <configuration>
    314                     <warName>${project.artifactId}</warName>
    315                     <webXml>${webXmlPath}</webXml>
    316                     <webResources>
     27                <webXmlPath>src/main/webapp/WEB-INF/web-test.xml</webXmlPath>
     28                <!-- non-shib web.xml -->
     29                <isocatSearchUrl>http://www.isocat.org/rest/user/guest/search</isocatSearchUrl>
     30                <ComponentRegistrySwfName>${project.artifactId}-${ComponentBrowserGui.version}</ComponentRegistrySwfName>
     31                <flexDebug>0</flexDebug>
     32                <spring-data-jpa.version>1.3.4.RELEASE</spring-data-jpa.version>
     33                <spring.version>3.1.4.RELEASE</spring.version>
     34                <jackson.version>1.9.13</jackson.version>
     35                <jersey.version>1.17.1</jersey.version>
     36                <hibernate.version>4.2.4.Final</hibernate.version>
     37                <spring-data-jpa.version>1.3.4.RELEASE</spring-data-jpa.version>
     38        </properties>
     39
     40
     41        <ciManagement>
     42                <system>hudson</system>
     43                <url>http://lux16.mpi.nl/jenkins/job/ComponentRegistry/</url>
     44        </ciManagement>
     45        <scm>
     46                <connection>scm:svn:http://svn.clarin.eu/ComponentRegistry/trunk/ComponentRegistry</connection>
     47                <developerConnection>scm:svn:http://svn.clarin.eu/ComponentRegistry/trunk/ComponentRegistry</developerConnection>
     48                <url>http://trac.clarin.eu/browser/ComponentRegistry</url>
     49        </scm>
     50
     51
     52
     53        <dependencies>
     54                <dependency>
     55                        <groupId>org.springframework.data</groupId>
     56                        <artifactId>spring-data-jpa</artifactId>
     57                        <version>${spring-data-jpa.version}</version>
     58                </dependency>
     59                <dependency>
     60                        <groupId>org.hibernate</groupId>
     61                        <artifactId>hibernate-entitymanager</artifactId>
     62                        <version>${hibernate.version}</version>
     63                </dependency>
     64                <dependency>
     65                        <groupId>junit</groupId>
     66                        <artifactId>junit</artifactId>
     67                        <version>4.11</version>
     68                        <scope>test</scope>
     69                </dependency>
     70                <dependency>
     71                        <groupId>net.sf.saxon</groupId>
     72                        <artifactId>Saxon-HE</artifactId>
     73                        <version>9.4</version>
     74                </dependency>
     75                <dependency>
     76                        <groupId>javax.servlet</groupId>
     77                        <artifactId>servlet-api</artifactId>
     78                        <version>2.5</version>
     79                        <scope>provided</scope>
     80                </dependency>
     81                <dependency>
     82                        <groupId>commons-codec</groupId>
     83                        <artifactId>commons-codec</artifactId>
     84                        <version>1.3</version>
     85                </dependency>
     86                <dependency>
     87                        <groupId>commons-io</groupId>
     88                        <artifactId>commons-io</artifactId>
     89                        <version>1.4</version>
     90                </dependency>
     91                <dependency>
     92                        <groupId>commons-lang</groupId>
     93                        <artifactId>commons-lang</artifactId>
     94                        <version>2.5</version>
     95                </dependency>
     96                <dependency>
     97                        <groupId>commons-fileupload</groupId>
     98                        <artifactId>commons-fileupload</artifactId>
     99                        <version>1.2.1</version>
     100                </dependency>
     101                <dependency>
     102                        <groupId>commons-collections</groupId>
     103                        <artifactId>commons-collections</artifactId>
     104                        <version>3.2.1</version>
     105                </dependency>
     106                <dependency>
     107                        <groupId>xml-resolver</groupId>
     108                        <artifactId>xml-resolver</artifactId>
     109                        <version>1.2</version>
     110                </dependency>
     111                <dependency>
     112                        <groupId>org.slf4j</groupId>
     113                        <artifactId>slf4j-log4j12</artifactId>
     114                        <version>1.7.2</version>
     115                </dependency>
     116                <dependency>
     117                        <groupId>org.slf4j</groupId>
     118                        <artifactId>jcl-over-slf4j</artifactId>
     119                        <version>1.7.2</version>
     120                </dependency>
     121                <dependency>
     122                        <groupId>com.sun.jersey.contribs</groupId>
     123                        <artifactId>jersey-multipart</artifactId>
     124                        <version>${jersey.version}</version>
     125                </dependency>
     126                <dependency>
     127                        <groupId>org.codehaus.jackson</groupId>
     128                        <artifactId>jackson-core-asl</artifactId>
     129                        <version>${jackson.version}</version>
     130                </dependency>
     131                <dependency>
     132                        <groupId>com.sun.jersey</groupId>
     133                        <artifactId>jersey-bundle</artifactId>
     134                        <version>${jersey.version}</version>
     135                        <exclusions>
     136                                <!-- Jersey has dependencies with different group ids therefore maven
     137                                        cannot resolve the conflict and gives me both jars (two of stax and two of
     138                                        jaxb-impl). Excluding them manually to overcome the problem -->
     139                                <exclusion>
     140                                        <groupId>stax</groupId>
     141                                        <artifactId>stax-api</artifactId>
     142                                </exclusion>
     143                        </exclusions>
     144                </dependency>
     145                <dependency>
     146                        <groupId>com.sun.jersey.jersey-test-framework</groupId>
     147                        <artifactId>jersey-test-framework-grizzly</artifactId>
     148                        <version>${jersey.version}</version>
     149                        <scope>test</scope>
     150                </dependency>
     151                <dependency>
     152                        <groupId>com.sun.grizzly</groupId>
     153                        <artifactId>grizzly-servlet-webserver</artifactId>
     154                        <version>1.9.19</version>
     155                        <scope>test</scope>
     156                </dependency>
     157                <dependency>
     158                        <groupId>com.sun.xml.stream</groupId>
     159                        <artifactId>sjsxp</artifactId>
     160                        <version>1.0.1</version>
     161                </dependency>
     162                <dependency>
     163                        <groupId>de.mpg.mpgaai</groupId>
     164                        <artifactId>mpgaai-jaas</artifactId>
     165                        <version>1.3.2</version>
     166                        <exclusions>
     167                                <exclusion>
     168                                        <groupId>commons-logging</groupId>
     169                                        <artifactId>commons-logging</artifactId>
     170                                </exclusion>
     171                        </exclusions>
     172                </dependency>
     173                <dependency>
     174                        <groupId>de.mpg.mpgaai</groupId>
     175                        <artifactId>mpgaai-shhaa</artifactId>
     176                        <version>1.0.3</version>
     177                        <exclusions>
     178                                <exclusion>
     179                                        <groupId>commons-logging</groupId>
     180                                        <artifactId>commons-logging</artifactId>
     181                                </exclusion>
     182                        </exclusions>
     183                </dependency>
     184                <dependency>
     185                        <groupId>org.apache.wicket</groupId>
     186                        <artifactId>wicket</artifactId>
     187                        <version>1.4.8</version>
     188                </dependency>
     189                <dependency>
     190                        <groupId>org.apache.wicket</groupId>
     191                        <artifactId>wicket-extensions</artifactId>
     192                        <version>1.4.8</version>
     193                </dependency>
     194                <dependency>
     195                        <groupId>javax.servlet</groupId>
     196                        <artifactId>jsp-api</artifactId>
     197                        <version>2.0</version>
     198                        <scope>provided</scope>
     199                </dependency>
     200
     201                <!-- Spring framework -->
     202
     203                <dependency>
     204                        <groupId>org.springframework</groupId>
     205                        <artifactId>spring-webmvc</artifactId>
     206                        <version>${spring.version}</version>
     207                </dependency>
     208                <dependency>
     209                        <groupId>org.springframework</groupId>
     210                        <artifactId>spring-test</artifactId>
     211                        <version>${spring.version}</version>
     212                        <scope>test</scope>
     213                </dependency>
     214                <dependency>
     215                        <groupId>org.springframework</groupId>
     216                        <artifactId>spring-context</artifactId>
     217                        <version>${spring.version}</version>
     218                </dependency>
     219                <dependency>
     220                        <groupId>org.springframework.data</groupId>
     221                        <artifactId>spring-data-jpa</artifactId>
     222                        <version>${spring-data-jpa.version}</version>
     223                        <exclusions>
     224                                <exclusion>
     225                                        <artifactId>spring-aop</artifactId>
     226                                        <groupId>org.springframework</groupId>
     227                                </exclusion>
     228                                <exclusion>
     229                                        <artifactId>spring-core</artifactId>
     230                                        <groupId>org.springframework</groupId>
     231                                </exclusion>
     232                                <exclusion>
     233                                        <artifactId>spring-context</artifactId>
     234                                        <groupId>org.springframework</groupId>
     235                                </exclusion>
     236                                <exclusion>
     237                                        <artifactId>spring-beans</artifactId>
     238                                        <groupId>org.springframework</groupId>
     239                                </exclusion>
     240                        </exclusions>
     241                </dependency>
     242                <dependency>
     243                        <groupId>org.springframework</groupId>
     244                        <artifactId>spring-core</artifactId>
     245                        <version>${spring.version}</version>
     246                </dependency>
     247                <dependency>
     248                        <groupId>org.apache.wicket</groupId>
     249                        <artifactId>wicket-spring</artifactId>
     250                        <version>1.4.8</version>
     251                        <exclusions>
     252                                <exclusion>
     253                                        <groupId>org.springframework</groupId>
     254                                        <artifactId>spring</artifactId>
     255                                </exclusion>
     256                        </exclusions>
     257                </dependency>
     258                <dependency>
     259                        <groupId>com.sun.jersey.contribs</groupId>
     260                        <artifactId>jersey-spring</artifactId>
     261                        <version>${jersey.version}</version>
     262                        <exclusions>
     263                                <exclusion>
     264                                        <groupId>commons-logging</groupId>
     265                                        <artifactId>commons-logging</artifactId>
     266                                </exclusion>
     267                                <exclusion>
     268                                        <artifactId>spring-core</artifactId>
     269                                        <groupId>org.springframework</groupId>
     270                                </exclusion>
     271                                <exclusion>
     272                                        <artifactId>spring-aop</artifactId>
     273                                        <groupId>org.springframework</groupId>
     274                                </exclusion>
     275                                <exclusion>
     276                                        <artifactId>spring-context</artifactId>
     277                                        <groupId>org.springframework</groupId>
     278                                </exclusion>
     279                                <exclusion>
     280                                        <artifactId>spring-web</artifactId>
     281                                        <groupId>org.springframework</groupId>
     282                                </exclusion>
     283                                <exclusion>
     284                                        <artifactId>spring-beans</artifactId>
     285                                        <groupId>org.springframework</groupId>
     286                                </exclusion>
     287                        </exclusions>
     288                </dependency>
     289
     290                <!-- Database -->
     291
     292                <dependency>
     293                        <groupId>commons-dbcp</groupId>
     294                        <artifactId>commons-dbcp</artifactId>
     295                        <version>1.4</version>
     296                </dependency>
     297                <dependency>
     298                        <groupId>postgresql</groupId>
     299                        <artifactId>postgresql</artifactId>
     300                        <version>8.4-701.jdbc3</version>
     301                </dependency>
     302                <dependency>
     303                        <groupId>hsqldb</groupId>
     304                        <artifactId>hsqldb</artifactId>
     305                        <version>1.8.0.10</version>
     306                        <scope>test</scope>
     307                </dependency>
     308                <dependency>
     309                        <groupId>clarin.cmdi</groupId>
     310                        <artifactId>cmd-validate</artifactId>
     311                        <version>1.1</version>
     312                </dependency>
     313                <dependency>
     314                        <groupId>org.slf4j</groupId>
     315                        <artifactId>jul-to-slf4j</artifactId>
     316                        <version>1.7.2</version>
     317                </dependency>
     318        </dependencies>
     319
     320
     321        <profiles>
     322                <profile>
     323                        <id>lux16</id>
     324                        <properties>
     325                                <serviceRootUrl>http://lux16.mpi.nl/ds/ComponentRegistry</serviceRootUrl>
     326                                <!-- Will be inserted in context.xml -->
     327                                <shibLI>http://lux16.mpi.nl/Shibboleth.sso/DS</shibLI>
     328                                <!-- Shibboleth login URI for SHHAA -->
     329                                <shibLO>http://lux16.mpi.nl/Shibboleth.sso/Logout</shibLO>
     330                                <!-- Shibboleth logout URI for SHHAA -->
     331                                <webXmlPath>src/main/webapp/WEB-INF/web-shib.xml</webXmlPath>
     332                                <!-- web.xml for shibboleth authentication -->
     333                        </properties>
     334                </profile>
     335                <profile>
     336                        <id>clarin</id>
     337                        <properties>
     338                                <serviceRootUrl>http://catalog.clarin.eu/ds/ComponentRegistry</serviceRootUrl>
     339                                <!-- Will be inserted in context.xml -->
     340                                <shibLI>https://catalog.clarin.eu/Shibboleth.sso/DiscoJuice</shibLI>
     341                                <!-- Shibboleth login URI for SHHAA -->
     342                                <shibLO>https://catalog.clarin.eu/Shibboleth.sso/Logout</shibLO>
     343                                <!-- Shibboleth logout URI for SHHAA -->
     344                                <webXmlPath>src/main/webapp/WEB-INF/web-shib.xml</webXmlPath>
     345                                <!-- web.xml for shibboleth authentication -->
     346                        </properties>
     347                </profile>
     348        </profiles>
     349
     350        <build>
     351                <filters>
     352                        <filter>properties/flexindex.properties</filter>
     353                </filters>
     354                <resources>
    317355                        <resource>
    318                             <directory>src/main/webapp</directory>
    319                             <filtering>true</filtering>
     356                                <filtering>false</filtering>
     357                                <directory>src/generated/jaxb/components</directory>
    320358                        </resource>
    321                     </webResources>
    322                     <archive>
    323                         <manifest>
    324                             <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
    325                         </manifest>
    326                     </archive>
    327                 </configuration>
    328             </plugin>
    329             <plugin>
    330                 <groupId>org.jvnet.jaxb2.maven2</groupId>
    331                 <artifactId>maven-jaxb2-plugin</artifactId>
    332                 <executions>
    333                     <execution>
    334                         <id>jaxb-components</id>
    335                         <goals>
    336                             <goal>generate</goal>
    337                         </goals>
    338                         <configuration>
    339                             <schemaDirectory>src/main/binding/components</schemaDirectory>
    340                             <schemaIncludes>
    341                                 <include>general-component-schema.xsd</include>
    342                             </schemaIncludes>
    343                             <bindingDirectory>src/main/binding/components</bindingDirectory>
    344                             <extension>true</extension>
    345                             <generateDirectory>${basedir}/src/generated/jaxb/components</generateDirectory>
    346                             <generatePackage>clarin.cmdi.componentregistry.components</generatePackage>
    347                             <catalog>src/main/resources/catalog.cat</catalog>
    348                             <catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
    349                         </configuration>
    350                     </execution>
    351                     <execution>
    352                         <id>jaxb-rrs</id>
    353                         <goals>
    354                             <goal>generate</goal>
    355                         </goals>
    356                         <configuration>
    357                             <schemaDirectory>src/main/binding/rss</schemaDirectory>
    358                             <schemaIncludes>
    359                                 <include>rss-2_0.xsd</include>
    360                             </schemaIncludes>
    361                             <bindingDirectory>src/main/binding/rss</bindingDirectory>
    362                             <extension>true</extension>
    363                             <generateDirectory>${basedir}/src/generated/jaxb/rss</generateDirectory>
    364                             <generatePackage>clarin.cmdi.componentregistry.rss</generatePackage>
    365                             <catalog>src/main/resources/catalog.cat</catalog>
    366                             <catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
    367                         </configuration>
    368                     </execution>
    369                 </executions>
    370             </plugin>
    371             <plugin>
    372                 <groupId>org.apache.maven.plugins</groupId>
    373                 <artifactId>maven-dependency-plugin</artifactId>
    374                 <executions>
    375                     <execution>
    376                         <id>copy</id>
    377                         <phase>process-resources</phase>
    378                         <goals>
    379                             <goal>copy</goal>
    380                         </goals>
    381                         <configuration>
    382                             <artifactItems>
    383                                 <artifactItem>
    384                                     <groupId>clarin.cmdi</groupId>
    385                                     <artifactId>ComponentBrowserGui</artifactId>
    386                                     <version>${ComponentBrowserGui.version}</version>
    387                                     <type>swf</type>
    388                                     <overWrite>true</overWrite>
    389                                     <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}</outputDirectory>
    390                                     <destFileName>${ComponentRegistrySwfName}.swf</destFileName>
    391                                 </artifactItem>
    392                             </artifactItems>
    393                         </configuration>
    394                     </execution>
    395                 </executions>
    396             </plugin>
    397             <plugin>
    398                 <artifactId>maven-assembly-plugin</artifactId>
    399                 <version>2.2.2</version>
    400                 <executions>
    401                     <execution>
    402                         <id>make-assembly</id>
    403                         <phase>package</phase>
    404                         <goals>
    405                             <goal>single</goal>
    406                         </goals>
    407                         <configuration>
    408                             <descriptors>
    409                                 <descriptor>src/main/assembly/release.xml</descriptor>
    410                             </descriptors>
    411                         </configuration>
    412                     </execution>
    413                 </executions>
    414             </plugin>
    415             <plugin>
    416                 <groupId>org.apache.maven.plugins</groupId>
    417                 <artifactId>maven-surefire-plugin</artifactId>
    418                 <version>2.13</version>
    419                 <configuration>
    420                     <systemProperties>
    421                         <property>
    422                             <name>java.util.logging.config.file</name>
    423                             <value>${project.build.directory}/classes/logging.properties</value>
    424                         </property>
    425                     </systemProperties>
    426                 </configuration>
    427             </plugin>
    428 
    429         </plugins>
    430     </build>
    431    
    432     <reporting>
    433         <plugins>
    434             <plugin>
    435                 <groupId>org.codehaus.mojo</groupId>
    436                 <artifactId>findbugs-maven-plugin</artifactId>
    437                 <configuration>
    438                     <excludeFilterFile>${basedir}/src/main/resources/findbugs-exclude.xml</excludeFilterFile>
    439                     <threshold>Normal</threshold>
    440                     <effort>Min</effort>
    441                 </configuration>
    442             </plugin>
    443         </plugins>
    444     </reporting> 
    445    
    446     <repositories>
    447         <repository>
    448             <id>cmdi.clarin.repository</id>
    449             <name>Clarin Repository</name>
    450             <url>http://catalog.clarin.eu/ds/nexus/content/groups/public/</url>
    451         </repository>
    452         <repository>
    453             <id>sonatype</id>
    454             <url>https://oss.sonatype.org/content/groups/public</url>
    455         </repository>
    456     </repositories>
     359                        <resource>
     360                                <filtering>false</filtering>
     361                                <directory>src/generated/jaxb/rss</directory>
     362                        </resource>
     363                        <resource>
     364                                <filtering>true</filtering>
     365                                <directory>src/main/resources</directory>
     366                        </resource>
     367                        <resource>
     368                                <filtering>false</filtering>
     369                                <directory>src/main/java</directory>
     370                                <includes>
     371                                        <include>**/*.html</include>
     372                                </includes>
     373                        </resource>
     374                </resources>
     375                <testResources>
     376                        <testResource>
     377                                <directory>src/test/resources</directory>
     378                        </testResource>
     379                </testResources>
     380                <plugins>
     381                        <plugin>
     382                                <groupId>org.apache.maven.plugins</groupId>
     383                                <artifactId>maven-compiler-plugin</artifactId>
     384                                <configuration>
     385                                        <source>1.6</source>
     386                                        <target>1.6</target>
     387                                </configuration>
     388                        </plugin>
     389                        <plugin>
     390                                <groupId>org.apache.maven.plugins</groupId>
     391                                <artifactId>maven-war-plugin</artifactId>
     392                                <configuration>
     393                                        <warName>${project.artifactId}</warName>
     394                                        <webXml>${webXmlPath}</webXml>
     395                                        <webResources>
     396                                                <resource>
     397                                                        <directory>src/main/webapp</directory>
     398                                                        <filtering>true</filtering>
     399                                                </resource>
     400                                        </webResources>
     401                                        <archive>
     402                                                <manifest>
     403                                                        <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
     404                                                </manifest>
     405                                        </archive>
     406                                </configuration>
     407                        </plugin>
     408                        <plugin>
     409                                <groupId>org.jvnet.jaxb2.maven2</groupId>
     410                                <artifactId>maven-jaxb2-plugin</artifactId>
     411                                <executions>
     412                                        <execution>
     413                                                <id>jaxb-components</id>
     414                                                <goals>
     415                                                        <goal>generate</goal>
     416                                                </goals>
     417                                                <configuration>
     418                                                        <schemaDirectory>src/main/binding/components</schemaDirectory>
     419                                                        <schemaIncludes>
     420                                                                <include>general-component-schema.xsd</include>
     421                                                        </schemaIncludes>
     422                                                        <bindingDirectory>src/main/binding/components</bindingDirectory>
     423                                                        <extension>true</extension>
     424                                                        <generateDirectory>${basedir}/src/generated/jaxb/components</generateDirectory>
     425                                                        <generatePackage>clarin.cmdi.componentregistry.components</generatePackage>
     426                                                        <catalog>src/main/resources/catalog.cat</catalog>
     427                                                        <catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
     428                                                </configuration>
     429                                        </execution>
     430                                        <execution>
     431                                                <id>jaxb-rrs</id>
     432                                                <goals>
     433                                                        <goal>generate</goal>
     434                                                </goals>
     435                                                <configuration>
     436                                                        <schemaDirectory>src/main/binding/rss</schemaDirectory>
     437                                                        <schemaIncludes>
     438                                                                <include>rss-2_0.xsd</include>
     439                                                        </schemaIncludes>
     440                                                        <bindingDirectory>src/main/binding/rss</bindingDirectory>
     441                                                        <extension>true</extension>
     442                                                        <generateDirectory>${basedir}/src/generated/jaxb/rss</generateDirectory>
     443                                                        <generatePackage>clarin.cmdi.componentregistry.rss</generatePackage>
     444                                                        <catalog>src/main/resources/catalog.cat</catalog>
     445                                                        <catalogResolver>org.jvnet.jaxb2.maven2.resolver.tools.ClasspathCatalogResolver</catalogResolver>
     446                                                </configuration>
     447                                        </execution>
     448                                </executions>
     449                        </plugin>
     450                        <plugin>
     451                                <groupId>org.apache.maven.plugins</groupId>
     452                                <artifactId>maven-dependency-plugin</artifactId>
     453                                <executions>
     454                                        <execution>
     455                                                <id>copy</id>
     456                                                <phase>process-resources</phase>
     457                                                <goals>
     458                                                        <goal>copy</goal>
     459                                                </goals>
     460                                                <configuration>
     461                                                        <artifactItems>
     462                                                                <artifactItem>
     463                                                                        <groupId>clarin.cmdi</groupId>
     464                                                                        <artifactId>ComponentBrowserGui</artifactId>
     465                                                                        <version>${ComponentBrowserGui.version}</version>
     466                                                                        <type>swf</type>
     467                                                                        <overWrite>true</overWrite>
     468                                                                        <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}</outputDirectory>
     469                                                                        <destFileName>${ComponentRegistrySwfName}.swf</destFileName>
     470                                                                </artifactItem>
     471                                                        </artifactItems>
     472                                                </configuration>
     473                                        </execution>
     474                                </executions>
     475                        </plugin>
     476                        <plugin>
     477                                <artifactId>maven-assembly-plugin</artifactId>
     478                                <version>2.2.2</version>
     479                                <executions>
     480                                        <execution>
     481                                                <id>make-assembly</id>
     482                                                <phase>package</phase>
     483                                                <goals>
     484                                                        <goal>single</goal>
     485                                                </goals>
     486                                                <configuration>
     487                                                        <descriptors>
     488                                                                <descriptor>src/main/assembly/release.xml</descriptor>
     489                                                        </descriptors>
     490                                                </configuration>
     491                                        </execution>
     492                                </executions>
     493                        </plugin>
     494                        <plugin>
     495                                <groupId>org.apache.maven.plugins</groupId>
     496                                <artifactId>maven-surefire-plugin</artifactId>
     497                                <version>2.13</version>
     498                                <configuration>
     499                                        <systemProperties>
     500                                                <property>
     501                                                        <name>java.util.logging.config.file</name>
     502                                                        <value>${project.build.directory}/classes/logging.properties</value>
     503                                                </property>
     504                                        </systemProperties>
     505                                        <additionalClasspathElements>
     506                                                <additionalClasspathElement>src/test/resources</additionalClasspathElement>
     507                                        </additionalClasspathElements>
     508                                </configuration>
     509                        </plugin>
     510
     511                </plugins>
     512        </build>
     513
     514        <reporting>
     515                <plugins>
     516                        <plugin>
     517                                <groupId>org.codehaus.mojo</groupId>
     518                                <artifactId>findbugs-maven-plugin</artifactId>
     519                                <configuration>
     520                                        <excludeFilterFile>${basedir}/src/main/resources/findbugs-exclude.xml</excludeFilterFile>
     521                                        <threshold>Normal</threshold>
     522                                        <effort>Min</effort>
     523                                </configuration>
     524                        </plugin>
     525                </plugins>
     526        </reporting>
     527
     528        <repositories>
     529                <repository>
     530                        <id>cmdi.clarin.repository</id>
     531                        <name>Clarin Repository</name>
     532                        <url>http://catalog.clarin.eu/ds/nexus/content/groups/public/</url>
     533                </repository>
     534                <repository>
     535                        <id>sonatype</id>
     536                        <url>https://oss.sonatype.org/content/groups/public</url>
     537                </repository>
     538        </repositories>
    457539</project>
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/AdminHomePage.java

    r3088 r3449  
    3333import clarin.cmdi.componentregistry.impl.database.AdminRegistry;
    3434import clarin.cmdi.componentregistry.impl.database.ComponentDescriptionDao;
     35import clarin.cmdi.componentregistry.impl.database.IComponentDescriptionDao;
     36import clarin.cmdi.componentregistry.impl.database.IProfileDescriptionDAO;
    3537import clarin.cmdi.componentregistry.impl.database.ProfileDescriptionDao;
    3638import clarin.cmdi.componentregistry.model.AbstractDescription;
     
    4951    private ComponentRegistryFactory componentRegistryFactory;
    5052    @SpringBean
    51     private ProfileDescriptionDao profileDescriptionDao;
     53    private IProfileDescriptionDAO profileDescriptionDao;
    5254    @SpringBean
    53     private ComponentDescriptionDao componentDescriptionDao;
     55    private IComponentDescriptionDao componentDescriptionDao;
    5456    @SpringBean
    5557    private MDMarshaller marshaller;
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/frontend/UserSettingsPage.java

    r1863 r3449  
    77import clarin.cmdi.componentregistry.ComponentRegistryFactory;
    88import clarin.cmdi.componentregistry.UserCredentials;
    9 import clarin.cmdi.componentregistry.impl.database.UserDao;
     9import clarin.cmdi.componentregistry.impl.database.IUserDAO;
    1010import clarin.cmdi.componentregistry.model.RegistryUser;
     11
    1112import java.security.Principal;
     13
    1214import org.apache.wicket.PageParameters;
    1315import org.apache.wicket.RequestCycle;
     
    3032
    3133    @SpringBean
    32     private UserDao userDao;
     34    private IUserDAO userDao;
    3335    @SpringBean(name = "componentRegistryFactory")
    3436    private ComponentRegistryFactory componentRegistryFactory;
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDao.java

    r1702 r3449  
    1313import org.slf4j.Logger;
    1414import org.slf4j.LoggerFactory;
    15 import org.springframework.beans.factory.annotation.Autowired;
    1615import org.springframework.dao.DataAccessException;
    1716import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
    1817import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
    1918import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
    20 import org.springframework.transaction.PlatformTransactionManager;
    21 import org.springframework.transaction.TransactionDefinition;
    22 import org.springframework.transaction.TransactionStatus;
    2319
    2420import clarin.cmdi.componentregistry.model.AbstractDescription;
     21import clarin.cmdi.componentregistry.model.ComponentDescription;
     22import clarin.cmdi.componentregistry.model.ProfileDescription;
     23
    2524import java.util.Arrays;
    2625import java.util.Collection;
     26
    2727import org.apache.commons.collections.ListUtils;
    2828
    2929/**
    30  *
     30 * Base DAO which can be extended to serve {@link ComponentDescription}s and {@link ProfileDescription}s
    3131 * @author Twan Goosen <twan.goosen@mpi.nl>
     32 * @author George.Georgovassilis@mpi.nl
    3233 */
    33 public abstract class AbstractDescriptionDao<T extends AbstractDescription> extends ComponentRegistryDao<T> {
    34 
    35     private final static Logger LOG = LoggerFactory.getLogger(AbstractDescriptionDao.class);
    36     @Autowired
    37     private PlatformTransactionManager txManager;
    38     @Autowired
    39     private TransactionDefinition txDefinition;
     34public abstract class AbstractDescriptionDao<T extends AbstractDescription>
     35        extends ComponentRegistryDao<T> implements IAbstractDescriptionDao<T> {
     36
     37    private final static Logger LOG = LoggerFactory
     38            .getLogger(AbstractDescriptionDao.class);
    4039
    4140    protected abstract String getTableName();
     
    4443
    4544    protected abstract String getCommentsForeignKeyColumn();
     45
    4646    /**
    4747     * Class object required to instantiate new description domain objects
     
    5959     * @return Whether the specified item is in the public space
    6060     */
     61    @Override
    6162    public boolean isPublic(String cmdId) {
    6263        StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM ");
    6364        query.append(getTableName());
    64         query.append(" WHERE is_public = true AND ").append(getCMDIdColumn()).append(" = ?");
    65         return (0 < getSimpleJdbcTemplate().queryForInt(query.toString(), cmdId));
     65        query.append(" WHERE is_public = true AND ").append(getCMDIdColumn())
     66                .append(" = ?");
     67        return (0 < getJdbcTemplate().queryForInt(query.toString(), cmdId));
    6668    }
    6769
     
    7476     * @return Whether the specified item is in the specified user's workspace
    7577     */
     78    @Override
    7679    public boolean isInUserSpace(String cmdId, Number userId) {
    7780        StringBuilder query = new StringBuilder("SELECT COUNT(*) FROM ");
    7881        query.append(getTableName());
    79         query.append(" WHERE is_public = false AND user_id = ? AND ").append(getCMDIdColumn()).append(" = ?");
    80         return (0 < getSimpleJdbcTemplate().queryForInt(query.toString(), userId, cmdId));
     82        query.append(" WHERE is_public = false AND user_id = ? AND ")
     83                .append(getCMDIdColumn()).append(" = ?");
     84        return (0 < getJdbcTemplate().queryForInt(query.toString(), userId,
     85                cmdId));
    8186    }
    8287
     
    8792     * @param userId
    8893     *            User db id of workspace owner, null for public registry
    89      * @return Whether the specified item is in the specified workspace (user or public)
    90      */
     94     * @return Whether the specified item is in the specified workspace (user or
     95     *         public)
     96     */
     97    @Override
    9198    public boolean isInRegistry(String cmdId, Number userId) {
    9299        if (userId == null) {
     
    103110     * @return String value of XML content for profile or component
    104111     */
    105     public String getContent(boolean isDeleted, String cmdId) throws DataAccessException {
    106         String select = "SELECT content FROM " + TABLE_XML_CONTENT + " JOIN " + getTableName() + " ON " + TABLE_XML_CONTENT + "."
    107                 + COLUMN_ID + " = " + getTableName() + ".content_id" + " WHERE is_deleted = ? AND " + getTableName() + "."
     112    @Override
     113    public String getContent(boolean isDeleted, String cmdId)
     114            throws DataAccessException {
     115        String select = "SELECT content FROM " + TABLE_XML_CONTENT + " JOIN "
     116                + getTableName() + " ON " + TABLE_XML_CONTENT + "." + COLUMN_ID
     117                + " = " + getTableName() + ".content_id"
     118                + " WHERE is_deleted = ? AND " + getTableName() + "."
    108119                + getCMDIdColumn() + " = ?";
    109120
    110         List<String> result = getSimpleJdbcTemplate().query(select, new ParameterizedSingleColumnRowMapper<String>(), isDeleted, cmdId);
     121        List<String> result = getJdbcTemplate().query(select,
     122                new ParameterizedSingleColumnRowMapper<String>(), isDeleted,
     123                cmdId);
    111124        if (result.size() > 0) {
    112125            return result.get(0);
     
    123136     * @return Id of newly inserted description
    124137     */
    125     public Number insertDescription(AbstractDescription description, String content, boolean isPublic, Number userId)
     138    @Override
     139    public Number insertDescription(AbstractDescription description,
     140            String content, boolean isPublic, Number userId)
    126141            throws DataAccessException {
    127142
    128         TransactionStatus transaction = getTransaction();
    129         try {
    130             SimpleJdbcInsert insert = new SimpleJdbcInsert(getDataSource()).withTableName(TABLE_XML_CONTENT).usingGeneratedKeyColumns(
    131                     COLUMN_ID);
    132             Number contentId = insert.executeAndReturnKey(Collections.singletonMap("content", (Object) content));
    133 
    134             SimpleJdbcInsert insertDescription = new SimpleJdbcInsert(getDataSource()).withTableName(getTableName()).usingGeneratedKeyColumns(COLUMN_ID);
    135             Map<String, Object> params = new HashMap<String, Object>();
    136             putInsertParameters(params, description, contentId, userId, isPublic);
    137 
    138             Number id = insertDescription.executeAndReturnKey(params);
    139             txManager.commit(transaction);
    140             return id;
    141         } catch (DataAccessException ex) {
    142             txManager.rollback(transaction);
    143             throw ex;
    144         }
     143        SimpleJdbcInsert insert = new SimpleJdbcInsert(getJdbcTemplate())
     144                .withTableName(TABLE_XML_CONTENT).usingGeneratedKeyColumns(
     145                        COLUMN_ID);
     146        Number contentId = insert.executeAndReturnKey(Collections.singletonMap(
     147                "content", (Object) content));
     148
     149        SimpleJdbcInsert insertDescription = new SimpleJdbcInsert(
     150                getJdbcTemplate()).withTableName(getTableName())
     151                .usingGeneratedKeyColumns(COLUMN_ID);
     152        Map<String, Object> params = new HashMap<String, Object>();
     153        putInsertParameters(params, description, contentId, userId, isPublic);
     154
     155        Number id = insertDescription.executeAndReturnKey(params);
     156        return id;
    145157    }
    146158
     
    148160        if (description.getRegistrationDate() != null) {
    149161            try {
    150                 Date date = AbstractDescription.getDate(description.getRegistrationDate());
     162                Date date = AbstractDescription.getDate(description
     163                        .getRegistrationDate());
    151164                return new Timestamp(date.getTime());
    152165            } catch (ParseException ex) {
    153                 LOG.warn("Could not convert registration date " + description.getRegistrationDate() + " to date", ex);
     166                LOG.warn(
     167                        "Could not convert registration date "
     168                                + description.getRegistrationDate()
     169                                + " to date", ex);
    154170            } catch (IllegalArgumentException ex) {
    155                 LOG.warn("Could not convert registration date " + description.getRegistrationDate() + " to timestamp", ex);
     171                LOG.warn(
     172                        "Could not convert registration date "
     173                                + description.getRegistrationDate()
     174                                + " to timestamp", ex);
    156175            }
    157176        }
     
    169188     *            New content for description (leave null to not change)
    170189     */
    171     public void updateDescription(Number id, AbstractDescription description, String content) {
    172         TransactionStatus transaction = getTransaction();
    173         try {
    174             if (description != null) {
    175                 // Update description
    176                 StringBuilder updateDescription = new StringBuilder();
    177                 updateDescription.append("UPDATE ").append(getTableName());
    178                 appendUpdateColumnsStatement(updateDescription);
    179                 updateDescription.append(" WHERE " + COLUMN_ID + " = ?");
    180                 Collection updateParams = ListUtils.union(getUpdateParameterValues(description), Collections.singletonList(id));
    181                 getSimpleJdbcTemplate().update(updateDescription.toString(), updateParams.toArray());
    182             }
    183 
    184             if (content != null) {
    185                 // Update content
    186                 StringBuilder updateContent = new StringBuilder();
    187                 updateContent.append("UPDATE " + TABLE_XML_CONTENT + " SET content = ? WHERE " + COLUMN_ID + " = ");
    188                 updateContent.append("(SELECT content_id FROM ").append(getTableName()).append(" WHERE " + COLUMN_ID + "= ?)");
    189 
    190                 getSimpleJdbcTemplate().update(updateContent.toString(), content, id);
    191             }
    192             txManager.commit(transaction);
    193         } catch (DataAccessException ex) {
    194             txManager.rollback(transaction);
    195             throw ex;
     190    @Override
     191    public void updateDescription(Number id, AbstractDescription description,
     192            String content) {
     193        if (description != null) {
     194            // Update description
     195            StringBuilder updateDescription = new StringBuilder();
     196            updateDescription.append("UPDATE ").append(getTableName());
     197            appendUpdateColumnsStatement(updateDescription);
     198            updateDescription.append(" WHERE " + COLUMN_ID + " = ?");
     199            Collection updateParams = ListUtils.union(
     200                    getUpdateParameterValues(description),
     201                    Collections.singletonList(id));
     202            getJdbcTemplate().update(updateDescription.toString(),
     203                    updateParams.toArray());
     204        }
     205
     206        if (content != null) {
     207            // Update content
     208            StringBuilder updateContent = new StringBuilder();
     209            updateContent.append("UPDATE " + TABLE_XML_CONTENT
     210                    + " SET content = ? WHERE " + COLUMN_ID + " = ");
     211            updateContent.append("(SELECT content_id FROM ")
     212                    .append(getTableName())
     213                    .append(" WHERE " + COLUMN_ID + "= ?)");
     214
     215            getJdbcTemplate().update(updateContent.toString(), content, id);
    196216        }
    197217    }
     
    204224     * @return The description, if it exists; null otherwise
    205225     */
     226    @Override
    206227    public T getById(Number id) throws DataAccessException {
    207         return getFirstOrNull(getSelectStatement("WHERE is_deleted = false AND id = ?"), id);
     228        return getFirstOrNull(
     229                getSelectStatement("WHERE is_deleted = false AND id = ?"), id);
    208230    }
    209231
     
    215237     * @return The description, if it exists; null otherwise
    216238     */
     239    @Override
    217240    public T getByCmdId(String id) throws DataAccessException {
    218         return getFirstOrNull(getSelectStatement("WHERE is_deleted = false AND " + getCMDIdColumn() + " = ?"), id);
     241        return getFirstOrNull(
     242                getSelectStatement("WHERE is_deleted = false AND "
     243                        + getCMDIdColumn() + " = ?"), id);
    219244    }
    220245
     
    228253     * @return The description, if it exists; null otherwise
    229254     */
     255    @Override
    230256    public T getByCmdId(String id, Number userId) throws DataAccessException {
    231         StringBuilder query = new StringBuilder("WHERE is_deleted = false AND ").append(getCMDIdColumn()).append(" = ?");
     257        StringBuilder query = new StringBuilder("WHERE is_deleted = false AND ")
     258                .append(getCMDIdColumn()).append(" = ?");
    232259        if (userId == null) {
    233             return getFirstOrNull(getSelectStatement(query.append(" AND is_public = true").toString()), id);
     260            return getFirstOrNull(
     261                    getSelectStatement(query.append(" AND is_public = true")
     262                            .toString()), id);
    234263        } else {
    235             return getFirstOrNull(getSelectStatement(query.append(" AND is_public = false AND user_id = ?").toString()), id, userId);
     264            return getFirstOrNull(
     265                    getSelectStatement(query.append(
     266                            " AND is_public = false AND user_id = ?")
     267                            .toString()), id, userId);
    236268        }
    237269    }
     
    243275     * @return Database id for description record
    244276     */
     277    @Override
    245278    public Number getDbId(String cmdId) {
    246         StringBuilder query = new StringBuilder("SELECT " + COLUMN_ID + " FROM ").append(getTableName());
     279        StringBuilder query = new StringBuilder("SELECT " + COLUMN_ID
     280                + " FROM ").append(getTableName());
    247281        query.append(" WHERE ").append(getCMDIdColumn()).append(" = ?");
    248         return getSimpleJdbcTemplate().queryForInt(query.toString(), cmdId);
     282        return getJdbcTemplate().queryForInt(query.toString(), cmdId);
    249283    }
    250284
     
    253287     * @return All descriptions in the public space
    254288     */
     289    @Override
    255290    public List<T> getPublicDescriptions() throws DataAccessException {
    256         return getList(getSelectStatement(" WHERE is_deleted = false AND is_public = true ").append(getOrderByClause()));
    257     }
    258 
    259     /**
    260      * @return List of deleted descriptions in user space or in public when userId=null
     291        return getList(getSelectStatement(
     292                " WHERE is_deleted = false AND is_public = true ").append(
     293                getOrderByClause()));
     294    }
     295
     296    /**
     297     * @return List of deleted descriptions in user space or in public when
     298     *         userId=null
    261299     * @param userId
    262300     */
     301    @Override
    263302    public List<T> getDeletedDescriptions(Number userId) {
    264303        if (userId != null) {
    265             String select = getSelectStatement().append(" WHERE is_deleted = true AND is_public = false AND user_id = ?").append(getOrderByClause()).toString();
     304            String select = getSelectStatement()
     305                    .append(" WHERE is_deleted = true AND is_public = false AND user_id = ?")
     306                    .append(getOrderByClause()).toString();
    266307            return getList(select, userId);
    267308        } else {
    268             String select = getSelectStatement().append(" WHERE is_deleted = true AND is_public = true").append(getOrderByClause()).toString();
     309            String select = getSelectStatement()
     310                    .append(" WHERE is_deleted = true AND is_public = true")
     311                    .append(getOrderByClause()).toString();
    269312            return getList(select);
    270313        }
     
    275318     * @return All the user's descriptions not in the public space
    276319     */
    277     public List<T> getUserspaceDescriptions(Number userId) throws DataAccessException {
    278         String select = getSelectStatement().append(" WHERE is_deleted = false AND is_public = false AND user_id = ?").append(getOrderByClause()).toString();
     320    @Override
     321    public List<T> getUserspaceDescriptions(Number userId)
     322            throws DataAccessException {
     323        String select = getSelectStatement()
     324                .append(" WHERE is_deleted = false AND is_public = false AND user_id = ?")
     325                .append(getOrderByClause()).toString();
    279326        return getList(select, userId);
    280327    }
    281328
    282     public void setDeleted(AbstractDescription desc, boolean isDeleted) throws DataAccessException {
    283         TransactionStatus transaction = getTransaction();
     329    @Override
     330    public void setDeleted(AbstractDescription desc, boolean isDeleted)
     331            throws DataAccessException {
    284332        Number dbId = getDbId(desc.getId());
    285         StringBuilder update = new StringBuilder("UPDATE ").append(getTableName());
    286         update.append(" SET is_deleted = ").append(Boolean.toString(isDeleted)).append(" WHERE " + COLUMN_ID + " = ?");
    287         getSimpleJdbcTemplate().update(update.toString(), dbId);
    288         txManager.commit(transaction);
    289     }
    290 
     333        StringBuilder update = new StringBuilder("UPDATE ")
     334                .append(getTableName());
     335        update.append(" SET is_deleted = ").append(Boolean.toString(isDeleted))
     336                .append(" WHERE " + COLUMN_ID + " = ?");
     337        getJdbcTemplate().update(update.toString(), dbId);
     338    }
     339
     340    @Override
    291341    public void setPublished(Number id, boolean published) {
    292         TransactionStatus transaction = getTransaction();
    293         StringBuilder update = new StringBuilder("UPDATE ").append(getTableName());
     342        StringBuilder update = new StringBuilder("UPDATE ")
     343                .append(getTableName());
    294344        update.append(" SET is_public = ? WHERE " + COLUMN_ID + " = ?");
    295         getSimpleJdbcTemplate().update(update.toString(), published, id);
    296         txManager.commit(transaction);
     345        getJdbcTemplate().update(update.toString(), published, id);
    297346    }
    298347
     
    303352     * @return Principal name of description's owner, if any. Otherwise, null.
    304353     */
     354    @Override
    305355    public String getOwnerPrincipalName(Number id) {
    306         StringBuilder select = new StringBuilder("SELECT principal_name FROM " + TABLE_REGISTRY_USER);
     356        StringBuilder select = new StringBuilder("SELECT principal_name FROM "
     357                + TABLE_REGISTRY_USER);
    307358        select.append(" JOIN ").append(getTableName());
    308359        select.append(" ON user_id = " + TABLE_REGISTRY_USER + ".id ");
    309360        select.append(" WHERE ").append(getTableName()).append(".id = ?");
    310         List<String> owner = getSimpleJdbcTemplate().query(select.toString(), new ParameterizedSingleColumnRowMapper<String>(), id);
     361        List<String> owner = getJdbcTemplate().query(select.toString(),
     362                new ParameterizedSingleColumnRowMapper<String>(), id);
    311363        if (owner.isEmpty()) {
    312364            return null;
     
    326378    /**
    327379     * Inserts parameters int <column, value> parameters map
     380     *
    328381     * @param params
    329382     * @param description
    330383     * @param contentId
    331384     * @param userId
    332      * @param isPublic
    333      */
    334     protected void putInsertParameters(Map<String, Object> params, AbstractDescription description, Number contentId, Number userId, boolean isPublic) {
     385     * @param isPublic
     386     */
     387    protected void putInsertParameters(Map<String, Object> params,
     388            AbstractDescription description, Number contentId, Number userId,
     389            boolean isPublic) {
    335390        params.put("content_id", contentId);
    336391        params.put("user_id", userId);
     
    349404    /**
    350405     * Sets values on a new description object from specified ResultSet
    351      * @param rs ResultSet from database query
    352      * @param newDescription Newly created description object to be filled
    353      * @throws SQLException
    354      */
    355     protected void setDescriptionValuesFromResultSet(ResultSet rs, AbstractDescription newDescription) throws SQLException {
     406     *
     407     * @param rs
     408     *            ResultSet from database query
     409     * @param newDescription
     410     *            Newly created description object to be filled
     411     * @throws SQLException
     412     */
     413    protected void setDescriptionValuesFromResultSet(ResultSet rs,
     414            AbstractDescription newDescription) throws SQLException {
    356415        Timestamp registrationDate = rs.getTimestamp("registration_date");
    357416        newDescription.setName(rs.getString("name"));
    358417        newDescription.setDescription(rs.getString("description"));
    359418        newDescription.setId(rs.getString(getCMDIdColumn()));
    360         newDescription.setRegistrationDate(registrationDate == null ? null : AbstractDescription.createNewDate(registrationDate.getTime()));
     419        newDescription
     420                .setRegistrationDate(registrationDate == null ? null
     421                        : AbstractDescription.createNewDate(registrationDate
     422                                .getTime()));
    361423        newDescription.setCreatorName(rs.getString("creator_name"));
    362424        newDescription.setDomainName(rs.getString("domain_name"));
     
    372434
    373435    protected void appendUpdateColumnsStatement(StringBuilder updateDescription) {
    374         updateDescription.append(" SET name = ?, description = ?, registration_date=?, creator_name=?, domain_name=?, group_name=?, href=?");
     436        updateDescription
     437                .append(" SET name = ?, description = ?, registration_date=?, creator_name=?, domain_name=?, group_name=?, href=?");
    375438    }
    376439
    377440    protected List getUpdateParameterValues(AbstractDescription description) {
    378         List updateParams = Arrays.asList(description.getName(), description.getDescription(),
    379                 extractTimestamp(description), description.getCreatorName(), description.getDomainName(),
     441        List updateParams = Arrays.asList(description.getName(),
     442                description.getDescription(), extractTimestamp(description),
     443                description.getCreatorName(), description.getDomainName(),
    380444                description.getGroupName(), description.getHref());
    381445        return updateParams;
    382446    }
     447
    383448    /*
    384449     * DAO HELPER METHODS
    385450     */
    386451
    387     private StringBuilder getSelectStatement(String... where) throws DataAccessException {
    388         StringBuilder select = new StringBuilder("SELECT ").append(getDescriptionColumnList());
     452    private StringBuilder getSelectStatement(String... where)
     453            throws DataAccessException {
     454        StringBuilder select = new StringBuilder("SELECT ")
     455                .append(getDescriptionColumnList());
    389456        select.append(" FROM ").append(getTableName());
    390457        if (where.length > 0) {
     
    407474        sb.append(",description,registration_date,creator_name,domain_name,group_name,href,user_id,");
    408475        sb.append(getCMDIdColumn());
    409         sb.append(", (SELECT COUNT(*) FROM comments WHERE ").append(getCommentsForeignKeyColumn()).append(" = ").append(getCMDIdColumn()).append(") AS columns_count");
     476        sb.append(", (SELECT COUNT(*) FROM comments WHERE ")
     477                .append(getCommentsForeignKeyColumn()).append(" = ")
     478                .append(getCMDIdColumn()).append(") AS columns_count");
    410479        return sb;
    411480    }
     
    416485
    417486    private String getOrderByClause() {
    418         return " order by upper(" + getOrderByColumn() + "), " + getCMDIdColumn() + " asc ";
    419     }
     487        return " order by upper(" + getOrderByColumn() + "), "
     488                + getCMDIdColumn() + " asc ";
     489    }
     490
    420491    private final ParameterizedRowMapper<T> rowMapper = new ParameterizedRowMapper<T>() {
    421492
     
    423494        public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    424495            try {
    425                 AbstractDescription newDescription = (AbstractDescription) _class.newInstance();
     496                AbstractDescription newDescription = (AbstractDescription) _class
     497                        .newInstance();
    426498                setDescriptionValuesFromResultSet(rs, newDescription);
    427499                return (T) newDescription;
     
    435507    };
    436508
    437     private TransactionStatus getTransaction() {
    438         return txManager.getTransaction(txDefinition);
    439     }
    440509}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/AdminRegistry.java

    r3088 r3449  
    2626import clarin.cmdi.componentregistry.model.ProfileDescription;
    2727
     28/**
     29 *
     30 * @author george.georgovassilis@mpi.nl
     31 *
     32 */
    2833public class AdminRegistry {
    2934
    30     private final static Logger LOG = LoggerFactory.getLogger(AdminRegistry.class);
     35    private final static Logger LOG = LoggerFactory
     36            .getLogger(AdminRegistry.class);
    3137    private ComponentRegistryFactory componentRegistryFactory;
    32     private ProfileDescriptionDao profileDescriptionDao;
    33     private ComponentDescriptionDao componentDescriptionDao;
     38    private IProfileDescriptionDAO profileDescriptionDao;
     39    private IComponentDescriptionDao componentDescriptionDao;
    3440    private MDMarshaller marshaller;
    3541
    36     public void setComponentRegistryFactory(ComponentRegistryFactory componentRegistryFactory) {
     42    public void setComponentRegistryFactory(
     43            ComponentRegistryFactory componentRegistryFactory) {
    3744        this.componentRegistryFactory = componentRegistryFactory;
    3845    }
    3946
    40     public void setProfileDescriptionDao(ProfileDescriptionDao profileDescriptionDao) {
     47    public void setProfileDescriptionDao(
     48            IProfileDescriptionDAO profileDescriptionDao) {
    4149        this.profileDescriptionDao = profileDescriptionDao;
    4250    }
    4351
    44     public void setComponentDescriptionDao(ComponentDescriptionDao componentDescriptionDao) {
     52    public void setComponentDescriptionDao(
     53            IComponentDescriptionDao componentDescriptionDao) {
    4554        this.componentDescriptionDao = componentDescriptionDao;
    4655    }
     
    5059    }
    5160
    52     public void submitFile(CMDItemInfo info, Principal userPrincipal) throws SubmitFailedException {
     61    public void submitFile(CMDItemInfo info, Principal userPrincipal)
     62            throws SubmitFailedException {
    5363        try {
    54             AbstractDescription originalDescription = info.getDataNode().getDescription();
     64            AbstractDescription originalDescription = info.getDataNode()
     65                    .getDescription();
    5566            AbstractDescription description = null;
    5667            CMDComponentSpec spec = null;
    5768            if (originalDescription.isProfile()) {
    58                 description = marshaller.unmarshal(ProfileDescription.class, IOUtils.toInputStream(info.getDescription(), "UTF-8"), null);
     69                description = marshaller.unmarshal(ProfileDescription.class,
     70                        IOUtils.toInputStream(info.getDescription(), "UTF-8"),
     71                        null);
    5972            } else {
    60                 description = marshaller.unmarshal(ComponentDescription.class, IOUtils.toInputStream(info.getDescription(), "UTF-8"),
     73                description = marshaller.unmarshal(ComponentDescription.class,
     74                        IOUtils.toInputStream(info.getDescription(), "UTF-8"),
    6175                        null);
    6276            }
    63             spec = marshaller.unmarshal(CMDComponentSpec.class, IOUtils.toInputStream(info.getContent(), "UTF-8"), null);
     77            spec = marshaller.unmarshal(CMDComponentSpec.class,
     78                    IOUtils.toInputStream(info.getContent(), "UTF-8"), null);
    6479            checkId(originalDescription.getId(), description.getId());
    6580
    66             int result = getRegistry(userPrincipal, originalDescription, info).update(description, spec, userPrincipal, info.isForceUpdate());
     81            int result = getRegistry(userPrincipal, originalDescription, info)
     82                    .update(description, spec, userPrincipal,
     83                            info.isForceUpdate());
    6784            if (result < 0) {
    68                 throw new SubmitFailedException("Problem occured while registering, please check the tomcat logs for errors.");
     85                throw new SubmitFailedException(
     86                        "Problem occured while registering, please check the tomcat logs for errors.");
    6987            }
    7088        } catch (JAXBException e) {
     
    7795    private void checkId(String id, String id2) throws SubmitFailedException {
    7896        if (id == null || id2 == null || !id.equals(id2)) {
    79             throw new SubmitFailedException("Id's do not match up, you cannot edit id's: id1=" + id + ", id2=" + id2);
     97            throw new SubmitFailedException(
     98                    "Id's do not match up, you cannot edit id's: id1=" + id
     99                            + ", id2=" + id2);
    80100        }
    81101    }
     
    94114    }
    95115
    96     public void delete(CMDItemInfo info, Principal userPrincipal) throws SubmitFailedException {
     116    public void delete(CMDItemInfo info, Principal userPrincipal)
     117            throws SubmitFailedException {
    97118        String id = info.getName();
    98119        AbstractDescription desc = info.getDataNode().getDescription();
     
    112133    }
    113134
    114     private void deleteFromRegistry(Principal userPrincipal, AbstractDescription desc, CMDItemInfo info) throws IOException,
     135    private void deleteFromRegistry(Principal userPrincipal,
     136            AbstractDescription desc, CMDItemInfo info) throws IOException,
    115137            UserUnauthorizedException, ComponentRegistryException {
    116138        ComponentRegistry registry = getRegistry(userPrincipal, desc, info);
     
    119141            registry.deleteMDProfile(desc.getId(), userPrincipal);
    120142        } else {
    121             registry.deleteMDComponent(desc.getId(), userPrincipal, info.isForceUpdate());
     143            registry.deleteMDComponent(desc.getId(), userPrincipal,
     144                    info.isForceUpdate());
    122145        }
    123146    }
    124147
    125     private ComponentRegistry getRegistry(Principal userPrincipal, AbstractDescription desc, CMDItemInfo info) {
    126         ComponentRegistry registry = componentRegistryFactory.getPublicRegistry();
    127         //TODO: More generic check
    128         if (info.getStatus() == ComponentStatus.PRIVATE /* || info.getStatus() == ComponentStatus.DEVELOPMENT */) {
    129             registry = componentRegistryFactory.getOtherUserComponentRegistry(userPrincipal, info.getStatus(), new OwnerUser(Integer.parseInt(desc.getUserId())));
     148    private ComponentRegistry getRegistry(Principal userPrincipal,
     149            AbstractDescription desc, CMDItemInfo info) {
     150        ComponentRegistry registry = componentRegistryFactory
     151                .getPublicRegistry();
     152        // TODO: More generic check
     153        if (info.getStatus() == ComponentStatus.PRIVATE /*
     154                                                         * || info.getStatus()
     155                                                         * == ComponentStatus.
     156                                                         * DEVELOPMENT
     157                                                         */) {
     158            registry = componentRegistryFactory.getOtherUserComponentRegistry(
     159                    userPrincipal, info.getStatus(),
     160                    new OwnerUser(Integer.parseInt(desc.getUserId())));
    130161        }
    131162        return registry;
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/CommentsDao.java

    r1895 r3449  
    1111import java.util.List;
    1212import java.util.Map;
     13
    1314import org.slf4j.Logger;
    1415import org.slf4j.LoggerFactory;
    15 import org.springframework.beans.factory.annotation.Autowired;
    1616import org.springframework.dao.DataAccessException;
    1717import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
    1818import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper;
    1919import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
    20 import org.springframework.transaction.PlatformTransactionManager;
    21 import org.springframework.transaction.TransactionDefinition;
    22 import org.springframework.transaction.TransactionStatus;
     20import org.springframework.stereotype.Repository;
    2321
    2422/**
    25  *
     23 * Serves comments for profiles and components
    2624 * @author jean-charles FerriÚres <jean-charles.ferrieres@mpi.nl>
     25 * @author George.Georgovassilis@mpi.nl
    2726 */
    28 public class CommentsDao extends ComponentRegistryDao<Comment> {
    29 
    30     @Autowired
    31     private PlatformTransactionManager txManager;
    32     @Autowired
    33     private TransactionDefinition txDefinition;
    34     private final static Logger LOG = LoggerFactory.getLogger(CommentsDao.class);
    35     private final static String SELECT_BASE = "SELECT " + COLUMN_ID + ", comments, comment_date, user_id, "
    36             + "component_description_id, profile_description_id, user_name FROM " + TABLE_COMMENTS;
     27@Repository
     28public class CommentsDao extends ComponentRegistryDao<Comment> implements
     29        ICommentsDao {
     30
     31    private final static Logger LOG = LoggerFactory
     32            .getLogger(CommentsDao.class);
     33    private final static String SELECT_BASE = "SELECT "
     34            + COLUMN_ID
     35            + ", comments, comment_date, user_id, "
     36            + "component_description_id, profile_description_id, user_name FROM "
     37            + TABLE_COMMENTS;
    3738
    3839    protected String getTableName() {
    39         return TABLE_COMMENTS;
     40        return TABLE_COMMENTS;
    4041    }
    4142
    4243    protected String getCMDIdColumn() {
    43         return COLUMN_ID;
    44     }
    45 
    46     /**
    47      * Get the list of all the comments available in the database
    48      * The distinction between profile or component is not treated in this method
    49      * @return list of Comments
    50      */
     44        return COLUMN_ID;
     45    }
     46
     47    /**
     48     * Get the list of all the comments available in the database The
     49     * distinction between profile or component is not treated in this method
     50     *
     51     * @return list of Comments
     52     */
     53    @Override
    5154    public List<Comment> getAllComments() throws DataAccessException {
    52         return getList(SELECT_BASE);
     55        return getList(SELECT_BASE);
    5356    }
    5457
    5558    /**
    5659     * Look for a specified Comment through its id
    57      * @param id Database record id (key)
     60     *
     61     * @param id
     62     *            Database record id (key)
    5863     * @return Comment, if it exists
    5964     * @throws DataAccessException
    6065     */
     66    @Override
    6167    public Comment getById(Number id) throws DataAccessException {
    62         return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", id);
     68        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", id);
    6369    }
    6470
    6571    /**
    6672     * Retrieve the comments related to a certain profile
    67      * @param id Database record id (fkey)
    68      * @return list of Comments
    69      */
    70     public List<Comment> getCommentsFromProfile(String profileId) throws DataAccessException {
    71         return getList((SELECT_BASE + " WHERE profile_description_id = ?").concat(getOrderByDate()), profileId);
     73     *
     74     * @param id
     75     *            Database record id (fkey)
     76     * @return list of Comments
     77     */
     78    @Override
     79    public List<Comment> getCommentsFromProfile(String profileId)
     80            throws DataAccessException {
     81        return getList(
     82                (SELECT_BASE + " WHERE profile_description_id = ?")
     83                        .concat(getOrderByDate()),
     84                profileId);
    7285    }
    7386
    7487    /**
    7588     * Retrieve a specific comment related to a profile
    76      * @param id Database record id (key)
     89     *
     90     * @param id
     91     *            Database record id (key)
    7792     * @return Comment
    78      * @throws DataAccessException
    79      */
    80     public Comment getSpecifiedCommentFromProfile(String commentId) throws DataAccessException {
    81         return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", Integer.parseInt(commentId));
     93     * @throws DataAccessException
     94     */
     95    public Comment getSpecifiedCommentFromProfile(String commentId)
     96            throws DataAccessException {
     97        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?",
     98                Integer.parseInt(commentId));
    8299    }
    83100
    84101    /**
    85102     * Retrieve the comments related to a certain component
    86      * @param id Database record id (fkey)
    87      * @return list of Comments
    88      * @throws DataAccessException
    89      */
    90     public List<Comment> getCommentsFromComponent(String componentId) throws DataAccessException {
    91         return getList((SELECT_BASE + " WHERE component_description_id = ?").concat(getOrderByDate()), componentId);
     103     *
     104     * @param id
     105     *            Database record id (fkey)
     106     * @return list of Comments
     107     * @throws DataAccessException
     108     */
     109    public List<Comment> getCommentsFromComponent(String componentId)
     110            throws DataAccessException {
     111        return getList(
     112                (SELECT_BASE + " WHERE component_description_id = ?")
     113                        .concat(getOrderByDate()),
     114                componentId);
    92115    }
    93116
    94117    /**
    95118     * Retrieve a specific comment related to a component
    96      * @param id Database record id (key)
     119     *
     120     * @param id
     121     *            Database record id (key)
    97122     * @return Comment
    98      * @throws DataAccessException
    99      */
    100     public Comment getSpecifiedCommentFromComponent(String commentId) throws DataAccessException {
    101         return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " =  ?", Integer.parseInt(commentId));
     123     * @throws DataAccessException
     124     */
     125    public Comment getSpecifiedCommentFromComponent(String commentId)
     126            throws DataAccessException {
     127        return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " =  ?",
     128                Integer.parseInt(commentId));
    102129    }
    103130
     
    109136     */
    110137    public String getOwnerPrincipalName(Number id) {
    111         StringBuilder select = new StringBuilder("SELECT principal_name FROM " + TABLE_REGISTRY_USER);
    112         select.append(" JOIN ").append(getTableName());
    113         select.append(" ON user_id = " + TABLE_REGISTRY_USER + ".id ");
    114         select.append(" WHERE ").append(getTableName()).append(".id = ?");
    115         List<String> owner = getSimpleJdbcTemplate().query(select.toString(), new ParameterizedSingleColumnRowMapper<String>(), id);
    116         if (owner.isEmpty()) {
    117             return null;
    118         }
    119         {
    120             return owner.get(0);
    121         }
    122     }
    123 
    124     /**
    125      *
     138        StringBuilder select = new StringBuilder("SELECT principal_name FROM "
     139                + TABLE_REGISTRY_USER);
     140        select.append(" JOIN ").append(getTableName());
     141        select.append(" ON user_id = " + TABLE_REGISTRY_USER + ".id ");
     142        select.append(" WHERE ").append(getTableName()).append(".id = ?");
     143        List<String> owner = getJdbcTemplate().query(select.toString(),
     144                new ParameterizedSingleColumnRowMapper<String>(), id);
     145        if (owner.isEmpty()) {
     146            return null;
     147        }
     148        {
     149            return owner.get(0);
     150        }
     151    }
     152
     153    /**
     154     *
    126155     * @param comment
    127      *              the comment to be inserted
     156     *            the comment to be inserted
    128157     * @param content
    129      *              
     158     *
    130159     * @param userId
    131      *              the id of the user
     160     *            the id of the user
    132161     * @return Record id of the inserted comment
    133162     * @throws DataAccessException
    134163     */
    135     public Number insertComment(Comment comment, Number userId) throws DataAccessException {
    136         TransactionStatus transaction = getTransaction();
    137         try {
    138             SimpleJdbcInsert insertComment = new SimpleJdbcInsert(getDataSource()).withTableName(getTableName()).usingGeneratedKeyColumns(COLUMN_ID);
    139             Map<String, Object> params = new HashMap<String, Object>();
    140             putInsertComment(params, comment, userId);
    141 
    142             Number id = insertComment.executeAndReturnKey(params);
    143             txManager.commit(transaction);
    144             return id;
    145         } catch (DataAccessException ex) {
    146             txManager.rollback(transaction);
    147             throw ex;
    148         }
     164    public Number insertComment(Comment comment, Number userId)
     165            throws DataAccessException {
     166        SimpleJdbcInsert insertComment = new SimpleJdbcInsert(getDataSource())
     167                .withTableName(getTableName()).usingGeneratedKeyColumns(
     168                        COLUMN_ID);
     169        Map<String, Object> params = new HashMap<String, Object>();
     170        putInsertComment(params, comment, userId);
     171
     172        Number id = insertComment.executeAndReturnKey(params);
     173        return id;
    149174    }
    150175
     
    155180     * @param contentId
    156181     * @param userId
    157      * @throws DataAccessException
    158      */
    159     protected void putInsertComment(Map<String, Object> params, Comment comment, Number userId) throws DataAccessException {
    160         params.put("comments", comment.getComment());
    161         params.put("comment_date", extractTimestamp(comment));
    162         params.put("component_description_id", comment.getComponentDescriptionId());
    163         params.put("profile_description_id", comment.getProfileDescriptionId());
    164         params.put("user_id", userId);
     182     * @throws DataAccessException
     183     */
     184    protected void putInsertComment(Map<String, Object> params,
     185            Comment comment, Number userId) throws DataAccessException {
     186        params.put("comments", comment.getComment());
     187        params.put("comment_date", extractTimestamp(comment));
     188        params.put("component_description_id",
     189                comment.getComponentDescriptionId());
     190        params.put("profile_description_id", comment.getProfileDescriptionId());
     191        params.put("user_id", userId);
    165192        params.put("user_name", comment.getUserName());
    166193    }
     
    168195    @Override
    169196    protected ParameterizedRowMapper<Comment> getRowMapper() {
    170         return rowMapper;
    171     }
     197        return rowMapper;
     198    }
     199
    172200    private final ParameterizedRowMapper<Comment> rowMapper = new ParameterizedRowMapper<Comment>() {
    173201
    174         @Override
    175         public Comment mapRow(ResultSet rs, int rowNumber) throws SQLException {
    176             Comment comment = new Comment();
    177             Timestamp commentDate = rs.getTimestamp("comment_date");
    178             comment.setId(rs.getString(COLUMN_ID));
    179             comment.setComment(rs.getString("comments"));
    180             comment.setComponentDescriptionId(rs.getString("component_description_id"));
    181             comment.setProfileDescriptionId(rs.getString("profile_description_id"));
    182             comment.setUserId(rs.getString("user_id"));
     202        @Override
     203        public Comment mapRow(ResultSet rs, int rowNumber) throws SQLException {
     204            Comment comment = new Comment();
     205            Timestamp commentDate = rs.getTimestamp("comment_date");
     206            comment.setId(rs.getString(COLUMN_ID));
     207            comment.setComment(rs.getString("comments"));
     208            comment.setComponentDescriptionId(rs
     209                    .getString("component_description_id"));
     210            comment.setProfileDescriptionId(rs
     211                    .getString("profile_description_id"));
     212            comment.setUserId(rs.getString("user_id"));
    183213            comment.setUserName(rs.getString("user_name"));
    184             comment.setCommentDate(commentDate == null ? null : Comment.createNewDate(commentDate.getTime()));
    185             return comment;
    186         }
     214            comment.setCommentDate(commentDate == null ? null : Comment
     215                    .createNewDate(commentDate.getTime()));
     216            return comment;
     217        }
    187218    };
    188219
    189220    /**
    190221     * Method that will delete a comment from the database based on its id
     222     *
    191223     * @param com
    192      *           comment to be deleted
    193      * @throws DataAccessException 
     224     *            comment to be deleted
     225     * @throws DataAccessException
    194226     */
    195227    public void deleteComment(Comment com) throws DataAccessException {
    196         TransactionStatus transaction = getTransaction();
    197         Number dbId = Integer.parseInt(com.getId());
    198         StringBuilder delete = new StringBuilder("DELETE FROM ").append(getTableName());
    199         delete.append(" WHERE " + COLUMN_ID + " = ?");
    200         getSimpleJdbcTemplate().update(delete.toString(), dbId);
    201         txManager.commit(transaction);
     228        Number dbId = Integer.parseInt(com.getId());
     229        StringBuilder delete = new StringBuilder("DELETE FROM ")
     230                .append(getTableName());
     231        delete.append(" WHERE " + COLUMN_ID + " = ?");
     232        getJdbcTemplate().update(delete.toString(), dbId);
    202233    }
    203234
    204235    private Timestamp extractTimestamp(Comment comment) {
    205         if (comment.getCommentDate() != null) {
    206             try {
    207                 Date date = Comment.getDate(comment.getCommentDate());
    208                 return new Timestamp(date.getTime());
    209             } catch (ParseException ex) {
    210                 LOG.warn("Could not convert registration date " + comment.getCommentDate() + " to date", ex);
    211             } catch (IllegalArgumentException ex) {
    212                 LOG.warn("Could not convert registration date " + comment.getCommentDate() + " to timestamp", ex);
    213             }
    214         }
    215         return null;
    216     }
    217 
    218     private TransactionStatus getTransaction() {
    219         return txManager.getTransaction(txDefinition);
     236        if (comment.getCommentDate() != null) {
     237            try {
     238                Date date = Comment.getDate(comment.getCommentDate());
     239                return new Timestamp(date.getTime());
     240            } catch (ParseException ex) {
     241                LOG.warn(
     242                        "Could not convert registration date "
     243                                + comment.getCommentDate() + " to date", ex);
     244            } catch (IllegalArgumentException ex) {
     245                LOG.warn(
     246                        "Could not convert registration date "
     247                                + comment.getCommentDate() + " to timestamp",
     248                        ex);
     249            }
     250        }
     251        return null;
    220252    }
    221253
    222254    /**
    223255     * Method use for tests that will select comments based on the content
     256     *
    224257     * @param aComment
    225258     * @return list of Comments
    226      * @throws DataAccessException 
     259     * @throws DataAccessException
    227260     */
    228261    public Comment getByComment(String aComment) throws DataAccessException {
    229         return getFirstOrNull(SELECT_BASE + " WHERE comments = ?", aComment);
    230     }
    231    
     262        return getFirstOrNull(SELECT_BASE + " WHERE comments = ?", aComment);
     263    }
     264
    232265    /**
    233266     * Sort the returned comments per date from the most recent to the oldest
    234      * @return
    235      */
    236         private String getOrderByDate() {
    237         return " order by comment_date asc ";
     267     *
     268     * @return
     269     */
     270    private String getOrderByDate() {
     271        return " order by comment_date asc, " + COLUMN_ID + " asc";
    238272    }
    239273}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentDescriptionDao.java

    r1701 r3449  
    22
    33import clarin.cmdi.componentregistry.model.ComponentDescription;
     4
    45import java.util.List;
    56
     7import org.springframework.stereotype.Repository;
     8
    69/**
    7  *
     10 * Serves components
    811 * @author Twan Goosen <twan.goosen@mpi.nl>
     12 * @author George.Georgovassilis@mpi.nl
    913 */
    10 public class ComponentDescriptionDao extends AbstractDescriptionDao<ComponentDescription> {
     14@Repository
     15public class ComponentDescriptionDao extends
     16        AbstractDescriptionDao<ComponentDescription> implements
     17        IComponentDescriptionDao {
    1118
    1219    public ComponentDescriptionDao() {
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDao.java

    r3048 r3449  
    22
    33import java.util.List;
     4
     5import javax.sql.DataSource;
     6
     7import org.springframework.beans.factory.annotation.Autowired;
     8import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
    49import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
    5 import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
    610
    711/**
    812 * Logic and constants shared by the dao's of the DB implementation
    9  *
    10  * TODO: For future extensions we may want to use {@link org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport}
    11  *
     13 *
     14 *
    1215 * @author Twan Goosen <twan.goosen@mpi.nl>
    13  * @param <T> Type the dao maps to
     16 * @author George.Georgovassilis@mpi.nl
     17 * @param <T>
     18 *            Type the dao maps to
    1419 */
    15 public abstract class ComponentRegistryDao<T> extends SimpleJdbcDaoSupport {
    16 
    17     public final static String TABLE_COMMENTS = "comments";
    18     public final static String TABLE_COMPONENT_DESCRIPTION = "component_description";
    19     public final static String TABLE_PROFILE_DESCRIPTION = "profile_description";
    20     public final static String TABLE_XML_CONTENT = "xml_content";
    21     public final static String TABLE_REGISTRY_USER = "registry_user";
    22     public final static String COLUMN_ID = "id";
     20public abstract class ComponentRegistryDao<T> extends
     21        NamedParameterJdbcDaoSupport implements IComponentRegistryDao<T> {
    2322
    2423    public ComponentRegistryDao() {
     
    4342
    4443    protected List<T> getList(String selectQuery, Object... args) {
    45         return getSimpleJdbcTemplate().query(selectQuery, getRowMapper(), args);
     44        return getJdbcTemplate().query(selectQuery, getRowMapper(), args);
    4645    }
    4746
     
    5049     */
    5150    protected abstract ParameterizedRowMapper<T> getRowMapper();
     51
     52    @Override
     53    @Autowired
     54    public void setDatasourceProperty(DataSource ds) {
     55        super.setDataSource(ds);
     56    }
     57
    5258}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImpl.java

    r3088 r3449  
    4343 * Implementation of ComponentRegistry that uses Database Acces Objects for
    4444 * accessing the registry (ergo: a database implementation)
    45  *
     45 * 
    4646 * @author Twan Goosen <twan.goosen@mpi.nl>
     47 * @author George.Georgovassilis@mpi.nl
    4748 */
    48 public class ComponentRegistryDbImpl extends ComponentRegistryImplBase implements ComponentRegistry {
    49 
    50     private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryDbImpl.class);
     49public class ComponentRegistryDbImpl extends ComponentRegistryImplBase
     50        implements ComponentRegistry {
     51
     52    private final static Logger LOG = LoggerFactory
     53            .getLogger(ComponentRegistryDbImpl.class);
    5154    private Owner registryOwner;
    5255    private ComponentStatus registryStatus;
     
    6164    // DAO's
    6265    @Autowired
    63     private ProfileDescriptionDao profileDescriptionDao;
     66    private IProfileDescriptionDAO profileDescriptionDao;
    6467    @Autowired
    65     private ComponentDescriptionDao componentDescriptionDao;
     68    private IComponentDescriptionDao componentDescriptionDao;
    6669    @Autowired
    67     private UserDao userDao;
     70    private IUserDAO userDao;
    6871    @Autowired
    69     private CommentsDao commentsDao;
     72    private ICommentsDao commentsDao;
    7073    @Autowired
    7174    private MDMarshaller marshaller;
    7275
    7376    /**
    74      * Default constructor, to use this as a (spring) bean. The public registry by default.
    75      * Use setStatus() and setOwner() to make it another kind of registry.
    76      *
     77     * Default constructor, to use this as a (spring) bean. The public registry
     78     * by default. Use setStatus() and setOwner() to make it another kind of
     79     * registry.
     80     *
    7781     * @see setUser
    7882     */
     
    8387    /**
    8488     * Creates a new ComponentRegistry (either public or not) for the provided
    85      * user. Only use for test and/or make sure to inject all dao's and other services
    86      *
     89     * user. Only use for test and/or make sure to inject all dao's and other
     90     * services
     91     *
    8792     * @param userId
    88      * User id of the user to create registry for. Pass null for
    89      * public
     93     *            User id of the user to create registry for. Pass null for
     94     *            public
    9095     */
    9196    public ComponentRegistryDbImpl(ComponentStatus status, Owner owner) {
     
    95100
    96101    @Override
    97     public List<ProfileDescription> getProfileDescriptions() throws ComponentRegistryException {
     102    public List<ProfileDescription> getProfileDescriptions()
     103            throws ComponentRegistryException {
    98104        try {
    99105            switch (registryStatus) {
    100                 // TODO: support other status types
    101                 case PRIVATE:
    102                     if (registryOwner == null) {
    103                         throw new ComponentRegistryException("Private workspace without owner!");
    104                     }
    105                     // TODO: Support group space
    106                     return profileDescriptionDao.getUserspaceDescriptions(registryOwner.getId());
    107                 case PUBLISHED:
    108                     return profileDescriptionDao.getPublicProfileDescriptions();
    109                 default:
    110                     throw new ComponentRegistryException("Unsupported status type" + registryStatus);
    111             }
    112         } catch (DataAccessException ex) {
    113             throw new ComponentRegistryException("Database access error while trying to get profile descriptions", ex);
    114         }
    115     }
    116 
    117     @Override
    118     public ProfileDescription getProfileDescription(String id) throws ComponentRegistryException {
     106            // TODO: support other status types
     107            case PRIVATE:
     108                if (registryOwner == null) {
     109                    throw new ComponentRegistryException(
     110                            "Private workspace without owner!");
     111                }
     112                // TODO: Support group space
     113                return profileDescriptionDao
     114                        .getUserspaceDescriptions(registryOwner.getId());
     115            case PUBLISHED:
     116                return profileDescriptionDao.getPublicProfileDescriptions();
     117            default:
     118                throw new ComponentRegistryException("Unsupported status type"
     119                        + registryStatus);
     120            }
     121        } catch (DataAccessException ex) {
     122            throw new ComponentRegistryException(
     123                    "Database access error while trying to get profile descriptions",
     124                    ex);
     125        }
     126    }
     127
     128    @Override
     129    public ProfileDescription getProfileDescription(String id)
     130            throws ComponentRegistryException {
    119131        try {
    120132            return profileDescriptionDao.getByCmdId(id, getUserId());
    121133        } catch (DataAccessException ex) {
    122             throw new ComponentRegistryException("Database access error while trying to get profile description", ex);
    123         }
    124     }
    125 
    126     @Override
    127     public List<ComponentDescription> getComponentDescriptions() throws ComponentRegistryException {
     134            throw new ComponentRegistryException(
     135                    "Database access error while trying to get profile description",
     136                    ex);
     137        }
     138    }
     139
     140    @Override
     141    public List<ComponentDescription> getComponentDescriptions()
     142            throws ComponentRegistryException {
    128143        try {
    129144            if (isPublic()) {
    130145                return componentDescriptionDao.getPublicComponentDescriptions();
    131146            } else {
    132                 return componentDescriptionDao.getUserspaceDescriptions(getUserId());
    133             }
    134         } catch (DataAccessException ex) {
    135             throw new ComponentRegistryException("Database access error while trying to get component descriptions", ex);
    136         }
    137     }
    138 
    139     @Override
    140     public ComponentDescription getComponentDescription(String id) throws ComponentRegistryException {
     147                return componentDescriptionDao
     148                        .getUserspaceDescriptions(getUserId());
     149            }
     150        } catch (DataAccessException ex) {
     151            throw new ComponentRegistryException(
     152                    "Database access error while trying to get component descriptions",
     153                    ex);
     154        }
     155    }
     156
     157    @Override
     158    public ComponentDescription getComponentDescription(String id)
     159            throws ComponentRegistryException {
    141160        try {
    142161            return componentDescriptionDao.getByCmdId(id, getUserId());
    143162        } catch (DataAccessException ex) {
    144             throw new ComponentRegistryException("Database access error while trying to get component description", ex);
    145         }
    146     }
    147 
    148     @Override
    149     public List<Comment> getCommentsInProfile(String profileId, Principal principal) throws ComponentRegistryException {
     163            throw new ComponentRegistryException(
     164                    "Database access error while trying to get component description",
     165                    ex);
     166        }
     167    }
     168
     169    @Override
     170    public List<Comment> getCommentsInProfile(String profileId,
     171            Principal principal) throws ComponentRegistryException {
    150172        try {
    151173            if (profileDescriptionDao.isInRegistry(profileId, getUserId())) {
    152                 final List<Comment> commentsFromProfile = commentsDao.getCommentsFromProfile(profileId);
     174                final List<Comment> commentsFromProfile = commentsDao
     175                        .getCommentsFromProfile(profileId);
    153176                setCanDeleteInComments(commentsFromProfile, principal);
    154177                return commentsFromProfile;
    155178            } else {
    156179                // Profile does not exist (at least not in this registry)
    157                 throw new ComponentRegistryException("Profile " + profileId + " does not exist in specified registry");
    158             }
    159         } catch (DataAccessException ex) {
    160             throw new ComponentRegistryException("Database access error while trying to get list of comments from profile", ex);
    161         }
    162     }
    163 
    164     @Override
    165     public Comment getSpecifiedCommentInProfile(String profileId, String commentId, Principal principal) throws ComponentRegistryException {
    166         try {
    167             Comment comment = commentsDao.getSpecifiedCommentFromProfile(commentId);
     180                throw new ComponentRegistryException("Profile " + profileId
     181                        + " does not exist in specified registry");
     182            }
     183        } catch (DataAccessException ex) {
     184            throw new ComponentRegistryException(
     185                    "Database access error while trying to get list of comments from profile",
     186                    ex);
     187        }
     188    }
     189
     190    @Override
     191    public Comment getSpecifiedCommentInProfile(String profileId,
     192            String commentId, Principal principal)
     193            throws ComponentRegistryException {
     194        try {
     195            Comment comment = commentsDao
     196                    .getSpecifiedCommentFromProfile(commentId);
    168197            if (comment != null
    169198                    && profileId.equals(comment.getProfileDescriptionId())
    170                     && profileDescriptionDao.isInRegistry(comment.getProfileDescriptionId(), getUserId())) {
    171                 setCanDeleteInComments(Collections.singleton(comment), principal);
     199                    && profileDescriptionDao.isInRegistry(
     200                            comment.getProfileDescriptionId(), getUserId())) {
     201                setCanDeleteInComments(Collections.singleton(comment),
     202                        principal);
    172203                return comment;
    173204            } else {
    174205                // Comment exists in DB, but profile is not in this registry
    175                 throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
    176             }
    177         } catch (DataAccessException ex) {
    178             throw new ComponentRegistryException("Database access error while trying to get comment from profile", ex);
    179         }
    180     }
    181 
    182     @Override
    183     public List<Comment> getCommentsInComponent(String componentId, Principal principal) throws ComponentRegistryException {
     206                throw new ComponentRegistryException("Comment " + commentId
     207                        + " cannot be found in specified registry");
     208            }
     209        } catch (DataAccessException ex) {
     210            throw new ComponentRegistryException(
     211                    "Database access error while trying to get comment from profile",
     212                    ex);
     213        }
     214    }
     215
     216    @Override
     217    public List<Comment> getCommentsInComponent(String componentId,
     218            Principal principal) throws ComponentRegistryException {
    184219        try {
    185220            if (componentDescriptionDao.isInRegistry(componentId, getUserId())) {
    186                 final List<Comment> commentsFromComponent = commentsDao.getCommentsFromComponent(componentId);
     221                final List<Comment> commentsFromComponent = commentsDao
     222                        .getCommentsFromComponent(componentId);
    187223                setCanDeleteInComments(commentsFromComponent, principal);
    188224                return commentsFromComponent;
    189225            } else {
    190226                // Component does not exist (at least not in this registry)
    191                 throw new ComponentRegistryException("Component " + componentId + " does not exist in specified registry");
    192             }
    193         } catch (DataAccessException ex) {
    194             throw new ComponentRegistryException("Database access error while trying to get list of comments from component", ex);
    195         }
    196     }
    197 
    198     @Override
    199     public Comment getSpecifiedCommentInComponent(String componentId, String commentId, Principal principal) throws ComponentRegistryException {
    200         try {
    201             Comment comment = commentsDao.getSpecifiedCommentFromComponent(commentId);
     227                throw new ComponentRegistryException("Component " + componentId
     228                        + " does not exist in specified registry");
     229            }
     230        } catch (DataAccessException ex) {
     231            throw new ComponentRegistryException(
     232                    "Database access error while trying to get list of comments from component",
     233                    ex);
     234        }
     235    }
     236
     237    @Override
     238    public Comment getSpecifiedCommentInComponent(String componentId,
     239            String commentId, Principal principal)
     240            throws ComponentRegistryException {
     241        try {
     242            Comment comment = commentsDao
     243                    .getSpecifiedCommentFromComponent(commentId);
    202244            if (comment != null
    203245                    && componentId.equals(comment.getComponentDescriptionId())
    204                     && componentDescriptionDao.isInRegistry(comment.getComponentDescriptionId(), getUserId())) {
    205                 setCanDeleteInComments(Collections.singleton(comment), principal);
     246                    && componentDescriptionDao.isInRegistry(
     247                            comment.getComponentDescriptionId(), getUserId())) {
     248                setCanDeleteInComments(Collections.singleton(comment),
     249                        principal);
    206250                return comment;
    207251            } else {
    208                 // Comment does not exists in DB or component is not in this registry
    209                 throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry for specified component");
    210             }
    211         } catch (DataAccessException ex) {
    212             throw new ComponentRegistryException("Database access error while trying to get comment from component", ex);
    213         }
    214     }
    215 
    216     /**
    217      * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all comments in the provided collection for the perspective of
    218      * the specified principal.
    219      * Comment owners (determined by {@link Comment#getUserId() }) and admins can delete, others cannot.
    220      *
    221      * @param comments comments to configure
    222      * @param principal user to configure for
     252                // Comment does not exists in DB or component is not in this
     253                // registry
     254                throw new ComponentRegistryException(
     255                        "Comment "
     256                                + commentId
     257                                + " cannot be found in specified registry for specified component");
     258            }
     259        } catch (DataAccessException ex) {
     260            throw new ComponentRegistryException(
     261                    "Database access error while trying to get comment from component",
     262                    ex);
     263        }
     264    }
     265
     266    /**
     267     * Sets the {@link Comment#setCanDelete(boolean) canDelete} property on all
     268     * comments in the provided collection for the perspective of the specified
     269     * principal. Comment owners (determined by {@link Comment#getUserId() }) and
     270     * admins can delete, others cannot.
     271     *
     272     * @param comments
     273     *            comments to configure
     274     * @param principal
     275     *            user to configure for
    223276     * @see Comment#isCanDelete()
    224277     */
    225     private void setCanDeleteInComments(Collection<Comment> comments, Principal principal) {
     278    private void setCanDeleteInComments(Collection<Comment> comments,
     279            Principal principal) {
    226280        if (principal != null && principal.getName() != null) {
    227             final RegistryUser registryUser = userDao.getByPrincipalName(principal.getName());
    228             final String registryUserId = registryUser == null ? null : registryUser.getId().toString();
    229             final boolean isAdmin = registryUser != null && configuration.isAdminUser(principal);
     281            final RegistryUser registryUser = userDao
     282                    .getByPrincipalName(principal.getName());
     283            final String registryUserId = registryUser == null ? null
     284                    : registryUser.getId().toString();
     285            final boolean isAdmin = registryUser != null
     286                    && configuration.isAdminUser(principal);
    230287            for (Comment comment : comments) {
    231                 comment.setCanDelete(isAdmin || comment.getUserId().equals(registryUserId));
    232             }
    233         }
    234     }
    235 
    236     @Override
    237     public CMDComponentSpec getMDProfile(String id) throws ComponentRegistryException {
     288                comment.setCanDelete(isAdmin
     289                        || comment.getUserId().equals(registryUserId));
     290            }
     291        }
     292    }
     293
     294    @Override
     295    public CMDComponentSpec getMDProfile(String id)
     296            throws ComponentRegistryException {
    238297        if (inWorkspace(profileDescriptionDao, id)) {
    239298            CMDComponentSpec result = profilesCache.get(id);
     
    245304        } else {
    246305            // May exist, but not in this workspace
    247             LOG.debug("Could not find profile '{}' in registry '{}'", new Object[]{id, this.toString()});
     306            LOG.debug("Could not find profile '{}' in registry '{}'",
     307                    new Object[] { id, this.toString() });
    248308            return null;
    249309        }
    250310    }
    251311
    252     public CMDComponentSpec getUncachedMDProfile(String id) throws ComponentRegistryException {
     312    public CMDComponentSpec getUncachedMDProfile(String id)
     313            throws ComponentRegistryException {
    253314        try {
    254315            return getUncachedMDComponent(id, profileDescriptionDao);
    255316        } catch (DataAccessException ex) {
    256             throw new ComponentRegistryException("Database access error while trying to get profile", ex);
    257         }
    258     }
    259 
    260     @Override
    261     public CMDComponentSpec getMDComponent(String id) throws ComponentRegistryException {
     317            throw new ComponentRegistryException(
     318                    "Database access error while trying to get profile", ex);
     319        }
     320    }
     321
     322    @Override
     323    public CMDComponentSpec getMDComponent(String id)
     324            throws ComponentRegistryException {
    262325        if (inWorkspace(componentDescriptionDao, id)) {
    263326            CMDComponentSpec result = componentsCache.get(id);
     
    269332        } else {
    270333            // May exist, but not in this workspace
    271             LOG.info("Could not find component '{}' was in registry '{}'", new Object[]{id, this.toString()});
     334            LOG.info("Could not find component '{}' was in registry '{}'",
     335                    new Object[] { id, this.toString() });
    272336            return null;
    273337        }
    274338    }
    275339
    276     public CMDComponentSpec getUncachedMDComponent(String id) throws ComponentRegistryException {
     340    public CMDComponentSpec getUncachedMDComponent(String id)
     341            throws ComponentRegistryException {
    277342        try {
    278343            return getUncachedMDComponent(id, componentDescriptionDao);
    279344        } catch (DataAccessException ex) {
    280             throw new ComponentRegistryException("Database access error while trying to get component", ex);
     345            throw new ComponentRegistryException(
     346                    "Database access error while trying to get component", ex);
    281347        }
    282348    }
     
    289355            // Convert principal name to user record id
    290356            Number uid = convertUserInDescription(description);
    291             getDaoForDescription(description).insertDescription(description, xml, isPublic(), uid);
     357            getDaoForDescription(description).insertDescription(description,
     358                    xml, isPublic(), uid);
    292359            invalidateCache(description);
    293360            return 0;
     
    305372
    306373    @Override
    307     public int registerComment(Comment comment, String principalName) throws ComponentRegistryException {
    308         try {
    309             if (comment.getComponentDescriptionId() != null && componentDescriptionDao.isInRegistry(comment.getComponentDescriptionId(), getUserId())
    310                     || comment.getProfileDescriptionId() != null && profileDescriptionDao.isInRegistry(comment.getProfileDescriptionId(), getUserId())) {
     374    public int registerComment(Comment comment, String principalName)
     375            throws ComponentRegistryException {
     376        try {
     377            if (comment.getComponentDescriptionId() != null
     378                    && componentDescriptionDao.isInRegistry(
     379                            comment.getComponentDescriptionId(), getUserId())
     380                    || comment.getProfileDescriptionId() != null
     381                    && profileDescriptionDao.isInRegistry(
     382                            comment.getProfileDescriptionId(), getUserId())) {
    311383                // Convert principal name to user record id
    312384                Number uid = convertUserIdInComment(comment, principalName);
     
    316388                comment.setId(commentId.toString());
    317389            } else {
    318                 throw new ComponentRegistryException("Cannot insert comment into this registry. Unknown profileId or componentId");
     390                throw new ComponentRegistryException(
     391                        "Cannot insert comment into this registry. Unknown profileId or componentId");
    319392            }
    320393            return 0;
     
    329402     * an id for later reference. If none is set and this is a user's workspace,
    330403     * set from that user's id.
    331      *
    332      * It also sets the name in the description according to the display name in the database.
    333      *
     404     *
     405     * It also sets the name in the description according to the display name in
     406     * the database.
     407     *
    334408     * @param description
    335      * Description containing principle name as userId
     409     *            Description containing principle name as userId
    336410     * @return Id (from database)
    337411     * @throws DataAccessException
    338412     */
    339     private Number convertUserInDescription(AbstractDescription description) throws DataAccessException {
     413    private Number convertUserInDescription(AbstractDescription description)
     414            throws DataAccessException {
    340415        Number uid = null;
    341416        String name = null;
    342417        if (description.getUserId() != null) {
    343             RegistryUser user = userDao.getByPrincipalName(description.getUserId());
     418            RegistryUser user = userDao.getByPrincipalName(description
     419                    .getUserId());
    344420            if (user != null) {
    345421                uid = user.getId();
     
    362438     * an id for later reference. If none is set and this is a user's workspace,
    363439     * set from that user's id.
    364      *
     440     * 
    365441     * @param comment
    366      * Comment containing principle name as userId
     442     *            Comment containing principle name as userId
    367443     * @return Id (from database)
    368444     * @throws DataAccessException
    369445     */
    370     private Number convertUserIdInComment(Comment comment, String principalName) throws DataAccessException, ComponentRegistryException {
     446    private Number convertUserIdInComment(Comment comment, String principalName)
     447            throws DataAccessException, ComponentRegistryException {
    371448        if (principalName != null) {
    372449            RegistryUser user = userDao.getByPrincipalName(principalName);
     
    374451                Number id = user.getId();
    375452                if (id != null) {
    376                     // Set user id in comment for convenience of calling method 
     453                    // Set user id in comment for convenience of calling method
    377454                    comment.setUserId(id.toString());
    378455                    // Set name to user's preferred display name
     
    380457                    return id;
    381458                } else {
    382                     throw new ComponentRegistryException("Cannot find user with principal name: " + principalName);
     459                    throw new ComponentRegistryException(
     460                            "Cannot find user with principal name: "
     461                                    + principalName);
    383462                }
    384463            }
     
    388467
    389468    @Override
    390     public int update(AbstractDescription description, CMDComponentSpec spec, Principal principal, boolean forceUpdate) {
     469    public int update(AbstractDescription description, CMDComponentSpec spec,
     470            Principal principal, boolean forceUpdate) {
    391471        try {
    392472            checkAuthorisation(description, principal);
    393473            checkAge(description, principal);
    394             // For public components, check if used in other components or profiles (unless forced)
     474            // For public components, check if used in other components or
     475            // profiles (unless forced)
    395476            if (!forceUpdate && this.isPublic() && !description.isProfile()) {
    396477                checkStillUsed(description.getId());
    397478            }
    398             AbstractDescriptionDao<?> dao = getDaoForDescription(description);
    399             dao.updateDescription(getIdForDescription(description), description, componentSpecToString(spec));
     479            IAbstractDescriptionDao<?> dao = getDaoForDescription(description);
     480            dao.updateDescription(getIdForDescription(description),
     481                    description, componentSpecToString(spec));
    400482            invalidateCache(description);
    401483            return 0;
     
    422504
    423505    @Override
    424     public int publish(AbstractDescription desc, CMDComponentSpec spec, Principal principal) {
     506    public int publish(AbstractDescription desc, CMDComponentSpec spec,
     507            Principal principal) {
    425508        int result = 0;
    426         AbstractDescriptionDao<?> dao = getDaoForDescription(desc);
    427         if (!isPublic()) { // if already in public workspace there is nothing todo
     509        IAbstractDescriptionDao<?> dao = getDaoForDescription(desc);
     510        if (!isPublic()) { // if already in public workspace there is nothing
     511                           // todo
    428512            desc.setHref(AbstractDescription.createPublicHref(desc.getHref()));
    429513            Number id = getIdForDescription(desc);
     
    448532
    449533    @Override
    450     public void getMDProfileAsXml(String profileId, OutputStream output) throws ComponentRegistryException {
    451         CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
     534    public void getMDProfileAsXml(String profileId, OutputStream output)
     535            throws ComponentRegistryException {
     536        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl
     537                .expandProfile(profileId, this);
    452538        writeXml(expandedSpec, output);
    453539    }
    454540
    455541    @Override
    456     public void getMDProfileAsXsd(String profileId, OutputStream outputStream) throws ComponentRegistryException {
    457         CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandProfile(profileId, this);
     542    public void getMDProfileAsXsd(String profileId, OutputStream outputStream)
     543            throws ComponentRegistryException {
     544        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl
     545                .expandProfile(profileId, this);
    458546        writeXsd(expandedSpec, outputStream);
    459547    }
    460548
    461549    @Override
    462     public void getMDComponentAsXml(String componentId, OutputStream output) throws ComponentRegistryException {
    463         CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
     550    public void getMDComponentAsXml(String componentId, OutputStream output)
     551            throws ComponentRegistryException {
     552        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl
     553                .expandComponent(componentId, this);
    464554        writeXml(expandedSpec, output);
    465555    }
    466556
    467557    @Override
    468     public void getMDComponentAsXsd(String componentId, OutputStream outputStream) throws ComponentRegistryException {
    469         CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl.expandComponent(componentId, this);
     558    public void getMDComponentAsXsd(String componentId,
     559            OutputStream outputStream) throws ComponentRegistryException {
     560        CMDComponentSpec expandedSpec = CMDComponentSpecExpanderDbImpl
     561                .expandComponent(componentId, this);
    470562        writeXsd(expandedSpec, outputStream);
    471563    }
    472564
    473565    @Override
    474     public void deleteMDProfile(String profileId, Principal principal) throws UserUnauthorizedException, DeleteFailedException,
     566    public void deleteMDProfile(String profileId, Principal principal)
     567            throws UserUnauthorizedException, DeleteFailedException,
    475568            ComponentRegistryException {
    476569        ProfileDescription desc = getProfileDescription(profileId);
     
    482575                invalidateCache(desc);
    483576            } catch (DataAccessException ex) {
    484                 throw new DeleteFailedException("Database access error while trying to delete profile", ex);
    485             }
    486         }
    487     }
    488 
    489     @Override
    490     public void deleteMDComponent(String componentId, Principal principal, boolean forceDelete) throws UserUnauthorizedException,
     577                throw new DeleteFailedException(
     578                        "Database access error while trying to delete profile",
     579                        ex);
     580            }
     581        }
     582    }
     583
     584    @Override
     585    public void deleteMDComponent(String componentId, Principal principal,
     586            boolean forceDelete) throws UserUnauthorizedException,
    491587            DeleteFailedException, ComponentRegistryException {
    492         ComponentDescription desc = componentDescriptionDao.getByCmdId(componentId);
     588        ComponentDescription desc = componentDescriptionDao
     589                .getByCmdId(componentId);
    493590        if (desc != null) {
    494591            try {
     
    502599                invalidateCache(desc);
    503600            } catch (DataAccessException ex) {
    504                 throw new DeleteFailedException("Database access error while trying to delete component", ex);
    505             }
    506         }
    507     }
    508 
    509     /**
    510      *
     601                throw new DeleteFailedException(
     602                        "Database access error while trying to delete component",
     603                        ex);
     604            }
     605        }
     606    }
     607
     608    /**
     609     *
    511610     * @return whether this is the public registry
    512      * @deprecated use {@link #getStatus() } to check if this is the {@link ComponentStatus#PUBLISHED public registry}
     611     * @deprecated use {@link #getStatus() } to check if this is the
     612     *             {@link ComponentStatus#PUBLISHED public registry}
    513613     */
    514614    @Override
     
    547647    /**
    548648     * Sets status and owner of this registry
    549      *
    550      * @param status new status for registry
    551      * @param owner new owner for registry
     649     *
     650     * @param status
     651     *            new status for registry
     652     * @param owner
     653     *            new owner for registry
    552654     */
    553655    public void setStatus(ComponentStatus status, Owner owner) {
     
    573675    }
    574676
    575     private AbstractDescriptionDao<?> getDaoForDescription(AbstractDescription description) {
    576         return description.isProfile() ? profileDescriptionDao : componentDescriptionDao;
     677    private IAbstractDescriptionDao<?> getDaoForDescription(
     678            AbstractDescription description) {
     679        return description.isProfile() ? profileDescriptionDao
     680                : componentDescriptionDao;
    577681    }
    578682
     
    580684     * Looks up description on basis of CMD Id. This will also check if such a
    581685     * record even exists.
    582      *
     686     * 
    583687     * @param description
    584      * Description to look up
     688     *            Description to look up
    585689     * @return Database id for description
    586690     * @throws IllegalArgumentException
    587      * If description with non-existing id is passed
    588      */
    589     private Number getIdForDescription(AbstractDescription description) throws IllegalArgumentException {
     691     *             If description with non-existing id is passed
     692     */
     693    private Number getIdForDescription(AbstractDescription description)
     694            throws IllegalArgumentException {
    590695        Number dbId = null;
    591         AbstractDescriptionDao<?> dao = getDaoForDescription(description);
     696        IAbstractDescriptionDao<?> dao = getDaoForDescription(description);
    592697        try {
    593698            dbId = dao.getDbId(description.getId());
    594699        } catch (DataAccessException ex) {
    595             LOG.error("Error getting dbId for component with id " + description.getId(), ex);
     700            LOG.error(
     701                    "Error getting dbId for component with id "
     702                            + description.getId(), ex);
    596703        }
    597704        if (dbId == null) {
    598             throw new IllegalArgumentException("Could not get database Id for description");
     705            throw new IllegalArgumentException(
     706                    "Could not get database Id for description");
    599707        } else {
    600708            return dbId;
     
    602710    }
    603711
    604     private String componentSpecToString(CMDComponentSpec spec) throws UnsupportedEncodingException, JAXBException {
     712    private String componentSpecToString(CMDComponentSpec spec)
     713            throws UnsupportedEncodingException, JAXBException {
    605714        ByteArrayOutputStream os = new ByteArrayOutputStream();
    606715        getMarshaller().marshal(spec, os);
     
    609718    }
    610719
    611     private CMDComponentSpec getUncachedMDComponent(String id, AbstractDescriptionDao dao) {
     720    private CMDComponentSpec getUncachedMDComponent(String id,
     721            IAbstractDescriptionDao dao) {
    612722        String xml = dao.getContent(false, id);
    613723        if (xml != null) {
    614724            try {
    615725                InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    616                 return getMarshaller().unmarshal(CMDComponentSpec.class, is, null);
     726                return getMarshaller().unmarshal(CMDComponentSpec.class, is,
     727                        null);
    617728
    618729            } catch (JAXBException ex) {
     
    625736    }
    626737
    627     private void checkAuthorisation(AbstractDescription desc, Principal principal) throws UserUnauthorizedException {
    628         if (!isOwnerOfDescription(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
    629             throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
    630                     + "' is not the creator (nor an administrator) of the " + (desc.isProfile() ? "profile" : "component") + "(" + desc
     738    private void checkAuthorisation(AbstractDescription desc,
     739            Principal principal) throws UserUnauthorizedException {
     740        if (!isOwnerOfDescription(desc, principal.getName())
     741                && !configuration.isAdminUser(principal)) {
     742            throw new UserUnauthorizedException("Unauthorized operation user '"
     743                    + principal.getName()
     744                    + "' is not the creator (nor an administrator) of the "
     745                    + (desc.isProfile() ? "profile" : "component") + "(" + desc
    631746                    + ").");
    632747        }
    633748    }
    634749
    635     private void checkAuthorisationComment(Comment desc, Principal principal) throws UserUnauthorizedException {
    636         if (!isOwnerOfComment(desc, principal.getName()) && !configuration.isAdminUser(principal)) {
    637             throw new UserUnauthorizedException("Unauthorized operation user '" + principal.getName()
    638                     + "' is not the creator (nor an administrator) of the " + (desc.getId()) + "(" + desc
    639                     + ").");
    640         }
    641     }
    642 
    643     private boolean isOwnerOfDescription(AbstractDescription desc, String principalName) {
    644         String owner = getDaoForDescription(desc).getOwnerPrincipalName(getIdForDescription(desc));
     750    private void checkAuthorisationComment(Comment desc, Principal principal)
     751            throws UserUnauthorizedException {
     752        if (!isOwnerOfComment(desc, principal.getName())
     753                && !configuration.isAdminUser(principal)) {
     754            throw new UserUnauthorizedException("Unauthorized operation user '"
     755                    + principal.getName()
     756                    + "' is not the creator (nor an administrator) of the "
     757                    + (desc.getId()) + "(" + desc + ").");
     758        }
     759    }
     760
     761    private boolean isOwnerOfDescription(AbstractDescription desc,
     762            String principalName) {
     763        String owner = getDaoForDescription(desc).getOwnerPrincipalName(
     764                getIdForDescription(desc));
    645765        return owner != null // If owner is null, no one can be owner
    646766                && principalName.equals(owner);
     
    648768
    649769    private boolean isOwnerOfComment(Comment com, String principalName) {
    650         String owner = commentsDao.getOwnerPrincipalName(Integer.parseInt(com.getId()));
     770        String owner = commentsDao.getOwnerPrincipalName(Integer.parseInt(com
     771                .getId()));
    651772        return owner != null // If owner is null, no one can be owner
    652773                && principalName.equals(owner);
    653774    }
    654775
    655     private void checkAge(AbstractDescription desc, Principal principal) throws DeleteFailedException {
     776    private void checkAge(AbstractDescription desc, Principal principal)
     777            throws DeleteFailedException {
    656778        if (isPublic() && !configuration.isAdminUser(principal)) {
    657779            try {
    658                 Date regDate = AbstractDescription.getDate(desc.getRegistrationDate());
     780                Date regDate = AbstractDescription.getDate(desc
     781                        .getRegistrationDate());
    659782                Calendar calendar = Calendar.getInstance();
    660783                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
     
    662785                    throw new DeleteFailedException(
    663786                            "The "
    664                             + (desc.isProfile() ? "Profile" : "Component")
    665                             + " is more then a month old and cannot be deleted anymore. It might have been used to create metadata, deleting it would invalidate that metadata.");
     787                                    + (desc.isProfile() ? "Profile"
     788                                            : "Component")
     789                                    + " is more then a month old and cannot be deleted anymore. It might have been used to create metadata, deleting it would invalidate that metadata.");
    666790                }
    667791            } catch (ParseException e) {
     
    671795    }
    672796
    673     private boolean inWorkspace(AbstractDescriptionDao<?> dao, String cmdId) {
     797    private boolean inWorkspace(IAbstractDescriptionDao<?> dao, String cmdId) {
    674798        if (isPublic()) {
    675799            return dao.isPublic(cmdId);
     
    699823
    700824    @Override
    701     public void deleteComment(String commentId, Principal principal) throws IOException,
    702             ComponentRegistryException, UserUnauthorizedException, DeleteFailedException {
     825    public void deleteComment(String commentId, Principal principal)
     826            throws IOException, ComponentRegistryException,
     827            UserUnauthorizedException, DeleteFailedException {
    703828        try {
    704829            Comment comment = commentsDao.getById(Integer.parseInt(commentId));
    705830            if (comment != null
    706                     // Comment must have an existing (in this registry) componentId or profileId
    707                     && (comment.getComponentDescriptionId() != null && componentDescriptionDao.isInRegistry(comment.getComponentDescriptionId(), getUserId())
    708                     || comment.getProfileDescriptionId() != null && profileDescriptionDao.isInRegistry(comment.getProfileDescriptionId(), getUserId()))) {
     831                    // Comment must have an existing (in this registry)
     832                    // componentId or profileId
     833                    && (comment.getComponentDescriptionId() != null
     834                            && componentDescriptionDao.isInRegistry(
     835                                    comment.getComponentDescriptionId(),
     836                                    getUserId()) || comment
     837                            .getProfileDescriptionId() != null
     838                            && profileDescriptionDao.isInRegistry(
     839                                    comment.getProfileDescriptionId(),
     840                                    getUserId()))) {
    709841                checkAuthorisationComment(comment, principal);
    710842                commentsDao.deleteComment(comment);
    711843            } else {
    712844                // Comment exists in DB, but component is not in this registry
    713                 throw new ComponentRegistryException("Comment " + commentId + " cannot be found in specified registry");
    714             }
    715         } catch (DataAccessException ex) {
    716             throw new DeleteFailedException("Database access error while trying to delete component", ex);
     845                throw new ComponentRegistryException("Comment " + commentId
     846                        + " cannot be found in specified registry");
     847            }
     848        } catch (DataAccessException ex) {
     849            throw new DeleteFailedException(
     850                    "Database access error while trying to delete component",
     851                    ex);
    717852        } catch (NumberFormatException ex) {
    718             throw new DeleteFailedException("Illegal comment ID, cannot parse integer", ex);
     853            throw new DeleteFailedException(
     854                    "Illegal comment ID, cannot parse integer", ex);
    719855        }
    720856    }
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImpl.java

    r3036 r3449  
    2222 * ComponentRegistryDbImpl implementation of ComponentRegistry for accessing the
    2323 * registry
    24  *
     24 * 
    2525 * @author Twan Goosen <twan.goosen@mpi.nl>
     26 * @author George.Georgovassilis@mpi.nl
    2627 */
    2728public class ComponentRegistryFactoryDbImpl implements ComponentRegistryFactory {
    2829
    29     private final static Logger LOG = LoggerFactory.getLogger(ComponentRegistryFactoryDbImpl.class);
     30    private final static Logger LOG = LoggerFactory
     31            .getLogger(ComponentRegistryFactoryDbImpl.class);
    3032    @Autowired
    3133    private Configuration configuration;
     
    3335    private ComponentRegistryBeanFactory componentRegistryBeanFactory;
    3436    @Autowired
    35     private UserDao userDao;
     37    private IUserDAO userDao;
    3638    private ComponentRegistry publicComponentRegistry = null;
    3739
     
    5355
    5456    @Override
    55     public ComponentRegistry getComponentRegistry(ComponentStatus status, Owner owner, UserCredentials credentials) throws UserUnauthorizedException {
     57    public ComponentRegistry getComponentRegistry(ComponentStatus status,
     58            Owner owner, UserCredentials credentials)
     59            throws UserUnauthorizedException {
    5660        switch (status) {
    57             case PRIVATE:
    58                 return getPrivateRegistry(owner, credentials);
    59             case PUBLISHED:
    60                 return getPublicRegistry();
    61             default:
    62                 // TODO: Add support for other status types
    63                 throw new UnsupportedOperationException("Unsupported component status" + status);
     61        case PRIVATE:
     62            return getPrivateRegistry(owner, credentials);
     63        case PUBLISHED:
     64            return getPublicRegistry();
     65        default:
     66            // TODO: Add support for other status types
     67            throw new UnsupportedOperationException(
     68                    "Unsupported component status" + status);
    6469        }
    6570    }
    6671
    67     private ComponentRegistry getPrivateRegistry(Owner owner, UserCredentials credentials) throws IllegalArgumentException, DataAccessException, UserUnauthorizedException {
     72    private ComponentRegistry getPrivateRegistry(Owner owner,
     73            UserCredentials credentials) throws IllegalArgumentException,
     74            DataAccessException, UserUnauthorizedException {
    6875        if (owner == null || owner instanceof OwnerUser) {
    6976            RegistryUser user = getOrCreateUser(credentials);
    7077            if (user != null) {
    7178                if (owner != null && !user.getId().equals(owner.getId())) {
    72                     throw new UserUnauthorizedException("User cannot access other user's private registry");
     79                    throw new UserUnauthorizedException(
     80                            "User cannot access other user's private registry");
    7381                }
    7482
     
    8088                }
    8189            } else {
    82                 throw new UserUnauthorizedException("No user credentials available cannot load userspace.");
     90                throw new UserUnauthorizedException(
     91                        "No user credentials available cannot load userspace.");
    8392            }
    8493        } else {
    8594            // TODO: Support group owners
    86             throw new UnsupportedOperationException("Group owners not supported");
     95            throw new UnsupportedOperationException(
     96                    "Group owners not supported");
    8797        }
    8898    }
    8999
    90100    @Override
    91     public ComponentRegistry getOtherUserComponentRegistry(Principal adminPrincipal, ComponentStatus status, Owner owner) {
     101    public ComponentRegistry getOtherUserComponentRegistry(
     102            Principal adminPrincipal, ComponentStatus status, Owner owner) {
    92103        try {
    93104            RegistryUser user;
     
    96107            } else {
    97108                // TODO: Implement for groups
    98                 throw new UnsupportedOperationException("Groups not implemented yet");
     109                throw new UnsupportedOperationException(
     110                        "Groups not implemented yet");
    99111            }
    100112            ComponentRegistry result = null;
     
    103115                    result = getNewComponentRegistryForUser(user.getId());
    104116                } else {
    105                     LOG.info("{} not found in list of {}", adminPrincipal.getName(), configuration.getAdminUsersArray().length);
    106                     throw new IllegalArgumentException("User " + adminPrincipal.getName() + " is not admin user cannot load userspace.");
     117                    LOG.info("{} not found in list of {}",
     118                            adminPrincipal.getName(),
     119                            configuration.getAdminUsersArray().length);
     120                    throw new IllegalArgumentException("User "
     121                            + adminPrincipal.getName()
     122                            + " is not admin user cannot load userspace.");
    107123                }
    108124            }
     
    123139
    124140    private ComponentRegistry getNewComponentRegistryForUser(Number userId) {
    125         ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
     141        ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory
     142                .getNewComponentRegistry();
    126143        if (userId != null) {
    127144            // Null means public registry
    128145            // TODO: Make this more explicit
    129             componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(userId));
     146            componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(
     147                    userId));
    130148        }
    131149        return componentRegistry;
     
    134152    @Override
    135153    public RegistryUser getOrCreateUser(UserCredentials credentials) {
    136         if (credentials != null && !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
     154        if (credentials != null
     155                && !ANONYMOUS_USER.equals(credentials.getPrincipalName())) {
    137156            String principalName = credentials.getPrincipalName();
    138157            return getOrCreateUser(principalName, credentials.getDisplayName());
     
    141160    }
    142161
    143     private synchronized RegistryUser getOrCreateUser(String principalName, String displayName) {
     162    private synchronized RegistryUser getOrCreateUser(String principalName,
     163            String displayName) {
    144164        // Try getting it from db
    145165        RegistryUser user = userDao.getByPrincipalName(principalName);
    146166        if (user == null) {
    147             LOG.info("Request to create user with principal name {} and display name {}", new Object[]{principalName, displayName});
     167            LOG.info(
     168                    "Request to create user with principal name {} and display name {}",
     169                    new Object[] { principalName, displayName });
    148170            // Create the new user
    149171            user = new RegistryUser();
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/ProfileDescriptionDao.java

    r1701 r3449  
    33import clarin.cmdi.componentregistry.model.AbstractDescription;
    44import clarin.cmdi.componentregistry.model.ProfileDescription;
     5
    56import java.sql.ResultSet;
    67import java.sql.SQLException;
     
    89import java.util.List;
    910import java.util.Map;
     11
    1012import org.apache.commons.collections.ListUtils;
     13import org.springframework.stereotype.Repository;
    1114
    1215/**
    1316 *
    1417 * @author Twan Goosen <twan.goosen@mpi.nl>
     18 * @author George.Georgovassilis@mpi.nl
    1519 */
    16 public class ProfileDescriptionDao extends AbstractDescriptionDao<ProfileDescription> {
     20@Repository
     21public class ProfileDescriptionDao extends AbstractDescriptionDao<ProfileDescription> implements IProfileDescriptionDAO{
    1722
    1823    public ProfileDescriptionDao() {
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/impl/database/UserDao.java

    r1779 r3449  
    22
    33import clarin.cmdi.componentregistry.model.RegistryUser;
     4
    45import java.sql.ResultSet;
    56import java.sql.SQLException;
     
    78import java.util.List;
    89import java.util.Map;
     10
    911import org.springframework.dao.DataAccessException;
    1012import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
    1113import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
     14import org.springframework.stereotype.Repository;
    1215
    1316/**
    14  *
     17 * 
    1518 * @author Twan Goosen <twan.goosen@mpi.nl>
     19 * @author George.Georgovassilis@mpi.nl
    1620 */
    17 public class UserDao extends ComponentRegistryDao<RegistryUser> {
     21@Repository
     22public class UserDao extends ComponentRegistryDao<RegistryUser> implements IUserDAO{
    1823
    19     private final static String SELECT_BASE = "SELECT " + COLUMN_ID + ", name, principal_name FROM " + TABLE_REGISTRY_USER;
     24        private final static String SELECT_BASE = "SELECT " + COLUMN_ID
     25                        + ", name, principal_name FROM " + TABLE_REGISTRY_USER;
    2026
    21     public List<RegistryUser> getAllUsers() throws DataAccessException {
    22         return getList(SELECT_BASE);
    23     }
     27        public List<RegistryUser> getAllUsers() throws DataAccessException {
     28                return getList(SELECT_BASE);
     29        }
    2430
    25     /**
    26      *
    27      * @param principalName User's principal name
    28      * @return User, if it exists
    29      * @throws DataAccessException
    30      */
    31     public RegistryUser getByPrincipalName(String principalName) throws DataAccessException {
    32         return getFirstOrNull(SELECT_BASE + " WHERE principal_name = ?", principalName);
    33     }
     31        /**
     32         *
     33         * @param principalName
     34         *            User's principal name
     35         * @return User, if it exists
     36         * @throws DataAccessException
     37         */
     38        public RegistryUser getByPrincipalName(String principalName)
     39                        throws DataAccessException {
     40                return getFirstOrNull(SELECT_BASE + " WHERE principal_name = ?",
     41                                principalName);
     42        }
    3443
    35     /**
    36      *
    37      * @param id Database record id (key)
    38      * @return User, if it exists
    39      * @throws DataAccessException
    40      */
    41     public RegistryUser getById(Number id) throws DataAccessException {
    42         return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", id);
    43     }
     44        /**
     45         *
     46         * @param id
     47         *            Database record id (key)
     48         * @return User, if it exists
     49         * @throws DataAccessException
     50         */
     51        public RegistryUser getById(Number id) throws DataAccessException {
     52                return getFirstOrNull(SELECT_BASE + " WHERE " + COLUMN_ID + " = ?", id);
     53        }
    4454
    45     /**
    46      *
    47      * @param user
    48      * @return Record id of the inserted user
    49      * @throws DataAccessException
    50      */
    51     public Number insertUser(RegistryUser user) throws DataAccessException {
    52         SimpleJdbcInsert insert = new SimpleJdbcInsert(getDataSource()).withTableName(TABLE_REGISTRY_USER).usingGeneratedKeyColumns(
    53                 COLUMN_ID);
     55        /**
     56         *
     57         * @param user
     58         * @return Record id of the inserted user
     59         * @throws DataAccessException
     60         */
     61        public Number insertUser(RegistryUser user) throws DataAccessException {
     62                SimpleJdbcInsert insert = new SimpleJdbcInsert(getDataSource())
     63                                .withTableName(TABLE_REGISTRY_USER).usingGeneratedKeyColumns(
     64                                                COLUMN_ID);
    5465
    55         Map<String, Object> params = new HashMap<String, Object>();
    56         params.put("name", user.getName());
    57         params.put("principal_name", user.getPrincipalName());
    58         return insert.executeAndReturnKey(params);
    59     }
     66                Map<String, Object> params = new HashMap<String, Object>();
     67                params.put("name", user.getName());
     68                params.put("principal_name", user.getPrincipalName());
     69                return insert.executeAndReturnKey(params);
     70        }
    6071
    61     /**
    62      * Updates some data stored about the user. At this point only the display name will be updated. ID is taken from 'id' parameter,
    63      * not user object.
    64      * @param id ID of user to update
    65      * @param user object containing new info
    66      */
    67     public void updateUser(Number id, RegistryUser user) throws DataAccessException {
    68         String updateString = String.format("UPDATE %1$s SET name = ? WHERE %2$s = ?", TABLE_REGISTRY_USER, COLUMN_ID);
    69         getSimpleJdbcTemplate().update(updateString, user.getName(), id);
    70     }
    71 
    72     @Override
    73     protected ParameterizedRowMapper<RegistryUser> getRowMapper() {
    74         return rowMapper;
    75     }
    76     private final ParameterizedRowMapper<RegistryUser> rowMapper = new ParameterizedRowMapper<RegistryUser>() {
     72        /**
     73         * Updates some data stored about the user. At this point only the display
     74         * name will be updated. ID is taken from 'id' parameter, not user object.
     75         *
     76         * @param id
     77         *            ID of user to update
     78         * @param user
     79         *            object containing new info
     80         */
     81        public void updateUser(Number id, RegistryUser user)
     82                        throws DataAccessException {
     83                String updateString = String.format(
     84                                "UPDATE %1$s SET name = ? WHERE %2$s = ?", TABLE_REGISTRY_USER,
     85                                COLUMN_ID);
     86                getJdbcTemplate().update(updateString, user.getName(), id);
     87        }
    7788
    7889        @Override
    79         public RegistryUser mapRow(ResultSet rs, int rowNumber) throws SQLException {
    80             RegistryUser user = new RegistryUser();
    81             user.setId(rs.getInt(COLUMN_ID));
    82             user.setName(rs.getString("name"));
    83             user.setPrincipalName(rs.getString("principal_name"));
    84             return user;
     90        protected ParameterizedRowMapper<RegistryUser> getRowMapper() {
     91                return rowMapper;
    8592        }
    86     };
     93
     94        private final ParameterizedRowMapper<RegistryUser> rowMapper = new ParameterizedRowMapper<RegistryUser>() {
     95
     96                @Override
     97                public RegistryUser mapRow(ResultSet rs, int rowNumber)
     98                                throws SQLException {
     99                        RegistryUser user = new RegistryUser();
     100                        user.setId(rs.getInt(COLUMN_ID));
     101                        user.setName(rs.getString("name"));
     102                        user.setPrincipalName(rs.getString("principal_name"));
     103                        return user;
     104                }
     105        };
    87106}
  • ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestService.java

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

    r2767 r3449  
    11<?xml version="1.0" encoding="UTF-8"?>
    2 <!--
    3         Configuration file for ComponentRegistry in NON-SHIBBOLIZED context,
    4         i.e. development or testing environments.
    5 -->
     2<!-- Configuration file for ComponentRegistry in NON-SHIBBOLIZED context,
     3        i.e. development or testing environments. -->
    64
    7 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    8     <display-name>ComponentRegistry</display-name>
    9     <description>Clarin Metadata Component Registry</description>
    10     <listener>
    11         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    12     </listener>
    13     <filter>
    14         <filter-name>characterEncodingFilter</filter-name>
    15         <filter-class>clarin.cmdi.componentregistry.servlet.CharacterEncodingFilter</filter-class>
    16         <init-param>
    17             <param-name>encoding</param-name>
    18             <param-value>UTF-8</param-value>
    19         </init-param>
    20     </filter>
    21     <filter-mapping>
    22         <filter-name>characterEncodingFilter</filter-name>
    23         <url-pattern>/*</url-pattern>
    24     </filter-mapping>
    25     <filter>
    26         <filter-name>wicket.componentregistry</filter-name>
    27         <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
    28         <init-param>
    29             <param-name>applicationClassName</param-name>
    30             <param-value>clarin.cmdi.componentregistry.frontend.AdminApp</param-value>
    31         </init-param>
    32         <init-param>
    33             <param-name>configuration</param-name>
    34             <!--      <param-value>development</param-value>-->
    35             <param-value>deployment</param-value>
    36             <!-- you can override with -Dwicket.configuration=development -->
    37         </init-param>
    38     </filter>
    39     <filter-mapping>
    40         <filter-name>wicket.componentregistry</filter-name>
    41         <url-pattern>/admin/*</url-pattern>
    42     </filter-mapping>
    43     <servlet>
    44         <servlet-name>ComponentRegistry Web Application</servlet-name>
    45         <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    46         <init-param>
    47             <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>
    48             <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig</param-value>
    49         </init-param>
    50         <init-param>
    51             <param-name>com.sun.jersey.config.property.classnames</param-name>
    52             <param-value>com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider;clarin.cmdi.componentregistry.rest.ComponentRegistryRestService</param-value>
    53         </init-param>
    54         <!--    <init-param>-->
    55         <!--      <param-name>com.sun.jersey.config.property.packages</param-name>-->
    56         <!--      <param-value>clarin.cmdi.componentregistry.rest</param-value>-->
    57         <!--    </init-param>-->
    58         <load-on-startup>1</load-on-startup>
    59     </servlet>
    60     <servlet-mapping>
    61         <servlet-name>ComponentRegistry Web Application</servlet-name>
    62         <url-pattern>/rest/*</url-pattern>
    63     </servlet-mapping>
    64     <servlet>
    65         <servlet-name>Isocat Servlet</servlet-name>
    66         <servlet-class>clarin.cmdi.componentregistry.servlet.IsocatServlet</servlet-class>
    67         <load-on-startup>1</load-on-startup>
    68     </servlet>
    69     <servlet-mapping>
    70         <servlet-name>Isocat Servlet</servlet-name>
    71         <url-pattern>/isocat/*</url-pattern>
    72     </servlet-mapping>
    73     <security-constraint>
    74         <display-name>ComponentRegistry web service</display-name>
    75         <web-resource-collection>
    76             <web-resource-name>ComponentRegistry edit</web-resource-name>
    77             <description/>
    78             <url-pattern>/rest/*</url-pattern>
    79             <http-method>DELETE</http-method>
    80             <http-method>PUT</http-method>
    81             <http-method>POST</http-method>
    82         </web-resource-collection>
    83         <auth-constraint>
    84             <role-name>tomcat</role-name>
    85         </auth-constraint>
    86     </security-constraint>
    87     <security-constraint>
    88         <display-name>ComponentRegistry SWF GET</display-name>
    89         <web-resource-collection>
    90             <web-resource-name>ComponentRegistry access</web-resource-name>
    91             <description/>
    92             <url-pattern>/*</url-pattern>
    93             <http-method>GET</http-method>
    94         </web-resource-collection>
    95         <auth-constraint>
    96             <role-name>tomcat</role-name>
    97         </auth-constraint>
    98     </security-constraint>
    99     <login-config>
    100         <auth-method>BASIC</auth-method>
    101     </login-config>
    102     <security-role>
    103         <description> The role that is required to log in to the Application </description>
    104         <role-name>tomcat</role-name>
    105     </security-role>
     5<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
     6        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     7        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
     8        <display-name>ComponentRegistry</display-name>
     9        <description>Clarin Metadata Component Registry</description>
     10        <listener>
     11                <listener-class>org.springframework.web.context.ContextLoaderListener
     12                </listener-class>
     13        </listener>
     14
     15        <context-param>
     16                <param-name>contextConfigLocation</param-name>
     17                <param-value>classpath:spring-config/applicationContext.xml,classpath:spring-config/container-environment.xml
     18                </param-value>
     19        </context-param>
     20
     21        <filter>
     22                <filter-name>characterEncodingFilter</filter-name>
     23                <filter-class>clarin.cmdi.componentregistry.servlet.CharacterEncodingFilter
     24                </filter-class>
     25                <init-param>
     26                        <param-name>encoding</param-name>
     27                        <param-value>UTF-8</param-value>
     28                </init-param>
     29        </filter>
     30        <filter-mapping>
     31                <filter-name>characterEncodingFilter</filter-name>
     32                <url-pattern>/*</url-pattern>
     33        </filter-mapping>
     34        <filter>
     35                <filter-name>wicket.componentregistry</filter-name>
     36                <filter-class>org.apache.wicket.protocol.http.WicketFilter
     37                </filter-class>
     38                <init-param>
     39                        <param-name>applicationClassName</param-name>
     40                        <param-value>clarin.cmdi.componentregistry.frontend.AdminApp
     41                        </param-value>
     42                </init-param>
     43                <init-param>
     44                        <param-name>configuration</param-name>
     45                        <!-- <param-value>development</param-value> -->
     46                        <param-value>deployment</param-value>
     47                        <!-- you can override with -Dwicket.configuration=development -->
     48                </init-param>
     49        </filter>
     50        <filter-mapping>
     51                <filter-name>wicket.componentregistry</filter-name>
     52                <url-pattern>/admin/*</url-pattern>
     53        </filter-mapping>
     54        <servlet>
     55                <servlet-name>ComponentRegistry Web Application</servlet-name>
     56                <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
     57                <!-- init-param>
     58                        <param-name>com.sun.jersey.config.property.resourceConfigClass
     59                        </param-name>
     60                        <param-value>com.sun.jersey.api.core.ClassNamesResourceConfig
     61                        </param-value>
     62                </init-param-->
     63                <!-- <init-param> <param-name>com.sun.jersey.config.property.classnames</param-name>
     64                        <param-value>com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider</param-value>
     65                        </init-param> -->
     66                <init-param>
     67                        <param-name>com.sun.jersey.config.property.packages</param-name>
     68                        <param-value>com.sun.jersey.multipart.impl</param-value>
     69                </init-param>
     70                <load-on-startup>1</load-on-startup>
     71        </servlet>
     72        <servlet-mapping>
     73                <servlet-name>ComponentRegistry Web Application</servlet-name>
     74                <url-pattern>/rest/*</url-pattern>
     75        </servlet-mapping>
     76        <servlet>
     77                <servlet-name>Isocat Servlet</servlet-name>
     78                <servlet-class>clarin.cmdi.componentregistry.servlet.IsocatServlet
     79                </servlet-class>
     80                <load-on-startup>1</load-on-startup>
     81        </servlet>
     82        <servlet-mapping>
     83                <servlet-name>Isocat Servlet</servlet-name>
     84                <url-pattern>/isocat/*</url-pattern>
     85        </servlet-mapping>
     86        <security-constraint>
     87                <display-name>ComponentRegistry web service</display-name>
     88                <web-resource-collection>
     89                        <web-resource-name>ComponentRegistry edit</web-resource-name>
     90                        <description />
     91                        <url-pattern>/rest/*</url-pattern>
     92                        <http-method>DELETE</http-method>
     93                        <http-method>PUT</http-method>
     94                        <http-method>POST</http-method>
     95                </web-resource-collection>
     96                <auth-constraint>
     97                        <role-name>tomcat</role-name>
     98                </auth-constraint>
     99        </security-constraint>
     100        <security-constraint>
     101                <display-name>ComponentRegistry SWF GET</display-name>
     102                <web-resource-collection>
     103                        <web-resource-name>ComponentRegistry access</web-resource-name>
     104                        <description />
     105                        <url-pattern>/*</url-pattern>
     106                        <http-method>GET</http-method>
     107                </web-resource-collection>
     108                <auth-constraint>
     109                        <role-name>tomcat</role-name>
     110                </auth-constraint>
     111        </security-constraint>
     112        <login-config>
     113                <auth-method>BASIC</auth-method>
     114        </login-config>
     115        <security-role>
     116                <description> The role that is required to log in to the Application
     117                </description>
     118                <role-name>tomcat</role-name>
     119        </security-role>
    106120</web-app>
  • ComponentRegistry/trunk/ComponentRegistry/src/main/webapp/WEB-INF/web.xml

    r3086 r3449  
    1111        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    1212    </listener>
     13   
     14    <context-param>
     15        <param-name>contextConfigLocation</param-name>
     16        <param-value>classpath:spring-config/applicationContext.xml</param-value>
     17    </context-param>
     18   
    1319    <filter>
    1420        <filter-name>characterEncodingFilter</filter-name>
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AbstractDescriptionDaoTest.java

    r1454 r3449  
    99
    1010import org.junit.Test;
    11 import org.junit.runner.RunWith;
    1211import org.springframework.beans.factory.annotation.Autowired;
    13 import org.springframework.jdbc.core.JdbcTemplate;
    14 import org.springframework.test.context.ContextConfiguration;
    15 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    16 
     12
     13import clarin.cmdi.componentregistry.BaseUnitTest;
    1714import clarin.cmdi.componentregistry.model.AbstractDescription;
    1815
    1916/**
    20  *
     17 * Base test class for concrete tests to profile and component DAOs
    2118 * @author Twan Goosen <twan.goosen@mpi.nl>
     19 * @author George.Georgovassilis@mpi.nl
    2220 */
    23 @RunWith(SpringJUnit4ClassRunner.class)
    24 @ContextConfiguration(locations = { "/applicationContext.xml" })
    25 public abstract class AbstractDescriptionDaoTest {
     21public abstract class AbstractDescriptionDaoTest extends BaseUnitTest {
    2622
    2723    @Autowired
    28     protected JdbcTemplate jdbcTemplate;
    29 
    30     @Autowired
    31     private UserDao userDao;
    32 
    33     protected abstract AbstractDescriptionDao getDao();
     24    private IUserDAO userDao;
     25
     26    protected abstract IAbstractDescriptionDao getDao();
    3427
    3528    @Test
     
    5447
    5548        String testComponent = getContentString();
    56         Number newId = getDao().insertDescription(description, testComponent, true, null);
     49        Number newId = getDao().insertDescription(description, testComponent,
     50                true, null);
    5751        assertNotNull(newId);
    5852        AbstractDescription descr = getDao().getById(newId);
     
    6458        assertEquals("MyDomain \u00CA", descr.getDomainName());
    6559        assertEquals("http://MyHref", descr.getHref());
    66         assertEquals(AbstractDescription.getDate(regDate), AbstractDescription.getDate(descr.getRegistrationDate()));
    67         assertEquals(testComponent, getDao().getContent(false, description.getId()));
     60        assertEquals(AbstractDescription.getDate(regDate),
     61                AbstractDescription.getDate(descr.getRegistrationDate()));
     62        assertEquals(testComponent,
     63                getDao().getContent(false, description.getId()));
    6864    }
    6965
     
    7470        insert("B", true, null);
    7571        insert("a", true, null);
    76        
    77         List<AbstractDescription> descs = getDao().getPublicDescriptions(); 
     72
     73        List<AbstractDescription> descs = getDao().getPublicDescriptions();
    7874        assertEquals(4, descs.size());
    79         assertEquals("a", descs.get(0).getName()); //ordered by name case insensitive then by cmdId
     75        assertEquals("a", descs.get(0).getName()); // ordered by name case
     76                                                   // insensitive then by cmdId
    8077        assertEquals("A", descs.get(1).getName());
    8178        assertEquals("a", descs.get(2).getName());
    8279        assertTrue(descs.get(1).getId().compareTo(descs.get(2).getId()) < 0);
    8380        assertEquals("B", descs.get(3).getName());
    84        
    85     }
    86    
     81
     82    }
     83
    8784    @Test
    8885    public void testGetPublicComponents() throws Exception {
    89         List<AbstractDescription> descriptions = getDao().getPublicDescriptions();
     86        List<AbstractDescription> descriptions = getDao()
     87                .getPublicDescriptions();
    9088        assertNotNull(descriptions);
    9189    }
     
    9391    @Test
    9492    public void testGetUserspaceDescriptions() throws Exception {
    95         List<AbstractDescription> descriptions = getDao().getUserspaceDescriptions(-1);
     93        List<AbstractDescription> descriptions = getDao()
     94                .getUserspaceDescriptions(-1);
    9695        assertEquals(0, descriptions.size());
    9796    }
     
    131130
    132131        String testComponent = getContentString();
    133         Number newId = getDao().insertDescription(description, testComponent, true, null);
     132        Number newId = getDao().insertDescription(description, testComponent,
     133                true, null);
    134134
    135135        // Change values
     
    156156        getDao().updateDescription(newId, null, testContent2);
    157157        // Test if new content is there
    158         assertEquals(testContent2, getDao().getContent(false, description.getId()));
     158        assertEquals(testContent2,
     159                getDao().getContent(false, description.getId()));
    159160
    160161        // Update both
     
    171172        assertEquals("YetAnotherDescription", description.getDescription());
    172173        // Test if new content is there
    173         assertEquals(testContent3, getDao().getContent(false, description.getId()));
     174        assertEquals(testContent3,
     175                getDao().getContent(false, description.getId()));
    174176    }
    175177
     
    180182        assertTrue(getDao().isPublic(publicDesc.getId()));
    181183        assertFalse(getDao().isInUserSpace(publicDesc.getId(), userId));
    182        
     184
    183185        AbstractDescription privateDesc = insert(false, userId);
    184186        assertFalse(getDao().isPublic(privateDesc.getId()));
    185187        assertTrue(getDao().isInUserSpace(privateDesc.getId(), userId));
    186        
     188
    187189        getDao().setDeleted(publicDesc, true);
    188190        assertTrue(getDao().isPublic(publicDesc.getId()));
    189191        assertFalse(getDao().isInUserSpace(publicDesc.getId(), userId));
    190        
     192
    191193        getDao().setDeleted(privateDesc, true);
    192194        assertFalse(getDao().isPublic(privateDesc.getId()));
     
    197199        return insert("Aap", isPublic, userId);
    198200    }
    199    
    200     private AbstractDescription insert(String name, boolean isPublic, Number userId) {
     201
     202    private AbstractDescription insert(String name, boolean isPublic,
     203            Number userId) {
    201204        AbstractDescription desc = createNewDescription();
    202205        desc.setName(name);
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/AdminRegistryTest.java

    r3088 r3449  
    99import org.junit.Before;
    1010import org.junit.Test;
    11 import org.junit.runner.RunWith;
    1211import org.springframework.beans.factory.annotation.Autowired;
    13 import org.springframework.jdbc.core.JdbcTemplate;
    14 import org.springframework.test.context.ContextConfiguration;
    15 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    1612
     13import clarin.cmdi.componentregistry.BaseUnitTest;
    1714import clarin.cmdi.componentregistry.ComponentRegistry;
    1815import clarin.cmdi.componentregistry.ComponentRegistryFactory;
     
    2825import clarin.cmdi.componentregistry.rest.RegistryTestHelper;
    2926
    30 @RunWith(SpringJUnit4ClassRunner.class)
    31 @ContextConfiguration(locations = {"/applicationContext.xml"})
    32 public class AdminRegistryTest {
     27/**
     28 *
     29 * @author george.georgovassilis@mpi.nl
     30 *
     31 */
     32public class AdminRegistryTest extends BaseUnitTest{
    3333
    3434    @Autowired
    35     private ComponentDescriptionDao componentDescriptionDao;
     35    private IComponentDescriptionDao componentDescriptionDao;
    3636    @Autowired
    37     private ProfileDescriptionDao profileDescriptionDao;
     37    private IProfileDescriptionDAO profileDescriptionDao;
    3838    @Autowired
    3939    private ComponentRegistryFactory componentRegistryFactory;
    4040    private static final Principal PRINCIPAL_ADMIN = DummyPrincipal.DUMMY_ADMIN_PRINCIPAL;
    41     @Autowired
    42     private JdbcTemplate jdbcTemplate;
    4341    @Autowired
    4442    private MDMarshaller marshaller;
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/CommentsDaoTest.java

    r1895 r3449  
    11package clarin.cmdi.componentregistry.impl.database;
    22
     3import clarin.cmdi.componentregistry.BaseUnitTest;
    34import clarin.cmdi.componentregistry.model.Comment;
     5
    46import java.util.List;
    5 import org.junit.runner.RunWith;
     7
    68import org.junit.Test;
     9
    710import static org.junit.Assert.assertNotNull;
    811import static org.junit.Assert.assertNull;
    912import static org.junit.Assert.assertEquals;
     13
    1014import org.junit.Before;
    11 
    1215import org.springframework.beans.factory.annotation.Autowired;
    1316import org.springframework.jdbc.core.JdbcTemplate;
    14 import org.springframework.test.context.ContextConfiguration;
    15 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    1617
    1718/**
    1819 *
    1920 * @author jean-charles FerriÚres <jean-charles.ferrieres@mpi.nl>
     21 * @author George.Georgovassilis@mpi.nl
    2022 */
    21 @RunWith(SpringJUnit4ClassRunner.class)
    22 @ContextConfiguration(locations = {"/applicationContext.xml"})
    23 public class CommentsDaoTest {
     23public class CommentsDaoTest extends BaseUnitTest{
    2424
    2525    @Autowired
    2626    private JdbcTemplate jdbcTemplate;
    2727    @Autowired
    28     private CommentsDao commentsDao;
     28    private ICommentsDao commentsDao;
    2929
    3030    @Before
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentDescriptionDaoTest.java

    r1701 r3449  
    77
    88import org.junit.Before;
    9 import org.junit.Test;
    10 import static org.junit.Assert.fail;
    11 import static org.junit.Assert.assertEquals;
    129import org.springframework.beans.factory.annotation.Autowired;
    13 import org.springframework.dao.DataAccessException;
    1410
    1511/**
    16  *
     12 * 
    1713 * @author Twan Goosen <twan.goosen@mpi.nl>
     14 * @author George.Georgovassilis@mpi.nl
    1815 */
    1916public class ComponentDescriptionDaoTest extends AbstractDescriptionDaoTest {
    2017
    2118    @Autowired
    22     ComponentDescriptionDao componentDescriptionDao;
     19    IComponentDescriptionDao componentDescriptionDao;
    2320
    2421    @Before
     
    3229
    3330    @Override
    34     protected AbstractDescriptionDao getDao() {
     31    protected IAbstractDescriptionDao getDao() {
    3532        return componentDescriptionDao;
    3633    }
     
    4138    }
    4239
    43     @Test
    44     public void testTransaction() {
    45         // Reset database and only create Content table so that inserting a description will fail
    46         resetDatabase(jdbcTemplate);
    47         createTableXmlContent(jdbcTemplate);
    48 
    49         // Create description and component
    50         String regDate = AbstractDescription.createNewDate();
    51         AbstractDescription description = createNewDescription();
    52         description.setName("MyComponent");
    53         description.setDescription("MyDescription");
    54         description.setCreatorName("Aap");
    55         description.setGroupName("MyGroup");
    56         description.setDomainName("MyDomain");
    57         description.setHref("http://MyHref");
    58         description.setRegistrationDate(regDate);
    59         String testComponent = RegistryTestHelper.getComponentTestContentString();
    60 
    61         // Try inserting description, which should fail because there is not ComponentDescription table
    62         try {
    63             getDao().insertDescription(description, testComponent, true, null);
    64             fail("No exception thrown for missing table");
    65         } catch (DataAccessException ex) {
    66         }
    67 
    68         // Check whether content was not inserted
    69         final String select = "SELECT count(*) FROM " + ComponentDescriptionDao.TABLE_XML_CONTENT;
    70         int count = jdbcTemplate.queryForInt(select);
    71         assertEquals(0, count);
    72     }
    73 
    7440    @Override
    7541    protected String getContentString() {
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryDbImplTest.java

    r3088 r3449  
    3333import static org.junit.Assert.*;
    3434
     35/**
     36 *
     37 * @author george.georgovassilis@mpi.nl
     38 *
     39 */
    3540@RunWith(SpringJUnit4ClassRunner.class)
    36 @ContextConfiguration(locations = {"/applicationContext.xml"})
     41@ContextConfiguration(locations = {
     42        "classpath:spring-config/applicationContext.xml",
     43        "classpath:spring-config/datasource-hsqldb.xml" })
    3744public class ComponentRegistryDbImplTest {
    3845
     
    4249    private ComponentRegistryBeanFactory componentRegistryBeanFactory;
    4350    @Autowired
    44     private UserDao userDao;
     51    private IUserDAO userDao;
    4552    @Autowired
    4653    private JdbcTemplate jdbcTemplate;
     
    5461    public void testRegisterComponent() throws Exception {
    5562        ComponentRegistry register = getComponentRegistryForUser(null);
    56         ComponentDescription description = ComponentDescription.createNewDescription();
     63        ComponentDescription description = ComponentDescription
     64                .createNewDescription();
    5765
    5866        description.setName("Aap");
     
    8088        assertNull(register.getMDProfile(desc.getId()));
    8189
    82         ComponentDescription componentDescription = register.getComponentDescription(description.getId());
     90        ComponentDescription componentDescription = register
     91                .getComponentDescription(description.getId());
    8392        assertNotNull(componentDescription);
    8493
    85         assertEquals("Header id should be set from description id", description.getId(), component.getHeader().getID());
     94        assertEquals("Header id should be set from description id",
     95                description.getId(), component.getHeader().getID());
    8696        assertEquals("Aap", component.getHeader().getName());
    87         assertEquals("Will not be overwritten", component.getHeader().
    88                 getDescription());
     97        assertEquals("Will not be overwritten", component.getHeader()
     98                .getDescription());
    8999    }
    90100
     
    92102    public void testRegisterProfile() throws Exception {
    93103        ComponentRegistry register = getComponentRegistryForUser(null);
    94         ProfileDescription description = ProfileDescription.createNewDescription();
     104        ProfileDescription description = ProfileDescription
     105                .createNewDescription();
    95106        description.setName("Aap");
    96107        description.setDescription("MyDescription");
     
    113124        CMDComponentSpec profile = register.getMDProfile(desc.getId());
    114125
    115         ProfileDescription profileDescription = register.getProfileDescription(description.getId());
     126        ProfileDescription profileDescription = register
     127                .getProfileDescription(description.getId());
    116128        assertNotNull(profileDescription);
    117129
    118130        assertNotNull(profile);
    119         assertEquals("Header id should be set from description id", description.getId(), profile.getHeader().getID());
     131        assertEquals("Header id should be set from description id",
     132                description.getId(), profile.getHeader().getID());
    120133        assertEquals("Aap", profile.getHeader().getName());
    121134        assertEquals("MyDescription", profile.getHeader().getDescription());
     
    182195        assertEquals(0, publicReg.getDeletedComponentDescriptions().size());
    183196
    184         registry.deleteMDComponent(desc3.getId(), USER_CREDS.getPrincipal(), false);
     197        registry.deleteMDComponent(desc3.getId(), USER_CREDS.getPrincipal(),
     198                false);
    185199
    186200        assertEquals(1, registry.getDeletedProfileDescriptions().size());
     
    189203        assertEquals(0, publicReg.getDeletedComponentDescriptions().size());
    190204
    191         publicReg.deleteMDComponent(desc4.getId(), USER_CREDS.getPrincipal(), false);
     205        publicReg.deleteMDComponent(desc4.getId(), USER_CREDS.getPrincipal(),
     206                false);
    192207
    193208        assertEquals(1, registry.getDeletedProfileDescriptions().size());
     
    198213    }
    199214
    200     private Comment createComment(ComponentRegistry register, ProfileDescription description) throws Exception {
     215    private Comment createComment(ComponentRegistry register,
     216            ProfileDescription description) throws Exception {
    201217        Comment comment = createComment(description);
    202218        register.registerComment(comment, USER_CREDS.getPrincipalName());
    203         assertEquals(1, register.getCommentsInProfile(description.getId(), null).size());
     219        assertEquals(1, register
     220                .getCommentsInProfile(description.getId(), null).size());
    204221        return comment;
    205222    }
     
    217234    }
    218235
    219     private ProfileDescription createProfile(ComponentRegistry register) throws Exception {
     236    private ProfileDescription createProfile(ComponentRegistry register)
     237            throws Exception {
    220238        ProfileDescription description = getProfileDesc();
    221239
     
    227245        // Non authorized user should never be able to delete
    228246        try {
    229             register.deleteMDProfile(description.getId(), new DummyPrincipal("Fake User"));
     247            register.deleteMDProfile(description.getId(), new DummyPrincipal(
     248                    "Fake User"));
    230249            fail("Should have thrown exception");
    231250        } catch (UserUnauthorizedException e) {
     
    238257
    239258    private ProfileDescription getProfileDesc() {
    240         ProfileDescription description = ProfileDescription.createNewDescription();
     259        ProfileDescription description = ProfileDescription
     260                .createNewDescription();
    241261        description.setName("Aap");
    242262        description.setCreatorName(USER_CREDS.getDisplayName());
     
    246266    }
    247267
    248 //    @Test
    249 //    public void testPostComponentcomment() throws Exception {
    250 //      ComponentRegistry registry = getComponentRegistryForUser(null);
    251 //      ComponentDescription description = createComponent(registry);
    252 //
    253 //    }
     268    // @Test
     269    // public void testPostComponentcomment() throws Exception {
     270    // ComponentRegistry registry = getComponentRegistryForUser(null);
     271    // ComponentDescription description = createComponent(registry);
     272    //
     273    // }
    254274    @Test
    255275    public void testDeletePublicComponent() throws Exception {
     
    269289        ComponentDescription description = createComponent(registry);
    270290        // Delete as user
    271         registry.deleteMDComponent(description.getId(), USER_CREDS.getPrincipal(), false);
     291        registry.deleteMDComponent(description.getId(),
     292                USER_CREDS.getPrincipal(), false);
    272293        assertEquals(0, registry.getComponentDescriptions().size());
    273294        assertNull(registry.getMDProfile(description.getId()));
     
    289310        Calendar calendar = Calendar.getInstance();
    290311        calendar.set(Calendar.YEAR, 1999);
    291         description.setRegistrationDate(DateFormatUtils.formatUTC(calendar.getTime(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()));
     312        description.setRegistrationDate(DateFormatUtils.formatUTC(
     313                calendar.getTime(),
     314                DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()));
    292315        CMDComponentSpec testComp = RegistryTestHelper.getTestComponent();
    293316
     
    299322
    300323        try {
    301             registry.deleteMDComponent(description.getId(), USER_CREDS.getPrincipal(), false);
     324            registry.deleteMDComponent(description.getId(),
     325                    USER_CREDS.getPrincipal(), false);
    302326            fail("Should have thrown exception");
    303327        } catch (DeleteFailedException e) {
     
    307331        assertEquals(0, registry.getComponentDescriptions().size());
    308332
    309         registry = getComponentRegistryForUser(userId); // ComponentRegistryFactoryImpl.getInstance().getComponentRegistry(true, USER_CREDS); //user registry
     333        registry = getComponentRegistryForUser(userId); // ComponentRegistryFactoryImpl.getInstance().getComponentRegistry(true,
     334                                                        // USER_CREDS); //user
     335                                                        // registry
    310336        description = getComponentDesc();
    311337        registry.register(description, testComp);
    312338        assertEquals(1, registry.getComponentDescriptions().size());
    313         registry.deleteMDComponent(description.getId(), USER_CREDS.getPrincipal(), false); //user workspace can always delete
     339        registry.deleteMDComponent(description.getId(),
     340                USER_CREDS.getPrincipal(), false); // user workspace can always
     341                                                   // delete
    314342        assertEquals(0, registry.getComponentDescriptions().size());
    315343    }
     
    323351        Calendar calendar = Calendar.getInstance();
    324352        calendar.set(Calendar.YEAR, 1999);
    325         description.setRegistrationDate(DateFormatUtils.formatUTC(calendar.getTime(), DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()));
     353        description.setRegistrationDate(DateFormatUtils.formatUTC(
     354                calendar.getTime(),
     355                DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern()));
    326356        CMDComponentSpec testComp = RegistryTestHelper.getTestProfile();
    327357
     
    332362        registry = getComponentRegistryForUser(null);
    333363        try {
    334             registry.deleteMDProfile(description.getId(), USER_CREDS.getPrincipal());
     364            registry.deleteMDProfile(description.getId(),
     365                    USER_CREDS.getPrincipal());
    335366            fail("Should have thrown exception");
    336367        } catch (DeleteFailedException e) {
     
    341372
    342373        registry = getComponentRegistryForUser(userId);
    343         description = getProfileDesc();//Need to create a new one for a new id
     374        description = getProfileDesc();// Need to create a new one for a new id
    344375        registry.register(description, testComp);
    345376        assertEquals(1, registry.getProfileDescriptions().size());
    346         registry.deleteMDProfile(description.getId(), USER_CREDS.getPrincipal()); //user workspace can always delete
     377        registry.deleteMDProfile(description.getId(), USER_CREDS.getPrincipal()); // user
     378                                                                                  // workspace
     379                                                                                  // can
     380                                                                                  // always
     381                                                                                  // delete
    347382        assertEquals(0, registry.getProfileDescriptions().size());
    348383    }
     
    365400        comp1Content += "</CMD_ComponentSpec>\n";
    366401
    367         ComponentDescription comp1Desc = RegistryTestHelper.addComponent(register, comp1Id, comp1Content);
     402        ComponentDescription comp1Desc = RegistryTestHelper.addComponent(
     403                register, comp1Id, comp1Content);
    368404
    369405        // Component2 references component1
     
    375411        comp2Content += "    <CMD_Component name=\"Recursion\" CardinalityMin=\"1\" CardinalityMax=\"10\">\n";
    376412        comp2Content += "        <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
    377         comp2Content += "        <CMD_Component ComponentId=\"" + comp1Desc.getId() + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
     413        comp2Content += "        <CMD_Component ComponentId=\"" + comp1Desc.getId()
     414                + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
    378415        comp2Content += "    </CMD_Component>\n";
    379416        comp2Content += "</CMD_ComponentSpec>\n";
     
    384421    }
    385422
    386     private ComponentDescription createComponent(ComponentRegistry registry) throws Exception {
     423    private ComponentDescription createComponent(ComponentRegistry registry)
     424            throws Exception {
    387425        ComponentDescription description = getComponentDesc();
    388426        CMDComponentSpec testComp = RegistryTestHelper.getTestComponent();
     
    392430        // Non authorized user should never be able to delete
    393431        try {
    394             registry.deleteMDComponent(description.getId(), new DummyPrincipal("Fake User"), false);
     432            registry.deleteMDComponent(description.getId(), new DummyPrincipal(
     433                    "Fake User"), false);
    395434            fail("Should have thrown exception");
    396435        } catch (UserUnauthorizedException e) {
     
    403442
    404443    private ComponentDescription getComponentDesc() {
    405         ComponentDescription description = ComponentDescription.createNewDescription();
     444        ComponentDescription description = ComponentDescription
     445                .createNewDescription();
    406446        description.setName("Aap");
    407447        description.setCreatorName(USER_CREDS.getDisplayName());
     
    412452
    413453    private ComponentRegistry getComponentRegistryForUser(Number userId) {
    414         ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory.getNewComponentRegistry();
     454        ComponentRegistryDbImpl componentRegistry = componentRegistryBeanFactory
     455                .getNewComponentRegistry();
    415456        if (userId != null) {
    416             componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(userId));
     457            componentRegistry.setStatus(ComponentStatus.PRIVATE, new OwnerUser(
     458                    userId));
    417459        }
    418460        return componentRegistry;
     
    447489
    448490        String id = "profile1";
    449         ProfileDescription description = RegistryTestHelper.addProfile(register, id, profileContent);
     491        ProfileDescription description = RegistryTestHelper.addProfile(
     492                register, id, profileContent);
    450493
    451494        OutputStream output = new ByteArrayOutputStream();
     
    454497        assertTrue(xsd.endsWith("</xs:schema>"));
    455498
    456         assertTrue(RegistryTestHelper.hasComponent(xsd, "Actor", "0", "unbounded"));
     499        assertTrue(RegistryTestHelper.hasComponent(xsd, "Actor", "0",
     500                "unbounded"));
    457501    }
    458502
     
    474518        comp1Content += "    <CMD_Component name=\"Recursion\" CardinalityMin=\"1\" CardinalityMax=\"10\">\n";
    475519        comp1Content += "       <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
    476         comp1Content += "       <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + comp2Id + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
     520        comp1Content += "       <CMD_Component ComponentId=\""
     521                + ComponentRegistry.REGISTRY_ID + comp2Id
     522                + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
    477523        comp1Content += "    </CMD_Component>\n";
    478524        comp1Content += "</CMD_ComponentSpec>\n";
    479525
    480         ComponentDescription comp1Desc = RegistryTestHelper.addComponent(register, comp1Id, comp1Content);
     526        ComponentDescription comp1Desc = RegistryTestHelper.addComponent(
     527                register, comp1Id, comp1Content);
    481528
    482529        // Component2 references component1
     
    488535        comp2Content += "    <CMD_Component name=\"Recursion\" CardinalityMin=\"1\" CardinalityMax=\"10\">\n";
    489536        comp2Content += "        <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
    490         comp2Content += "        <CMD_Component ComponentId=\"" + comp1Desc.getId() + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
     537        comp2Content += "        <CMD_Component ComponentId=\"" + comp1Desc.getId()
     538                + "\" CardinalityMin=\"0\" CardinalityMax=\"5\"/>\n";
    491539        comp2Content += "    </CMD_Component>\n";
    492540        comp2Content += "</CMD_ComponentSpec>\n";
     
    498546        profileContent += "    xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n";
    499547        profileContent += "    <Header />\n";
    500         profileContent += "    <CMD_Component ComponentId=\"" + comp1Desc.getId()
     548        profileContent += "    <CMD_Component ComponentId=\""
     549                + comp1Desc.getId()
    501550                + "\" filename=\"component-test-file\" CardinalityMin=\"0\" CardinalityMax=\"5\">\n";
    502551        profileContent += "    </CMD_Component>\n";
     
    504553
    505554        String id = "profile1";
    506         ProfileDescription description = RegistryTestHelper.addProfile(register, id, profileContent);
     555        ProfileDescription description = RegistryTestHelper.addProfile(
     556                register, id, profileContent);
    507557
    508558        OutputStream output = new ByteArrayOutputStream();
     
    529579        compContent += "</CMD_ComponentSpec>\n";
    530580
    531         ComponentDescription compDesc = RegistryTestHelper.addComponent(register, compId, compContent);
     581        ComponentDescription compDesc = RegistryTestHelper.addComponent(
     582                register, compId, compContent);
    532583
    533584        String profileContent = "";
     
    535586        profileContent += "    xsi:noNamespaceSchemaLocation=\"general-component-schema.xsd\">\n";
    536587        profileContent += "    <Header />\n";
    537         profileContent += "    <CMD_Component ComponentId=\"" + compDesc.getId()
     588        profileContent += "    <CMD_Component ComponentId=\""
     589                + compDesc.getId()
    538590                + "\" filename=\"component-test-file\" CardinalityMin=\"0\" CardinalityMax=\"5\">\n";
    539591        profileContent += "    </CMD_Component>\n";
     
    541593
    542594        String id = "profile1";
    543         ProfileDescription description = RegistryTestHelper.addProfile(register, id, profileContent);
     595        ProfileDescription description = RegistryTestHelper.addProfile(
     596                register, id, profileContent);
    544597
    545598        OutputStream output = new ByteArrayOutputStream();
     
    563616        compContent += "    </CMD_Component>\n";
    564617        compContent += "</CMD_ComponentSpec>\n";
    565         ComponentDescription compDesc1 = RegistryTestHelper.addComponent(register, "component1", compContent);
     618        ComponentDescription compDesc1 = RegistryTestHelper.addComponent(
     619                register, "component1", compContent);
    566620
    567621        compContent = "";
     
    571625        compContent += "    <CMD_Component name=\"YYY\" CardinalityMin=\"1\" CardinalityMax=\"1\">\n";
    572626        compContent += "        <CMD_Element name=\"Availability\" ValueScheme=\"string\" />\n";
    573         compContent += "        <CMD_Component ComponentId=\"" + compDesc1.getId() + "\" filename=\"component-test-file\">\n";
     627        compContent += "        <CMD_Component ComponentId=\""
     628                + compDesc1.getId() + "\" filename=\"component-test-file\">\n";
    574629        compContent += "        </CMD_Component>\n";
    575630        compContent += "    </CMD_Component>\n";
    576631        compContent += "</CMD_ComponentSpec>\n";
    577         ComponentDescription compDesc2 = RegistryTestHelper.addComponent(register, "component2", compContent);
     632        ComponentDescription compDesc2 = RegistryTestHelper.addComponent(
     633                register, "component2", compContent);
    578634
    579635        compContent = "";
     
    582638        compContent += "    <Header/>\n";
    583639        compContent += "    <CMD_Component name=\"ZZZ\u00e9\" CardinalityMin=\"1\" CardinalityMax=\"unbounded\">\n";
    584         compContent += "        <CMD_Component ComponentId=\"" + compDesc2.getId()
     640        compContent += "        <CMD_Component ComponentId=\""
     641                + compDesc2.getId()
    585642                + "\" filename=\"component-test-file\" CardinalityMin=\"0\" CardinalityMax=\"2\">\n";
    586643        compContent += "        </CMD_Component>\n";
    587         compContent += "        <CMD_Component ComponentId=\"" + compDesc1.getId()
     644        compContent += "        <CMD_Component ComponentId=\""
     645                + compDesc1.getId()
    588646                + "\" filename=\"component-test-file\" CardinalityMin=\"0\" CardinalityMax=\"99\">\n";
    589647        compContent += "        </CMD_Component>\n";
    590648        compContent += "    </CMD_Component>\n";
    591649        compContent += "</CMD_ComponentSpec>\n";
    592         ComponentDescription compDesc3 = RegistryTestHelper.addComponent(register, "component3", compContent);
     650        ComponentDescription compDesc3 = RegistryTestHelper.addComponent(
     651                register, "component3", compContent);
    593652
    594653        ByteArrayOutputStream output = new ByteArrayOutputStream();
     
    602661        assertTrue(RegistryTestHelper.hasComponent(xsd, "XXX", "1", "10"));
    603662        assertTrue(RegistryTestHelper.hasComponent(xsd, "XXX", "0", "99"));
    604         assertTrue(RegistryTestHelper.hasComponent(xsd, "ZZZ\u00e9", "1", "unbounded"));
     663        assertTrue(RegistryTestHelper.hasComponent(xsd, "ZZZ\u00e9", "1",
     664                "unbounded"));
    605665    }
    606666
     
    608668    public void testUpdate() throws Exception {
    609669        ComponentRegistry register = getComponentRegistryForUser(null);
    610         ComponentDescription description = ComponentDescription.createNewDescription();
     670        ComponentDescription description = ComponentDescription
     671                .createNewDescription();
    611672        description.setName("Aap");
    612673        description.setDescription("MyDescription");
    613674
    614         CMDComponentSpec testComponent = RegistryTestHelper.getTestComponent("Test1");
     675        CMDComponentSpec testComponent = RegistryTestHelper
     676                .getTestComponent("Test1");
    615677        register.register(description, testComponent);
    616678
     
    627689
    628690        // Update content
    629         CMDComponentSpec testComponent2 = RegistryTestHelper.getTestComponent("Test2");
     691        CMDComponentSpec testComponent2 = RegistryTestHelper
     692                .getTestComponent("Test2");
    630693        register.update(description, testComponent2, PRINCIPAL_ADMIN, false);
    631694        // Test if new content is there
    632695        assertEquals(RegistryTestHelper.getXml(testComponent2),
    633                 RegistryTestHelper.getXml(register.getMDComponent(description.getId())));
    634 
     696                RegistryTestHelper.getXml(register.getMDComponent(description
     697                        .getId())));
    635698
    636699        // Update both
    637700        description.setName("Mies");
    638701        description.setDescription("YetAnotherDescription");
    639         CMDComponentSpec testComponent3 = RegistryTestHelper.getTestComponent("Test3");
     702        CMDComponentSpec testComponent3 = RegistryTestHelper
     703                .getTestComponent("Test3");
    640704
    641705        // Update in db
     
    648712        // Test if new content is there
    649713        assertEquals(RegistryTestHelper.getXml(testComponent3),
    650                 RegistryTestHelper.getXml(register.getMDComponent(description.getId())));
     714                RegistryTestHelper.getXml(register.getMDComponent(description
     715                        .getId())));
    651716    }
    652717
     
    657722        ComponentRegistry userRegistry = getComponentRegistryForUser(userId);
    658723        ComponentRegistry publicRegistry = getComponentRegistryForUser(null);
    659         ComponentDescription description = ComponentDescription.createNewDescription();
     724        ComponentDescription description = ComponentDescription
     725                .createNewDescription();
    660726        description.setName("Aap");
    661727        description.setDescription("MyDescription");
    662         description.setUserId(DummyPrincipal.DUMMY_CREDENTIALS.getPrincipalName());
    663 
    664         CMDComponentSpec testComponent = RegistryTestHelper.getTestComponent("Test1");
     728        description.setUserId(DummyPrincipal.DUMMY_CREDENTIALS
     729                .getPrincipalName());
     730
     731        CMDComponentSpec testComponent = RegistryTestHelper
     732                .getTestComponent("Test1");
    665733        userRegistry.register(description, testComponent);
    666734        description = userRegistry.getComponentDescription(description.getId());
     
    672740        description.setName("Noot");
    673741        description.setDescription("AnotherDescription");
    674         CMDComponentSpec testComponent2 = RegistryTestHelper.getTestComponent("Test2");
     742        CMDComponentSpec testComponent2 = RegistryTestHelper
     743                .getTestComponent("Test2");
    675744
    676745        // Publish
    677         int result = userRegistry.publish(description, testComponent2, DummyPrincipal.DUMMY_PRINCIPAL);
     746        int result = userRegistry.publish(description, testComponent2,
     747                DummyPrincipal.DUMMY_PRINCIPAL);
    678748        assertEquals(0, result);
    679749
     
    681751        assertNull(userRegistry.getComponentDescription(description.getId()));
    682752        // Get from public registry
    683         description = publicRegistry.getComponentDescription(description.getId());
     753        description = publicRegistry.getComponentDescription(description
     754                .getId());
    684755        // Test if new values are there
    685756        assertNotNull(description);
     
    688759        // Test if new content is there
    689760        assertEquals(RegistryTestHelper.getXml(testComponent2),
    690                 RegistryTestHelper.getXml(publicRegistry.getMDComponent(description.getId())));
     761                RegistryTestHelper.getXml(publicRegistry
     762                        .getMDComponent(description.getId())));
    691763        assertNull(userRegistry.getMDComponent(description.getId()));
    692764    }
     
    704776        assertEquals(0, description.getCommentsCount());
    705777
    706         List<Comment> comments = register.getCommentsInProfile(description.getId(), null);
     778        List<Comment> comments = register.getCommentsInProfile(
     779                description.getId(), null);
    707780        assertEquals(1, comments.size());
    708781
     
    718791
    719792        // Test if owner can delete
    720         comments = register.getCommentsInProfile(description.getId(), DummyPrincipal.DUMMY_PRINCIPAL);
     793        comments = register.getCommentsInProfile(description.getId(),
     794                DummyPrincipal.DUMMY_PRINCIPAL);
    721795        assertTrue(comments.get(0).isCanDelete());
    722796
    723797        // Test if admin can delete
    724798        userDao.insertUser(createUser(DummyPrincipal.DUMMY_ADMIN_CREDENTIALS));
    725         comments = register.getCommentsInProfile(description.getId(), PRINCIPAL_ADMIN);
     799        comments = register.getCommentsInProfile(description.getId(),
     800                PRINCIPAL_ADMIN);
    726801        assertTrue(comments.get(0).isCanDelete());
    727802    }
     
    739814        assertEquals(0, description.getCommentsCount());
    740815
    741         List<Comment> comments = register.getCommentsInProfile(description.getId(), null);
     816        List<Comment> comments = register.getCommentsInProfile(
     817                description.getId(), null);
    742818        assertEquals(1, comments.size());
    743819
     
    761837        assertNotNull(comment);
    762838
    763         List<Comment> comments = register.getCommentsInProfile(description.getId(), null);
     839        List<Comment> comments = register.getCommentsInProfile(
     840                description.getId(), null);
    764841        assertEquals(1, comments.size());
    765842        description = register.getProfileDescription(description.getId());
     
    786863        assertNotNull(comment);
    787864
    788         List<Comment> comments = register.getCommentsInProfile(description.getId(), null);
     865        List<Comment> comments = register.getCommentsInProfile(
     866                description.getId(), null);
    789867        assertEquals(1, comments.size());
    790868        comment = comments.get(0);
     
    792870        // Another user comes along....
    793871
    794         DummyPrincipal user2 = new DummyPrincipal(USER_CREDS.getPrincipalName() + "2");
     872        DummyPrincipal user2 = new DummyPrincipal(USER_CREDS.getPrincipalName()
     873                + "2");
    795874        userDao.insertUser(createUser(user2.getCredentials()));
    796875
     
    825904
    826905    @Test
    827     public void testGetOwner()  throws Exception {
     906    public void testGetOwner() throws Exception {
    828907        ComponentRegistry register = new ComponentRegistryDbImpl();
    829908        assertNull(register.getOwner());
    830         register = new ComponentRegistryDbImpl(ComponentStatus.PRIVATE, new OwnerUser(101));
     909        register = new ComponentRegistryDbImpl(ComponentStatus.PRIVATE,
     910                new OwnerUser(101));
    831911        assertEquals(new OwnerUser(101), register.getOwner());
    832912
    833         register = new ComponentRegistryDbImpl(ComponentStatus.PRIVATE, new OwnerGroup(101));
     913        register = new ComponentRegistryDbImpl(ComponentStatus.PRIVATE,
     914                new OwnerGroup(101));
    834915        assertEquals(new OwnerGroup(101), register.getOwner());
    835916    }
     
    838919    public void testSetStatus() throws Exception {
    839920        // Construct with an owner
    840         ComponentRegistryDbImpl register = new ComponentRegistryDbImpl(ComponentStatus.PUBLISHED, new OwnerUser(101));
     921        ComponentRegistryDbImpl register = new ComponentRegistryDbImpl(
     922                ComponentStatus.PUBLISHED, new OwnerUser(101));
    841923        register.setStatus(ComponentStatus.PRIVATE);
    842924        assertEquals(ComponentStatus.PRIVATE, register.getStatus());
     
    854936    @Test
    855937    public void testSetStatusAndOwner() throws Exception {
    856         ComponentRegistryDbImpl register = new ComponentRegistryDbImpl(ComponentStatus.PUBLISHED, new OwnerUser(101));
     938        ComponentRegistryDbImpl register = new ComponentRegistryDbImpl(
     939                ComponentStatus.PUBLISHED, new OwnerUser(101));
    857940
    858941        register.setStatus(ComponentStatus.PRIVATE, new OwnerGroup(102));
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ComponentRegistryFactoryDbImplTest.java

    r3035 r3449  
    33import org.springframework.jdbc.core.JdbcTemplate;
    44import org.junit.Before;
     5
    56import clarin.cmdi.componentregistry.model.RegistryUser;
     7import clarin.cmdi.componentregistry.BaseUnitTest;
    68import clarin.cmdi.componentregistry.ComponentRegistry;
    79import clarin.cmdi.componentregistry.ComponentStatus;
     
    1012import clarin.cmdi.componentregistry.UserUnauthorizedException;
    1113import clarin.cmdi.componentregistry.rest.DummyPrincipal;
     14
    1215import org.springframework.beans.factory.annotation.Autowired;
    1316import org.junit.Test;
    14 import org.junit.runner.RunWith;
    15 import org.springframework.test.context.ContextConfiguration;
    16 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    1717
    1818import static org.junit.Assert.fail;
     
    2222
    2323/**
    24  *
     24 * 
    2525 * @author Twan Goosen <twan.goosen@mpi.nl>
     26 * @author George.Georgovassilis@mpi.nl
    2627 */
    27 @RunWith(SpringJUnit4ClassRunner.class)
    28 @ContextConfiguration(locations = {"/applicationContext.xml"})
    29 public class ComponentRegistryFactoryDbImplTest {
     28public class ComponentRegistryFactoryDbImplTest extends BaseUnitTest {
    3029
    3130    @Autowired
     
    4847    @Test
    4948    public void testGetPublicRegistry() {
    50         ComponentRegistry registry = componentRegistryFactory.getPublicRegistry();
     49        ComponentRegistry registry = componentRegistryFactory
     50                .getPublicRegistry();
    5151        assertNotNull(registry);
    5252    }
     
    5555    public void getComponentRegistry() throws UserUnauthorizedException {
    5656        // Get public
    57         assertNotNull(componentRegistryFactory.getComponentRegistry(ComponentStatus.PUBLISHED, null, null));
     57        assertNotNull(componentRegistryFactory.getComponentRegistry(
     58                ComponentStatus.PUBLISHED, null, null));
    5859
    5960        // Get for non-existing user
    6061        final RegistryUser testUser = UserDaoTest.createTestUser();
    61         UserCredentials credentials = new DummyPrincipal(testUser.getPrincipalName()).getCredentials();
     62        UserCredentials credentials = new DummyPrincipal(
     63                testUser.getPrincipalName()).getCredentials();
    6264
    63         ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory.getComponentRegistry(ComponentStatus.PRIVATE, null, credentials);
     65        ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
     66                .getComponentRegistry(ComponentStatus.PRIVATE, null,
     67                        credentials);
    6468        assertNotNull(cr1);
    6569        // Get for existing user
    66         ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory.getComponentRegistry(ComponentStatus.PRIVATE, null, credentials);;
     70        ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
     71                .getComponentRegistry(ComponentStatus.PRIVATE, null,
     72                        credentials);
     73        ;
    6774        assertNotNull(cr2);
    6875        assertEquals(cr1.getOwner(), cr2.getOwner());
    6976
    7077        // Get for another new user
    71         UserCredentials credentials2 = new DummyPrincipal(testUser.getPrincipalName() + "2").getCredentials();
    72         ComponentRegistryDbImpl cr3 = (ComponentRegistryDbImpl) componentRegistryFactory.getComponentRegistry(ComponentStatus.PRIVATE, null, credentials2);
     78        UserCredentials credentials2 = new DummyPrincipal(
     79                testUser.getPrincipalName() + "2").getCredentials();
     80        ComponentRegistryDbImpl cr3 = (ComponentRegistryDbImpl) componentRegistryFactory
     81                .getComponentRegistry(ComponentStatus.PRIVATE, null,
     82                        credentials2);
    7383        assertNotNull(cr3);
    7484        assertNotSame(cr1.getOwner(), cr3.getOwner());
     
    7686
    7787    @Test
    78     public void testGetOtherUserComponentRegistry() throws UserUnauthorizedException {
    79         UserCredentials userCredentials = DummyPrincipal.DUMMY_PRINCIPAL.getCredentials();
     88    public void testGetOtherUserComponentRegistry()
     89            throws UserUnauthorizedException {
     90        UserCredentials userCredentials = DummyPrincipal.DUMMY_PRINCIPAL
     91                .getCredentials();
    8092
    8193        // Create registry for new user
    82         ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory.getComponentRegistry(ComponentStatus.PRIVATE, null, userCredentials);
     94        ComponentRegistryDbImpl cr1 = (ComponentRegistryDbImpl) componentRegistryFactory
     95                .getComponentRegistry(ComponentStatus.PRIVATE, null,
     96                        userCredentials);
    8397
    8498        Number id = cr1.getOwner().getId();
    8599
    86100        // Get it as admin
    87         ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory.getOtherUserComponentRegistry(DummyPrincipal.DUMMY_ADMIN_PRINCIPAL, ComponentStatus.PRIVATE, new OwnerUser(id));
     101        ComponentRegistryDbImpl cr2 = (ComponentRegistryDbImpl) componentRegistryFactory
     102                .getOtherUserComponentRegistry(
     103                        DummyPrincipal.DUMMY_ADMIN_PRINCIPAL,
     104                        ComponentStatus.PRIVATE, new OwnerUser(id));
    88105        assertNotNull(cr2);
    89106        // Should be this user's registry
     
    92109        // Try get it as non-admin
    93110        try {
    94             componentRegistryFactory.getOtherUserComponentRegistry(DummyPrincipal.DUMMY_PRINCIPAL, ComponentStatus.PRIVATE, new OwnerUser(id));
     111            componentRegistryFactory.getOtherUserComponentRegistry(
     112                    DummyPrincipal.DUMMY_PRINCIPAL, ComponentStatus.PRIVATE,
     113                    new OwnerUser(id));
    95114            fail("Non-admin can get other user's component registry");
    96115        } catch (Exception ex) {
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/ProfileDescriptionDaoTest.java

    r1701 r3449  
    1010
    1111/**
    12  *
     12 * 
    1313 * @author Twan Goosen <twan.goosen@mpi.nl>
     14 * @author George.Georgovassilis@mpi.nl
    1415 */
    1516public class ProfileDescriptionDaoTest extends AbstractDescriptionDaoTest {
    1617
    1718    @Autowired
    18     ProfileDescriptionDao profileDescriptionDao;
     19    IProfileDescriptionDAO profileDescriptionDao;
    1920
    2021    @Before
     
    2829
    2930    @Override
    30     protected AbstractDescriptionDao getDao() {
     31    protected IAbstractDescriptionDao getDao() {
    3132        return profileDescriptionDao;
    3233    }
     
    3637        return ProfileDescription.createNewDescription();
    3738    }
    38    
     39
    3940    @Override
    4041    protected String getContentString() {
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/impl/database/UserDaoTest.java

    r1789 r3449  
    11package clarin.cmdi.componentregistry.impl.database;
    22
     3import clarin.cmdi.componentregistry.BaseUnitTest;
    34import clarin.cmdi.componentregistry.model.RegistryUser;
     5
    46import java.util.List;
    5 import org.junit.runner.RunWith;
     7
    68import org.junit.Test;
     9
    710import static org.junit.Assert.assertNotNull;
    811import static org.junit.Assert.assertNull;
    912import static org.junit.Assert.assertEquals;
     13
    1014import org.junit.Before;
    11 
    1215import org.springframework.beans.factory.annotation.Autowired;
    1316import org.springframework.jdbc.core.JdbcTemplate;
    14 import org.springframework.test.context.ContextConfiguration;
    15 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    1617
    1718/**
    18  *
     19 * 
    1920 * @author Twan Goosen <twan.goosen@mpi.nl>
     21 * @author George.Georgovassilis@mpi.nl
    2022 */
    21 @RunWith(SpringJUnit4ClassRunner.class)
    22 @ContextConfiguration(locations = {"/applicationContext.xml"})
    23 public class UserDaoTest {
     23public class UserDaoTest extends BaseUnitTest {
    2424
    2525    @Autowired
    2626    private JdbcTemplate jdbcTemplate;
    2727    @Autowired
    28     private UserDao userDao;
     28    private IUserDAO userDao;
    2929
    3030    @Before
     
    8686        assertEquals("I. Changed", userDao.getById(id).getName());
    8787    }
     88
    8889    public final static String TEST_USER_NAME = "Aap";
    8990    public final static String TEST_USER_PRINCIPAL_NAME = "aap@clarin.eu";
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/CMDComponentSetFilenamesToNullTestRunner.java

    r2515 r3449  
    1616
    1717/**
    18  *
    19  * @author olhsha non-automated developers. test, with and input (a valid
    20  * component/prifile xml file and a path to it) and the output (the file where
    21  * all filenames are set to null, in the same directory as the input file)
     18 * non-automated developers. test, with and input (a valid
     19 *         component/prifile xml file and a path to it) and the output (the file
     20 *         where all filenames are set to null, in the same directory as the
     21 *         input file)
     22 * @author olhsha
     23 * @author George.Georgovassilis@mpi.nl
    2224 */
    2325public class CMDComponentSetFilenamesToNullTestRunner {
    2426
    2527    /**
    26      *
     28     * 
    2729     * @author olhsha
    2830     */
    2931    /**
    3032     * makes a new component (with filled-in filename)
    31      *
    32      * @param filename is assigned to the filed "filename" of the new component
    33      * @param childcomponents is assigned to the list of child components of the
    34      * new component
     33     *
     34     * @param filename
     35     *            is assigned to the filed "filename" of the new component
     36     * @param childcomponents
     37     *            is assigned to the list of child components of the new
     38     *            component
    3539     * @return the reference to the new component
    3640     */
    37     protected CMDComponentType makeTestComponent(String filename, List<CMDComponentType> childcomponents) {
    38 
    39         CMDComponentType component = new CMDComponentType();
    40         component.setFilename(filename);
    41         List<CMDComponentType> kids = component.getCMDComponent();
    42         assertFalse(kids == null);
    43         assertEquals(kids.size(), 0);
    44         if (childcomponents != null) {
    45             kids.addAll(childcomponents);
    46         };
    47         return component;
    48     }
    49 
    50     /* checks if all the filenames related to the component are nulls
     41    protected CMDComponentType makeTestComponent(String filename,
     42            List<CMDComponentType> childcomponents) {
     43
     44        CMDComponentType component = new CMDComponentType();
     45        component.setFilename(filename);
     46        List<CMDComponentType> kids = component.getCMDComponent();
     47        assertFalse(kids == null);
     48        assertEquals(kids.size(), 0);
     49        if (childcomponents != null) {
     50            kids.addAll(childcomponents);
     51        }
     52        ;
     53        return component;
     54    }
     55
     56    /*
     57     * checks if all the filenames related to the component are nulls
    5158     */
    5259    private void checkNullnessOfFilenamesInComponent(CMDComponentType component) {
    53         assertEquals(component.getFilename(), null);
    54         checkNullnessOfFilenamesInListOfComponents(component.getCMDComponent());
    55     }
    56 
    57     /* checks if all the filenames related to the list of component are nulls
    58      *
    59      */
    60     private void checkNullnessOfFilenamesInListOfComponents(List<CMDComponentType> listofcomponents) {
    61         for (CMDComponentType currentcomponent : listofcomponents) {
    62             checkNullnessOfFilenamesInComponent(currentcomponent);
    63         }
    64     }
    65 
    66     /* returns true if all the filenames related to the input component are not null
    67      *
    68      */
    69     private boolean checkNonNullnessOfFilenamesInComponent(CMDComponentType component) {
    70 
    71         String filename = component.getFilename();
    72         System.out.println(filename);
    73         boolean check = (filename == null);
    74         if (check) {
    75             return false;
    76         }
    77         return checkNonNullnessOfFilenamesInListOfComponents(component.getCMDComponent());
    78     }
    79 
    80     /* returns true if all the filenames related to the list of components are not null
    81      *
    82      */
    83     private boolean checkNonNullnessOfFilenamesInListOfComponents(List<CMDComponentType> listofcomponents) {
    84         boolean check;
    85         for (CMDComponentType currentcomponent : listofcomponents) {
    86             check = checkNonNullnessOfFilenamesInComponent(currentcomponent);
    87             if (!check) {
    88                 return false;
    89             }
    90         }
    91         return true;
    92     }
    93 
    94     /* adding dummy filenames to a component
    95      *
     60        assertEquals(component.getFilename(), null);
     61        checkNullnessOfFilenamesInListOfComponents(component.getCMDComponent());
     62    }
     63
     64    /*
     65     * checks if all the filenames related to the list of component are nulls
     66     */
     67    private void checkNullnessOfFilenamesInListOfComponents(
     68            List<CMDComponentType> listofcomponents) {
     69        for (CMDComponentType currentcomponent : listofcomponents) {
     70            checkNullnessOfFilenamesInComponent(currentcomponent);
     71        }
     72    }
     73
     74    /*
     75     * returns true if all the filenames related to the input component are not
     76     * null
     77     */
     78    private boolean checkNonNullnessOfFilenamesInComponent(
     79            CMDComponentType component) {
     80
     81        String filename = component.getFilename();
     82        System.out.println(filename);
     83        boolean check = (filename == null);
     84        if (check) {
     85            return false;
     86        }
     87        return checkNonNullnessOfFilenamesInListOfComponents(component
     88                .getCMDComponent());
     89    }
     90
     91    /*
     92     * returns true if all the filenames related to the list of components are
     93     * not null
     94     */
     95    private boolean checkNonNullnessOfFilenamesInListOfComponents(
     96            List<CMDComponentType> listofcomponents) {
     97        boolean check;
     98        for (CMDComponentType currentcomponent : listofcomponents) {
     99            check = checkNonNullnessOfFilenamesInComponent(currentcomponent);
     100            if (!check) {
     101                return false;
     102            }
     103        }
     104        return true;
     105    }
     106
     107    /*
     108     * adding dummy filenames to a component
    96109     */
    97110    private void addDummyFilenamesToComponent(CMDComponentType component) {
    98         if (component != null) {
    99             component.setFilename("Dummy");
    100             List<CMDComponentType> listofcomponents = component.getCMDComponent();
    101             addDummyFilenamesToListOfComponents(listofcomponents);
    102         }
    103     }
    104 
    105     /* adding dummy filenames to the list of  components
    106      *
    107      */
    108     private void addDummyFilenamesToListOfComponents(List<CMDComponentType> listofcomponents) {
    109         for (CMDComponentType currentcomponent : listofcomponents) {
    110             addDummyFilenamesToComponent(currentcomponent);
    111         }
    112     }
    113 
    114     /* adds dummy filenames to the content of largeProfile.XML
    115      *
    116      */
    117     private CMDComponentSpec makeTestFromFile(String filename) throws IOException, JAXBException {
    118         FileInputStream is = new FileInputStream(filename);
    119         String profilestring = RegistryTestHelper.getStringFromStream(is);
    120         CMDComponentSpec compspec = RegistryTestHelper.getComponentFromString(profilestring); // calling unmarchaller
    121         List<CMDComponentType> listofcomponents = compspec.getCMDComponent();
    122         addDummyFilenamesToListOfComponents(listofcomponents);
    123         assertTrue(checkNonNullnessOfFilenamesInListOfComponents(listofcomponents));
    124         return compspec;
    125     }
    126 
    127     /* creating the profile with filenames filled by "Dummy" and writing it into the file
    128      *
    129      */
    130     private void writeDummiedXML(String filenamein, String filenameout) throws IOException, JAXBException {
    131         CMDComponentSpec compspec = makeTestFromFile(filenamein);
    132         String os = RegistryTestHelper.getXml(compspec);
    133         RegistryTestHelper.writeStringToFile(os, filenameout);
    134     }
    135 
    136     /*generic test-from-file read/write
    137      *
    138      */
    139     private void setFileNamesToNullInFile(String dirName, String fileNameInit, String fileNameDummied, String fileNameUnDummied) throws IOException, JAXBException {
    140 
    141         String path = RegistryTestHelper.openTestDir(dirName);
    142         writeDummiedXML(path + fileNameInit, path + fileNameDummied);
    143 
    144         FileInputStream is = new FileInputStream(path + fileNameDummied);
    145         String dummiedcontent = RegistryTestHelper.getStringFromStream(is);
    146         CMDComponentSpec compspec = RegistryTestHelper.getComponentFromString(dummiedcontent); // calling unmarchaller
    147 
    148         List<CMDComponentType> listofcomponents = compspec.getCMDComponent();
    149 
    150         ComponentRegistryRestService testrestservice = new ComponentRegistryRestService();
    151         testrestservice.setFileNamesFromListToNull(listofcomponents);
    152         checkNullnessOfFilenamesInListOfComponents(listofcomponents);
    153 
    154         String os = RegistryTestHelper.getXml(compspec);
    155         RegistryTestHelper.writeStringToFile(os, path + fileNameUnDummied);
    156     }
    157 
    158     /*
    159      * developer test method: nulling  filenames in an arbitrary (component) file
    160      * user's input: the name of the file, together with the sub-directory inside target/
    161      */
    162     public static void main(String args[])
    163             throws java.io.IOException, JAXBException {
    164 
    165         BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
    166 
    167         System.out.println("");
    168         System.out.print("Sub-directory (of target/) name? (up to 32 symbols): ");
    169         String dirName = buffer.readLine();
    170         System.out.println("");
    171         System.out.println("(Watch out: this is a temorary directory, which is removed after any new clean+build)");
    172         System.out.println(dirName);
    173 
    174         System.out.println("");
    175         System.out.println("Check if your file is in this temorary directory");
    176         System.out.print("and input the file name (up to 32 symbols): ");
    177         String fileName = buffer.readLine();
    178         System.out.println(fileName);
    179 
    180         System.out.println("Bedankt, ff wachten .. ");
    181 
    182         String fileNameDummied = "Dummied" + fileName;
    183         String fileNameUnDummied = "Nulled" + fileName;
    184 
    185         CMDComponentSetFilenamesToNullTestRunner helper = new CMDComponentSetFilenamesToNullTestRunner();
    186 
    187         helper.setFileNamesToNullInFile(dirName, fileName, fileNameDummied, fileNameUnDummied);
    188 
    189         System.out.println("Now look up the directory target/" + dirName);
     111        if (component != null) {
     112            component.setFilename("Dummy");
     113            List<CMDComponentType> listofcomponents = component
     114                    .getCMDComponent();
     115            addDummyFilenamesToListOfComponents(listofcomponents);
     116        }
     117    }
     118
     119    /*
     120     * adding dummy filenames to the list of components
     121     */
     122    private void addDummyFilenamesToListOfComponents(
     123            List<CMDComponentType> listofcomponents) {
     124        for (CMDComponentType currentcomponent : listofcomponents) {
     125            addDummyFilenamesToComponent(currentcomponent);
     126        }
     127    }
     128
     129    /*
     130     * adds dummy filenames to the content of largeProfile.XML
     131     */
     132    private CMDComponentSpec makeTestFromFile(String filename)
     133            throws IOException, JAXBException {
     134        FileInputStream is = new FileInputStream(filename);
     135        String profilestring = RegistryTestHelper.getStringFromStream(is);
     136        CMDComponentSpec compspec = RegistryTestHelper
     137                .getComponentFromString(profilestring); // calling unmarchaller
     138        List<CMDComponentType> listofcomponents = compspec.getCMDComponent();
     139        addDummyFilenamesToListOfComponents(listofcomponents);
     140        assertTrue(checkNonNullnessOfFilenamesInListOfComponents(listofcomponents));
     141        return compspec;
     142    }
     143
     144    /*
     145     * creating the profile with filenames filled by "Dummy" and writing it into
     146     * the file
     147     */
     148    private void writeDummiedXML(String filenamein, String filenameout)
     149            throws IOException, JAXBException {
     150        CMDComponentSpec compspec = makeTestFromFile(filenamein);
     151        String os = RegistryTestHelper.getXml(compspec);
     152        RegistryTestHelper.writeStringToFile(os, filenameout);
     153    }
     154
     155    /*
     156     * generic test-from-file read/write
     157     */
     158    private void setFileNamesToNullInFile(String dirName, String fileNameInit,
     159            String fileNameDummied, String fileNameUnDummied)
     160            throws IOException, JAXBException {
     161
     162        String path = RegistryTestHelper.openTestDir(dirName);
     163        writeDummiedXML(path + fileNameInit, path + fileNameDummied);
     164
     165        FileInputStream is = new FileInputStream(path + fileNameDummied);
     166        String dummiedcontent = RegistryTestHelper.getStringFromStream(is);
     167        CMDComponentSpec compspec = RegistryTestHelper
     168                .getComponentFromString(dummiedcontent); // calling unmarchaller
     169
     170        List<CMDComponentType> listofcomponents = compspec.getCMDComponent();
     171
     172        IComponentRegistryRestService testrestservice = new ComponentRegistryRestService();
     173        testrestservice.setFileNamesFromListToNull(listofcomponents);
     174        checkNullnessOfFilenamesInListOfComponents(listofcomponents);
     175
     176        String os = RegistryTestHelper.getXml(compspec);
     177        RegistryTestHelper.writeStringToFile(os, path + fileNameUnDummied);
     178    }
     179
     180    /*
     181     * developer test method: nulling filenames in an arbitrary (component) file
     182     * user's input: the name of the file, together with the sub-directory
     183     * inside target/
     184     */
     185    public static void main(String args[]) throws java.io.IOException,
     186            JAXBException {
     187
     188        BufferedReader buffer = new BufferedReader(new InputStreamReader(
     189                System.in));
     190
     191        System.out.println("");
     192        System.out
     193                .print("Sub-directory (of target/) name? (up to 32 symbols): ");
     194        String dirName = buffer.readLine();
     195        System.out.println("");
     196        System.out
     197                .println("(Watch out: this is a temorary directory, which is removed after any new clean+build)");
     198        System.out.println(dirName);
     199
     200        System.out.println("");
     201        System.out.println("Check if your file is in this temorary directory");
     202        System.out.print("and input the file name (up to 32 symbols): ");
     203        String fileName = buffer.readLine();
     204        System.out.println(fileName);
     205
     206        System.out.println("Bedankt, ff wachten .. ");
     207
     208        String fileNameDummied = "Dummied" + fileName;
     209        String fileNameUnDummied = "Nulled" + fileName;
     210
     211        CMDComponentSetFilenamesToNullTestRunner helper = new CMDComponentSetFilenamesToNullTestRunner();
     212
     213        helper.setFileNamesToNullInFile(dirName, fileName, fileNameDummied,
     214                fileNameUnDummied);
     215
     216        System.out.println("Now look up the directory target/" + dirName);
    190217    }
    191218}
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/CommentValidatorTest.java

    r3088 r3449  
    11package clarin.cmdi.componentregistry.rest;
    22
     3import clarin.cmdi.componentregistry.BaseUnitTest;
    34import clarin.cmdi.componentregistry.MDMarshaller;
    45import clarin.cmdi.componentregistry.impl.database.ComponentRegistryTestDatabase;
    56import clarin.cmdi.componentregistry.model.AbstractDescription;
    6 
    77import clarin.cmdi.componentregistry.model.ComponentDescription;
    88import static org.junit.Assert.assertEquals;
    99import static org.junit.Assert.assertFalse;
    1010import static org.junit.Assert.assertTrue;
     11import clarin.cmdi.componentregistry.model.ProfileDescription;
    1112
    12 import clarin.cmdi.componentregistry.model.ProfileDescription;
    1313import java.io.ByteArrayInputStream;
    1414import java.io.InputStream;
     15
    1516import javax.xml.transform.TransformerException;
     17
    1618import org.junit.Before;
    1719import org.junit.Test;
    18 import org.junit.runner.RunWith;
    1920import org.springframework.beans.factory.annotation.Autowired;
    2021import org.springframework.jdbc.core.JdbcTemplate;
    21 import org.springframework.test.context.ContextConfiguration;
    22 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    2322
    2423/**
    2524 * Test class for CommentValidator
     25 *
    2626 * @author jean-charles FerriÚres <jean-charles.ferrieres@mpi.nl>
     27 * @author George.Georgovassilis@mpi.nl
    2728 */
    28 @RunWith(SpringJUnit4ClassRunner.class)
    29 @ContextConfiguration(locations = {"/applicationContext.xml"})
    30 public class CommentValidatorTest {
     29public class CommentValidatorTest extends BaseUnitTest {
    3130
    3231    @Autowired
     
    4645    @Test
    4746    public void testValidateSucces() {
    48         AbstractDescription description = ProfileDescription.createNewDescription();
     47        AbstractDescription description = ProfileDescription
     48                .createNewDescription();
    4949        String comContent = "";
    5050        comContent += "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
     
    5252        comContent += "    <comments>myCom</comments>\n";
    5353        comContent += "    <commentDate></commentDate>\n";
    54         comContent += "     <profileDescriptionId>" + description.getId() + "</profileDescriptionId>";
     54        comContent += "     <profileDescriptionId>" + description.getId()
     55                + "</profileDescriptionId>";
    5556        comContent += "    <userId>0</userId>\n";
    5657        comContent += "    <id>1</id>\n";
    5758        comContent += "</comment>\n";
    5859        InputStream input = new ByteArrayInputStream(comContent.getBytes());
    59         CommentValidator validator = new CommentValidator(input, description, marshaller);
     60        CommentValidator validator = new CommentValidator(input, description,
     61                marshaller);
    6062        assertTrue(validator.validate());
    6163    }
     
    7779        comContent += "</comment>\n";
    7880        InputStream input = new ByteArrayInputStream(comContent.getBytes());
    79         CommentValidator validator = new CommentValidator(input, desc, marshaller);
    80         assertFalse(validator.validate());// missing componentId will return an error
     81        CommentValidator validator = new CommentValidator(input, desc,
     82                marshaller);
     83        assertFalse(validator.validate());// missing componentId will return an
     84                                          // error
    8185        assertEquals(validator.getErrorMessages().size(), 1);
    82         assertTrue(validator.getErrorMessages().get(0).startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
     86        assertTrue(validator.getErrorMessages().get(0)
     87                .startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
    8388
    8489        String commentContent = "";
     
    8792        commentContent += "    <comments>myCom</comments>\n";
    8893        commentContent += "    <commentDate></commentDate>\n";
    89         commentContent += "     <componentDescriptionId>" + desc.getId() + "</componentDescriptionId>";
     94        commentContent += "     <componentDescriptionId>" + desc.getId()
     95                + "</componentDescriptionId>";
    9096        commentContent += "    <userId>0</userId>\n";
    9197        commentContent += "    <id>1</id>\n";
     
    9399        input = new ByteArrayInputStream(commentContent.getBytes());
    94100        validator = new CommentValidator(input, desc, marshaller);
    95         assertTrue(validator.validate()); // componentId valid, validation complete
     101        assertTrue(validator.validate()); // componentId valid, validation
     102                                          // complete
    96103    }
    97104
     
    112119        comContent += "</comment>\n";
    113120        InputStream input = new ByteArrayInputStream(comContent.getBytes());
    114         CommentValidator validator = new CommentValidator(input, desc, marshaller);
    115         assertFalse(validator.validate());// missing profileId will return an error
     121        CommentValidator validator = new CommentValidator(input, desc,
     122                marshaller);
     123        assertFalse(validator.validate());// missing profileId will return an
     124                                          // error
    116125        assertEquals(validator.getErrorMessages().size(), 1);
    117         assertTrue(validator.getErrorMessages().get(0).startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
     126        assertTrue(validator.getErrorMessages().get(0)
     127                .startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
    118128
    119129        String commentContent = "";
     
    122132        commentContent += "    <comments>myCom</comments>\n";
    123133        commentContent += "    <commentDate></commentDate>\n";
    124         commentContent += "     <profileDescriptionId>" + desc.getId() + "</profileDescriptionId>";
     134        commentContent += "     <profileDescriptionId>" + desc.getId()
     135                + "</profileDescriptionId>";
    125136        commentContent += "    <userId>0</userId>\n";
    126137        commentContent += "    <id>1</id>\n";
     
    128139        input = new ByteArrayInputStream(commentContent.getBytes());
    129140        validator = new CommentValidator(input, desc, marshaller);
    130         assertTrue(validator.validate()); // profileId valid, validation complete
     141        assertTrue(validator.validate()); // profileId valid, validation
     142                                          // complete
    131143    }
    132144
    133145    /**
    134146     * Test the validation of comment with content comments
    135      * @throws Exception
     147     *
     148     * @throws Exception
    136149     */
    137150    @Test
     
    143156        commentContent += "    <comments></comments>\n";
    144157        commentContent += "    <commentDate></commentDate>\n";
    145         commentContent += "     <profileDescriptionId>" + desc.getId() + "</profileDescriptionId>";
     158        commentContent += "     <profileDescriptionId>" + desc.getId()
     159                + "</profileDescriptionId>";
    146160        commentContent += "    <userId>0</userId>\n";
    147161        commentContent += "    <id>1</id>\n";
    148162        commentContent += "</comment>\n";
    149163        InputStream input = new ByteArrayInputStream(commentContent.getBytes());
    150         CommentValidator validator = new CommentValidator(input, desc, marshaller);
    151         assertFalse(validator.validate()); // missing content will return an error
    152         assertTrue(validator.getErrorMessages().get(0).startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
     164        CommentValidator validator = new CommentValidator(input, desc,
     165                marshaller);
     166        assertFalse(validator.validate()); // missing content will return an
     167                                           // error
     168        assertTrue(validator.getErrorMessages().get(0)
     169                .startsWith(CommentValidator.COMMENT_SPECIFICATION_ERROR));
    153170
    154171        String comContent = "";
     
    157174        comContent += "    <comments>myCom</comments>\n";
    158175        comContent += "    <commentDate></commentDate>\n";
    159         comContent += "     <profileDescriptionId>" + desc.getId() + "</profileDescriptionId>";
     176        comContent += "     <profileDescriptionId>" + desc.getId()
     177                + "</profileDescriptionId>";
    160178        comContent += "    <userId>0</userId>\n";
    161179        comContent += "    <id>1</id>\n";
     
    163181        input = new ByteArrayInputStream(comContent.getBytes());
    164182        validator = new CommentValidator(input, desc, marshaller);
    165         assertTrue(validator.validate());// content comments is fill in, validation complete
     183        assertTrue(validator.validate());// content comments is fill in,
     184                                         // validation complete
    166185
    167186    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTest.java

    r3035 r3449  
    1515import clarin.cmdi.componentregistry.model.RegisterResponse;
    1616import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
     17
    1718import com.sun.jersey.api.client.ClientResponse;
    1819import com.sun.jersey.api.client.UniformInterfaceException;
    1920import com.sun.jersey.api.representation.Form;
    2021import com.sun.jersey.multipart.FormDataMultiPart;
     22
    2123import java.io.ByteArrayInputStream;
    2224import java.util.ArrayList;
    2325import java.util.Date;
    2426import java.util.List;
     27
    2528import javax.ws.rs.core.MediaType;
    2629import javax.ws.rs.core.Response.Status;
     30
    2731import static org.junit.Assert.*;
     32
    2833import org.junit.Before;
    2934import org.junit.Test;
    30 import org.junit.runner.RunWith;
    3135import org.springframework.beans.factory.annotation.Autowired;
    3236import org.springframework.jdbc.core.JdbcTemplate;
    33 import org.springframework.test.context.ContextConfiguration;
    34 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    3537import org.springframework.util.Assert;
    3638
    37 @RunWith(SpringJUnit4ClassRunner.class)
    38 @ContextConfiguration(locations = {"/applicationContext.xml"})
     39/**
     40 * Launches a servlet container environment and performs HTTP calls to the {@link ComponentRegistryRestService}
     41 * @author george.georgovassilis@mpi.nl
     42 *
     43 */
    3944public class ComponentRegistryRestServiceTest extends ComponentRegistryRestServiceTestCase {
    4045
     
    5560    }
    5661
    57     @Override
    58     protected String getApplicationContextFile() {
    59         return "classpath:applicationContext.xml";
    60     }
    61 
    6262    private ComponentRegistry getTestRegistry() {
    6363        return testRegistry;
     
    7474        RegistryTestHelper.addComponent(getTestRegistry(), "component1");
    7575        RegistryTestHelper.addComment(getTestRegistry(), "comment2", "clarin.eu:cr1:profile1", "JUnit@test.com");
    76         Thread.sleep(1000); // wait so order becomes predictable
    7776        RegistryTestHelper.addComment(getTestRegistry(), "comment1", "clarin.eu:cr1:profile1", "JUnit@test.com");
    78         Thread.sleep(1000); // wait so order becomes predictable
    7977        RegistryTestHelper.addComment(getTestRegistry(), "comment3", "clarin.eu:cr1:component1", "JUnit@test.com");
    80         Thread.sleep(1000); // wait so order becomes predictable
    8178        RegistryTestHelper.addComment(getTestRegistry(), "comment4", "clarin.eu:cr1:component1", "JUnit@test.com");
    82         Thread.sleep(1000); // wait so order becomes predictable
    8379    }
    8480
     
    525521    public void testRegisterProfile() throws Exception {
    526522        FormDataMultiPart form = new FormDataMultiPart();
    527         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getTestProfileContent(),
     523        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getTestProfileContent(),
    528524                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    529         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
    530         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
    531         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
    532         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
     525        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
     526        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
     527        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
     528        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
    533529        RegisterResponse response = getAuthenticatedResource("/registry/profiles").type(MediaType.MULTIPART_FORM_DATA).post(
    534530                RegisterResponse.class, form);
     
    681677    private FormDataMultiPart createFormData(Object content, String description) {
    682678        FormDataMultiPart form = new FormDataMultiPart();
    683         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, content, MediaType.APPLICATION_OCTET_STREAM_TYPE);
    684         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "Test1");
    685         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, description);
    686         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "My domain");
    687         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "TestGroup");
     679        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, content, MediaType.APPLICATION_OCTET_STREAM_TYPE);
     680        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "Test1");
     681        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, description);
     682        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "My domain");
     683        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "TestGroup");
    688684        return form;
    689685    }
     
    960956    public void testRegisterComponent() throws Exception {
    961957        FormDataMultiPart form = new FormDataMultiPart();
    962         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentTestContent(),
     958        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentTestContent(),
    963959                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    964         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "ComponentTest1");
    965         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Component");
    966         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
    967         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "TestGroup");
     960        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "ComponentTest1");
     961        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Component");
     962        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
     963        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "TestGroup");
    968964        RegisterResponse response = getAuthenticatedResource("/registry/components").type(MediaType.MULTIPART_FORM_DATA).post(
    969965                RegisterResponse.class, form);
     
    988984    public void testRegisterComment() throws Exception {
    989985        FormDataMultiPart form = new FormDataMultiPart();
    990         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
     986        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
    991987                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    992988        fillUp();
     
    10091005    public void testRegisterCommentToNonExistent() throws Exception {
    10101006        FormDataMultiPart form = new FormDataMultiPart();
    1011         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
     1007        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
    10121008                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    10131009        fillUp();
     
    10201016    public void testRegisterCommentUnauthenticated() throws Exception {
    10211017        FormDataMultiPart form = new FormDataMultiPart();
    1022         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
     1018        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getCommentTestContent(),
    10231019                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    10241020        fillUp();
     
    10321028        FormDataMultiPart form = new FormDataMultiPart();
    10331029        String notAValidProfile = "<CMD_ComponentSpec> </CMD_ComponentSpec>";
    1034         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, new ByteArrayInputStream(notAValidProfile.getBytes()),
     1030        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, new ByteArrayInputStream(notAValidProfile.getBytes()),
    10351031                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1036         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
    1037         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "Domain");
    1038         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "Group");
    1039         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
     1032        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
     1033        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "Domain");
     1034        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "Group");
     1035        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
    10401036        RegisterResponse postResponse = getAuthenticatedResource("/registry/profiles").type(MediaType.MULTIPART_FORM_DATA).post(
    10411037                RegisterResponse.class, form);
     
    10731069        profileContent += "    </CMD_Component>\n";
    10741070        profileContent += "</CMD_ComponentSpec>\n";
    1075         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentContent(profileContent),
     1071        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentContent(profileContent),
    10761072                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1077         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
    1078         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
    1079         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
    1080         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
     1073        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
     1074        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
     1075        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
     1076        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
    10811077        RegisterResponse response = getAuthenticatedResource("/registry/profiles").type(MediaType.MULTIPART_FORM_DATA).post(
    10821078                RegisterResponse.class, form);
     
    11151111    public void testRegisterLargeProfile() throws Exception {
    11161112        FormDataMultiPart form = new FormDataMultiPart();
    1117         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getLargeProfileContent(),
     1113        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getLargeProfileContent(),
    11181114                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1119         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
    1120         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
    1121         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
    1122         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
     1115        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "ProfileTest1");
     1116        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "TestDomain");
     1117        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test Profile");
     1118        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "My Test Group");
    11231119        ClientResponse response = getAuthenticatedResource("/registry/profiles").type(MediaType.MULTIPART_FORM_DATA).post(
    11241120                ClientResponse.class, form);
     
    11291125    public void testRegisterComponentAsProfile() throws Exception {
    11301126        FormDataMultiPart form = new FormDataMultiPart();
    1131         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentTestContent(),
     1127        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, RegistryTestHelper.getComponentTestContent(),
    11321128                MediaType.APPLICATION_OCTET_STREAM_TYPE);
    1133         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, "t");
    1134         form.field(ComponentRegistryRestService.DOMAIN_FORM_FIELD, "domain");
    1135         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test");
    1136         form.field(ComponentRegistryRestService.GROUP_FORM_FIELD, "My Group");
     1129        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, "t");
     1130        form.field(IComponentRegistryRestService.DOMAIN_FORM_FIELD, "domain");
     1131        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, "My Test");
     1132        form.field(IComponentRegistryRestService.GROUP_FORM_FIELD, "My Group");
    11371133        RegisterResponse response = getAuthenticatedResource("/registry/profiles").type(MediaType.MULTIPART_FORM_DATA).post(
    11381134                RegisterResponse.class, form);
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ComponentRegistryRestServiceTestCase.java

    r1696 r3449  
    55import javax.ws.rs.core.HttpHeaders;
    66
    7 
    8 import clarin.cmdi.componentregistry.impl.database.UserDao;
     7import clarin.cmdi.componentregistry.impl.database.IUserDAO;
    98import clarin.cmdi.componentregistry.model.Comment;
    109import clarin.cmdi.componentregistry.model.ComponentDescription;
     
    2322import com.sun.jersey.test.framework.JerseyTest;
    2423import com.sun.jersey.test.framework.WebAppDescriptor;
     24import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
    2525
     26import org.junit.runner.RunWith;
    2627import org.springframework.beans.factory.annotation.Autowired;
     28import org.springframework.test.context.ContextConfiguration;
     29import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     30import org.springframework.test.context.transaction.TransactionConfiguration;
     31import org.springframework.transaction.annotation.Transactional;
    2732import org.springframework.web.context.ContextLoaderListener;
    2833import org.springframework.web.context.request.RequestContextListener;
    2934
     35/**
     36 * Base test that starts a servlet container with the component registry
     37 * @author george.georgovassilis@mpi.nl
     38 *
     39 */
     40@RunWith(SpringJUnit4ClassRunner.class)
     41@ContextConfiguration(locations = {
     42        "classpath:spring-config/applicationContext.xml",
     43        "classpath:spring-config/datasource-hsqldb.xml" })
     44@TransactionConfiguration(defaultRollback = true)
     45@Transactional
    3046public abstract class ComponentRegistryRestServiceTestCase extends JerseyTest {
    31     //CommandLine test e.g.:  curl -i -H "Accept:application/json" -X GET  http://localhost:8080/ComponentRegistry/rest/registry/profiles
     47    // CommandLine test e.g.: curl -i -H "Accept:application/json" -X GET
     48    // http://localhost:8080/ComponentRegistry/rest/registry/profiles
    3249
    3350    protected final static GenericType<List<ProfileDescription>> PROFILE_LIST_GENERICTYPE = new GenericType<List<ProfileDescription>>() {
     
    3855    };
    3956
     57    private static SingletonTestContainerFactory _testContainerFactory;
     58
     59    @Override
     60    public void setUp() throws Exception {
     61        if (!_testContainerFactory.isTestContainerRunning()) {
     62            _testContainerFactory.startTestContainer();
     63        }
     64    }
     65
     66    @Override
     67    public void tearDown() throws Exception {
     68    }
     69
     70    @Override
     71    protected TestContainerFactory getTestContainerFactory() {
     72        if (_testContainerFactory == null) {
     73            _testContainerFactory = new SingletonTestContainerFactory(
     74                    super.getTestContainerFactory());
     75        }
     76        ;
     77        return _testContainerFactory;
     78    }
     79
    4080    @Autowired
    41     private UserDao userDao;
     81    private IUserDAO userDao;
    4282
    43    
    44     protected abstract String getApplicationContextFile();
     83    protected String getApplicationContextFile() {
     84        // sorry for the duplication, but JerseyTest is not aware of
     85        // @ContextConfiguration
     86        return "classpath:spring-config/applicationContext.xml, classpath:spring-config/datasource-hsqldb.xml";
     87    }
    4588
    4689    @Override
    4790    protected AppDescriptor configure() {
    48         WebAppDescriptor.Builder builder = new WebAppDescriptor.Builder()
    49                 .contextParam("contextConfigLocation", getApplicationContextFile())
    50                 .servletClass(SpringServlet.class)
    51                 .initParam(WebComponent.RESOURCE_CONFIG_CLASS,ClassNamesResourceConfig.class.getName())
    52                 .initParam(ClassNamesResourceConfig.PROPERTY_CLASSNAMES,FormDataMultiPartDispatchProvider.class.getName() + ";" + ComponentRegistryRestService.class.getName())
    53                 .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
    54                 .requestListenerClass(RequestContextListener.class)
    55                 .contextListenerClass(ContextLoaderListener.class)
    56                 ;
    57         return builder.build();
     91        WebAppDescriptor.Builder builder = new WebAppDescriptor.Builder()
     92                .contextParam("contextConfigLocation",
     93                        getApplicationContextFile())
     94                .servletClass(SpringServlet.class)
     95                .initParam(WebComponent.RESOURCE_CONFIG_CLASS,
     96                        ClassNamesResourceConfig.class.getName())
     97                .initParam(
     98                        ClassNamesResourceConfig.PROPERTY_CLASSNAMES,
     99                        FormDataMultiPartDispatchProvider.class.getName() + ";"
     100                                + ComponentRegistryRestService.class.getName())
     101                .addFilter(DummySecurityFilter.class, "DummySecurityFilter")
     102                .requestListenerClass(RequestContextListener.class)
     103                .contextListenerClass(ContextLoaderListener.class);
     104        return builder.build();
    58105    }
    59106
    60107    protected WebResource getResource() {
    61         return resource();
     108        return resource();
    62109    }
    63110
    64111    protected Builder getAuthenticatedResource(String path) {
    65         return getAuthenticatedResource(getResource().path(path));
     112        return getAuthenticatedResource(getResource().path(path));
    66113    }
    67114
    68115    protected Builder getAuthenticatedResource(WebResource resource) {
    69         return resource.header(HttpHeaders.AUTHORIZATION, "Basic "
    70                 + new String(Base64.encode(DummyPrincipal.DUMMY_PRINCIPAL.getName() + ":dummy")));
     116        return resource.header(
     117                HttpHeaders.AUTHORIZATION,
     118                "Basic "
     119                        + new String(Base64
     120                                .encode(DummyPrincipal.DUMMY_PRINCIPAL
     121                                        .getName() + ":dummy")));
    71122    }
    72    
     123
    73124    protected void createUserRecord() {
    74125        RegistryUser user = new RegistryUser();
     
    77128        userDao.insertUser(user);
    78129    }
    79    
    80     protected UserDao getUserDao() {
     130
     131    protected IUserDAO getUserDao() {
    81132        return userDao;
    82133    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/ConcurrentRestServiceTest.java

    r1861 r3449  
    1717import org.junit.Before;
    1818import org.junit.Test;
    19 import org.junit.runner.RunWith;
    2019import org.slf4j.Logger;
    2120import org.slf4j.LoggerFactory;
    2221import org.springframework.beans.factory.annotation.Autowired;
    2322import org.springframework.jdbc.core.JdbcTemplate;
    24 import org.springframework.test.context.ContextConfiguration;
    25 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    2623
    2724import static clarin.cmdi.componentregistry.rest.ComponentRegistryRestService.USERSPACE_PARAM;
    2825import static org.junit.Assert.*;
    2926
    30 @RunWith(SpringJUnit4ClassRunner.class)
    31 @ContextConfiguration(locations = {"/applicationContext.xml"})
    32 public class ConcurrentRestServiceTest extends ComponentRegistryRestServiceTestCase {
    33 
    34     private final static Logger LOG = LoggerFactory.getLogger(ConcurrentRestServiceTest.class);
     27/**
     28 *
     29 * @author george.georgovassilis@mpi.nl
     30 *
     31 */
     32public class ConcurrentRestServiceTest extends
     33        ComponentRegistryRestServiceTestCase {
     34
     35    private final static Logger LOG = LoggerFactory
     36            .getLogger(ConcurrentRestServiceTest.class);
    3537    private int NR_OF_PROFILES = 20;
    3638    private int NR_OF_COMPONENTS = 20;
     
    4446    }
    4547
    46     @Override
    47     protected String getApplicationContextFile() {
    48         return "classpath:applicationContext.xml";
    49     }
    50 
    5148    @Test
    5249    public void testConcurrentRegisterProfile() throws Exception {
    53         List<String> errors = new ArrayList();
     50        List<String> errors = new ArrayList<String>();
    5451        List<Thread> ts = new ArrayList<Thread>();
    5552
     
    7370    private void assertProfiles(int nrOfProfiles, String userSpace) {
    7471        List<ProfileDescription> response = getAuthenticatedResource(
    75                 getResource().path("/registry/profiles").queryParam(USERSPACE_PARAM, userSpace)).
    76                 accept(MediaType.APPLICATION_XML).get(
    77                 PROFILE_LIST_GENERICTYPE);
     72                getResource().path("/registry/profiles").queryParam(
     73                        USERSPACE_PARAM, userSpace)).accept(
     74                MediaType.APPLICATION_XML).get(PROFILE_LIST_GENERICTYPE);
    7875        Collections.sort(response, descriptionComparator);
    79         assertEquals("half should be deleted", nrOfProfiles / 2, response.size());
     76        assertEquals("half should be deleted", nrOfProfiles / 2,
     77                response.size());
    8078        for (int i = 0; i < nrOfProfiles / 2; i++) {
    8179            ProfileDescription desc = response.get(i);
    8280            assertEquals("Test Profile" + (i * 2 + 1000), desc.getName());
    83             assertEquals("Test Profile" + (i * 2 + 1000) + " Description", desc.getDescription());
    84         }
    85     }
     81            assertEquals("Test Profile" + (i * 2 + 1000) + " Description",
     82                    desc.getDescription());
     83        }
     84    }
     85
    8686    private Comparator<AbstractDescription> descriptionComparator = new Comparator<AbstractDescription>() {
    8787
     
    9494    private void assertComponents(int nrOfComponents, String userSpace) {
    9595        List<ComponentDescription> cResponse = getAuthenticatedResource(
    96                 getResource().path("/registry/components").queryParam(USERSPACE_PARAM, userSpace)).
    97                 accept(MediaType.APPLICATION_XML).get(
    98                 COMPONENT_LIST_GENERICTYPE);
     96                getResource().path("/registry/components").queryParam(
     97                        USERSPACE_PARAM, userSpace)).accept(
     98                MediaType.APPLICATION_XML).get(COMPONENT_LIST_GENERICTYPE);
    9999        Collections.sort(cResponse, descriptionComparator);
    100         assertEquals("half should be deleted", nrOfComponents / 2, cResponse.size());
     100        assertEquals("half should be deleted", nrOfComponents / 2,
     101                cResponse.size());
    101102        for (int i = 0; i < nrOfComponents / 2; i++) {
    102103            ComponentDescription desc = cResponse.get(i);
    103104            assertEquals("Test Component" + (i * 2 + 1000), desc.getName());
    104             assertEquals("Test Component" + (i * 2 + 1000) + " Description", desc.getDescription());
     105            assertEquals("Test Component" + (i * 2 + 1000) + " Description",
     106                    desc.getDescription());
    105107        }
    106108    }
     
    112114        }
    113115        for (Thread thread : ts) {
    114             thread.join(); //Wait till all are finished
    115         }
    116     }
    117 
    118     private void registerProfiles(List<Thread> ts, int size, final List<String> errors, String userSpace) throws InterruptedException {
     116            thread.join(); // Wait till all are finished
     117        }
     118    }
     119
     120    private void registerProfiles(List<Thread> ts, int size,
     121            final List<String> errors, String userSpace)
     122            throws InterruptedException {
    119123        for (int i = 0; i < size; i++) {
    120124            final boolean shouldDelete = (i % 2) == 1;
    121             LOG.debug("Profile {} should be registered in {} and {}", new Object[]{i + 1000, Boolean.parseBoolean(userSpace) ? "user space" : "public space", shouldDelete ? "ALSO DELETED" : "not deleted"});
    122             Thread thread = createThread("/registry/profiles/", userSpace, "Test Profile" + (i + 1000), shouldDelete, RegistryTestHelper.getTestProfileContent(), errors);
     125            LOG.debug("Profile {} should be registered in {} and {}",
     126                    new Object[] {
     127                            i + 1000,
     128                            Boolean.parseBoolean(userSpace) ? "user space"
     129                                    : "public space",
     130                            shouldDelete ? "ALSO DELETED" : "not deleted" });
     131            Thread thread = createThread("/registry/profiles/", userSpace,
     132                    "Test Profile" + (i + 1000), shouldDelete,
     133                    RegistryTestHelper.getTestProfileContent(), errors);
    123134            ts.add(thread);
    124135        }
    125136    }
    126137
    127     private void registerComponents(List<Thread> ts, int size, final List<String> errors, String userSpace) throws InterruptedException {
     138    private void registerComponents(List<Thread> ts, int size,
     139            final List<String> errors, String userSpace)
     140            throws InterruptedException {
    128141        for (int i = 0; i < size; i++) {
    129142            final boolean shouldDelete = (i % 2) == 1;
    130             LOG.debug("Component {} should be registered in {} and {}", new Object[]{i + 1000, Boolean.parseBoolean(userSpace) ? "user space" : "public space", shouldDelete ? "ALSO DELETED" : "not deleted"});
    131             Thread thread = createThread("/registry/components/", userSpace, "Test Component" + (i + 1000), shouldDelete,
     143            LOG.debug("Component {} should be registered in {} and {}",
     144                    new Object[] {
     145                            i + 1000,
     146                            Boolean.parseBoolean(userSpace) ? "user space"
     147                                    : "public space",
     148                            shouldDelete ? "ALSO DELETED" : "not deleted" });
     149            Thread thread = createThread("/registry/components/", userSpace,
     150                    "Test Component" + (i + 1000), shouldDelete,
    132151                    RegistryTestHelper.getComponentTestContent(), errors);
    133152            ts.add(thread);
     
    135154    }
    136155
    137     private Thread createThread(final String path, final String userSpace, final String name, final boolean alsoDelete,
    138             InputStream content, final List<String> errors) throws InterruptedException {
     156    private Thread createThread(final String path, final String userSpace,
     157            final String name, final boolean alsoDelete, InputStream content,
     158            final List<String> errors) throws InterruptedException {
    139159        final FormDataMultiPart form = new FormDataMultiPart();
    140         form.field(ComponentRegistryRestService.DATA_FORM_FIELD, content, MediaType.APPLICATION_OCTET_STREAM_TYPE);
    141         form.field(ComponentRegistryRestService.NAME_FORM_FIELD, name);
    142         form.field(ComponentRegistryRestService.DESCRIPTION_FORM_FIELD, name + " Description");
     160        form.field(IComponentRegistryRestService.DATA_FORM_FIELD, content,
     161                MediaType.APPLICATION_OCTET_STREAM_TYPE);
     162        form.field(IComponentRegistryRestService.NAME_FORM_FIELD, name);
     163        form.field(IComponentRegistryRestService.DESCRIPTION_FORM_FIELD, name
     164                + " Description");
    143165        Thread t = new Thread(new Runnable() {
    144166
    145167            @Override
    146168            public void run() {
    147                 //                System.out.println("THREAD STARTED"+Thread.currentThread().getName());
     169                // System.out.println("THREAD STARTED"+Thread.currentThread().getName());
    148170                RegisterResponse registerResponse = getAuthenticatedResource(
    149                         getResource().path(path).queryParam(USERSPACE_PARAM, userSpace)).
    150                         type(MediaType.MULTIPART_FORM_DATA).post(
    151                         RegisterResponse.class, form);
     171                        getResource().path(path).queryParam(USERSPACE_PARAM,
     172                                userSpace)).type(MediaType.MULTIPART_FORM_DATA)
     173                        .post(RegisterResponse.class, form);
    152174                if (!registerResponse.isRegistered()) {
    153                     errors.add("Failed to register " + Arrays.toString(registerResponse.getErrors().toArray()));
     175                    errors.add("Failed to register "
     176                            + Arrays.toString(registerResponse.getErrors()
     177                                    .toArray()));
    154178                }
    155                 LOG.debug(">>>>>>>>>>>>>>>> [Thread " + hashCode() + "] REGISTERING DESCRIPTION " + name + " " + registerResponse.getDescription().getId() + (Boolean.valueOf(userSpace) ? " userspace" : "") + (alsoDelete ? " alsoDelete" : ""));
     179                LOG.debug(">>>>>>>>>>>>>>>> [Thread " + hashCode()
     180                        + "] REGISTERING DESCRIPTION " + name + " "
     181                        + registerResponse.getDescription().getId()
     182                        + (Boolean.valueOf(userSpace) ? " userspace" : "")
     183                        + (alsoDelete ? " alsoDelete" : ""));
    156184                if (alsoDelete) {
    157                     LOG.debug(">>>>>>>>>>>>>>>> [Thread " + hashCode() + "] DELETING DESCRIPTION " + name + " " + registerResponse.getDescription().getId() + (Boolean.valueOf(userSpace) ? " userspace " : "") + (alsoDelete ? " alsoDelete" : ""));
     185                    LOG.debug(">>>>>>>>>>>>>>>> [Thread " + hashCode()
     186                            + "] DELETING DESCRIPTION " + name + " "
     187                            + registerResponse.getDescription().getId()
     188                            + (Boolean.valueOf(userSpace) ? " userspace " : "")
     189                            + (alsoDelete ? " alsoDelete" : ""));
    158190                    ClientResponse response = getAuthenticatedResource(
    159                             getResource().path(path + registerResponse.getDescription().getId()).queryParam(USERSPACE_PARAM, userSpace)).
    160                             delete(ClientResponse.class);
     191                            getResource().path(
     192                                    path
     193                                            + registerResponse.getDescription()
     194                                                    .getId()).queryParam(
     195                                    USERSPACE_PARAM, userSpace)).delete(
     196                            ClientResponse.class);
    161197                    if (response.getStatus() != 200) {
    162                         errors.add("Failed to delete " + registerResponse.getDescription());
     198                        errors.add("Failed to delete "
     199                                + registerResponse.getDescription());
    163200                    }
    164201                }
    165                 //                System.out.println("THREAD FINISHED"+Thread.currentThread().getName());
     202                // System.out.println("THREAD FINISHED"+Thread.currentThread().getName());
    166203            }
    167204        });
  • ComponentRegistry/trunk/ComponentRegistry/src/test/java/clarin/cmdi/componentregistry/rest/MDValidatorTest.java

    r3088 r3449  
    11package clarin.cmdi.componentregistry.rest;
    22
     3import clarin.cmdi.componentregistry.BaseUnitTest;
    34import clarin.cmdi.componentregistry.ComponentRegistry;
    45import clarin.cmdi.componentregistry.ComponentRegistryFactory;
     
    910import clarin.cmdi.componentregistry.model.ComponentDescription;
    1011import clarin.cmdi.componentregistry.model.ProfileDescription;
     12
    1113import java.io.ByteArrayInputStream;
    1214import java.io.InputStream;
     15
    1316import javax.xml.transform.TransformerException;
     17
    1418import org.junit.Before;
    1519import org.junit.Test;
    16 import org.junit.runner.RunWith;
    1720import org.springframework.beans.factory.annotation.Autowired;
    1821import org.springframework.jdbc.core.JdbcTemplate;
    19 import org.springframework.test.context.ContextConfiguration;
    20 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    2122
    2223import static org.junit.Assert.*;
    2324
    24 @RunWith(SpringJUnit4ClassRunner.class)
    25 @ContextConfiguration(locations = {"/applicationContext.xml"})
    26 public class MDValidatorTest {
     25/**
     26 *
     27 * @author george.georgovassilis@mpi.nl
     28 *
     29 */
     30public class MDValidatorTest extends BaseUnitTest {
    2731
    2832    @Autowired
     
    5660        profileContent += "        <AttributeList>\n";
    5761        profileContent += "             <Attribute>\n";
    58         profileContent += "                 <Name>myattribute</Name>\n"; // this should be allowed
     62        profileContent += "                 <Name>myattribute</Name>\n"; // this should be
     63                                                              // allowed
    5964        profileContent += "                 <Type>string</Type>\n";
    6065        profileContent += "             </Attribute>\n";
    6166        profileContent += "             <Attribute>\n";
    62         profileContent += "                 <Name>ref</Name>\n"; // this should NOT be allowed
     67        profileContent += "                 <Name>ref</Name>\n"; // this should NOT be
     68                                                      // allowed
    6369        profileContent += "                 <Type>string</Type>\n";
    6470        profileContent += "             </Attribute>\n";
    6571        profileContent += "             <Attribute>\n";
    66         profileContent += "                 <Name>ComponentId</Name>\n"; // neither should this
     72        profileContent += "                 <Name>ComponentId</Name>\n"; // neither should
     73                                                              // this
    6774        profileContent += "                 <Type>string</Type>\n";
    6875        profileContent += "             </Attribute>\n";
     
    7178        profileContent += "             <AttributeList>\n";
    7279        profileContent += "                 <Attribute>\n";
    73         profileContent += "                     <Name>ref</Name>\n"; // allowed here, only forbidden on components
     80        profileContent += "                     <Name>ref</Name>\n"; // allowed here, only
     81                                                   // forbidden on components
    7482        profileContent += "                     <Type>string</Type>\n";
    7583        profileContent += "                 </Attribute>\n";
    7684        profileContent += "                 <Attribute>\n";
    77         profileContent += "                     <Name>ComponentId</Name>\n"; // allowed here, only forbidden on components
     85        profileContent += "                     <Name>ComponentId</Name>\n"; // allowed here, only
     86                                                           // forbidden on
     87                                                           // components
    7888        profileContent += "                     <Type>string</Type>\n";
    7989        profileContent += "                 </Attribute>\n";
     
    8898
    8999        ProfileDescription desc = ProfileDescription.createNewDescription();
    90         MDValidator validator = new MDValidator(input, desc, publicRegistry, null, publicRegistry, marshaller);
     100        MDValidator validator = new MDValidator(input, desc, publicRegistry,
     101                null, publicRegistry, marshaller);
    91102        assertFalse(validator.validate());
    92103        assertEquals(4, validator.getErrorMessages().size());
    93         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.PARSE_ERROR));
    94         assertTrue(validator.getErrorMessages().get(1).startsWith(MDValidator.PARSE_ERROR));
     104        assertTrue(validator.getErrorMessages().get(0)
     105                .startsWith(MDValidator.PARSE_ERROR));
     106        assertTrue(validator.getErrorMessages().get(1)
     107                .startsWith(MDValidator.PARSE_ERROR));
    95108    }
    96109
     
    107120
    108121        ProfileDescription desc = ProfileDescription.createNewDescription();
    109         MDValidator validator = new MDValidator(input, desc, publicRegistry, null, publicRegistry, marshaller);
    110         assertFalse(validator.validate());
    111         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     122        MDValidator validator = new MDValidator(input, desc, publicRegistry,
     123                null, publicRegistry, marshaller);
     124        assertFalse(validator.validate());
     125        assertTrue(validator
     126                .getErrorMessages()
     127                .get(0)
     128                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    112129    }
    113130
     
    123140        profileContent += "    <Header />";
    124141        profileContent += "    <CMD_Component name=\"Test\">";
    125         profileContent += "     <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + id1 + "\"/>"; //id not registered
    126         profileContent += "     <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + id2 + "\"/>"; //id not registered
     142        profileContent += "     <CMD_Component ComponentId=\""
     143                + ComponentRegistry.REGISTRY_ID + id1 + "\"/>"; // id not
     144                                                                // registered
     145        profileContent += "     <CMD_Component ComponentId=\""
     146                + ComponentRegistry.REGISTRY_ID + id2 + "\"/>"; // id not
     147                                                                // registered
    127148        profileContent += "    </CMD_Component>";
    128149        profileContent += "</CMD_ComponentSpec>";
     
    130151        // Ids not registered will return two errors. One for each id
    131152        ProfileDescription desc = ProfileDescription.createNewDescription();
    132         MDValidator validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
     153        MDValidator validator = new MDValidator(new ByteArrayInputStream(
     154                profileContent.getBytes()), desc, publicRegistry, null,
     155                publicRegistry, marshaller);
    133156        assertFalse(validator.validate());
    134157        assertEquals(2, validator.getErrorMessages().size());
    135         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    136         assertTrue(validator.getErrorMessages().get(1).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     158        assertTrue(validator
     159                .getErrorMessages()
     160                .get(0)
     161                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     162        assertTrue(validator
     163                .getErrorMessages()
     164                .get(1)
     165                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    137166
    138167        // id1 will be added and therefore only id2 is not registered
    139168        RegistryTestHelper.addComponent(publicRegistry, id1);
    140         validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
     169        validator = new MDValidator(new ByteArrayInputStream(
     170                profileContent.getBytes()), desc, publicRegistry, null,
     171                publicRegistry, marshaller);
    141172        assertFalse(validator.validate());
    142173        assertEquals(1, validator.getErrorMessages().size());
    143         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     174        assertTrue(validator
     175                .getErrorMessages()
     176                .get(0)
     177                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    144178
    145179        // id2 is added, no more errors shoud be return
    146180        RegistryTestHelper.addComponent(publicRegistry, id2);
    147         validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
    148         assertTrue("component is registered should be valid now", validator.validate());
     181        validator = new MDValidator(new ByteArrayInputStream(
     182                profileContent.getBytes()), desc, publicRegistry, null,
     183                publicRegistry, marshaller);
     184        assertTrue("component is registered should be valid now",
     185                validator.validate());
    149186        assertEquals(0, validator.getErrorMessages().size());
    150187    }
     
    154191        String id1 = "component1";
    155192        String id2 = "component2";
    156         ComponentRegistry userRegistry = componentRegistryFactory.getComponentRegistry(ComponentStatus.PRIVATE, null, DummyPrincipal.DUMMY_CREDENTIALS);
     193        ComponentRegistry userRegistry = componentRegistryFactory
     194                .getComponentRegistry(ComponentStatus.PRIVATE, null,
     195                        DummyPrincipal.DUMMY_CREDENTIALS);
    157196
    158197        String profileContent = "";
     
    162201        profileContent += "    <Header />";
    163202        profileContent += "    <CMD_Component name=\"Test\">";
    164         profileContent += "     <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + id1 + "\"/>"; //id not registered
    165         profileContent += "     <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + id2 + "\"/>"; //id not registered
     203        profileContent += "     <CMD_Component ComponentId=\""
     204                + ComponentRegistry.REGISTRY_ID + id1 + "\"/>"; // id not
     205                                                                // registered
     206        profileContent += "     <CMD_Component ComponentId=\""
     207                + ComponentRegistry.REGISTRY_ID + id2 + "\"/>"; // id not
     208                                                                // registered
    166209        profileContent += "    </CMD_Component>";
    167210        profileContent += "</CMD_ComponentSpec>";
    168211
    169212        ProfileDescription desc = ProfileDescription.createNewDescription();
    170         MDValidator validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, userRegistry, userRegistry, publicRegistry, marshaller);
     213        MDValidator validator = new MDValidator(new ByteArrayInputStream(
     214                profileContent.getBytes()), desc, userRegistry, userRegistry,
     215                publicRegistry, marshaller);
    171216        assertFalse(validator.validate());
    172217        assertEquals(2, validator.getErrorMessages().size());
    173         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
    174         assertTrue(validator.getErrorMessages().get(1).startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     218        assertTrue(validator.getErrorMessages().get(0)
     219                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
     220        assertTrue(validator.getErrorMessages().get(1)
     221                .startsWith(MDValidator.COMPONENT_NOT_REGISTERED_ERROR));
    175222
    176223        RegistryTestHelper.addComponent(userRegistry, id1);
    177224        RegistryTestHelper.addComponent(publicRegistry, id2);
    178         validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
     225        validator = new MDValidator(new ByteArrayInputStream(
     226                profileContent.getBytes()), desc, publicRegistry, null,
     227                publicRegistry, marshaller);
    179228        assertFalse(validator.validate());
    180229        assertEquals(1, validator.getErrorMessages().size());
    181         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    182 
    183         validator = new MDValidator(new ByteArrayInputStream(profileContent.getBytes()), desc, userRegistry, userRegistry, publicRegistry, marshaller);
     230        assertTrue(validator
     231                .getErrorMessages()
     232                .get(0)
     233                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     234
     235        validator = new MDValidator(new ByteArrayInputStream(
     236                profileContent.getBytes()), desc, userRegistry, userRegistry,
     237                publicRegistry, marshaller);
    184238        assertTrue(validator.validate());
    185239        assertEquals(0, validator.getErrorMessages().size());
     
    197251        content += "    <CMD_Component name=\"Actor\" CardinalityMin=\"0\" CardinalityMax=\"unbounded\">\n";
    198252        content += "        <CMD_Element name=\"Name\" ValueScheme=\"string\" />\n";
    199         content += "      <CMD_Component ComponentId=\"" + ComponentRegistry.REGISTRY_ID + id1 + "\"/>\n"; //id not registered
     253        content += "      <CMD_Component ComponentId=\""
     254                + ComponentRegistry.REGISTRY_ID + id1 + "\"/>\n"; // id not
     255                                                                  // registered
    200256        content += "    </CMD_Component>\n";
    201257        content += "</CMD_ComponentSpec>\n";
    202258
    203259        ComponentDescription desc = ComponentDescription.createNewDescription();
    204         MDValidator validator = new MDValidator(new ByteArrayInputStream(content.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
     260        MDValidator validator = new MDValidator(new ByteArrayInputStream(
     261                content.getBytes()), desc, publicRegistry, null,
     262                publicRegistry, marshaller);
    205263        assertFalse(validator.validate());
    206264        assertEquals(1, validator.getErrorMessages().size());
    207         assertTrue(validator.getErrorMessages().get(0).startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
     265        assertTrue(validator
     266                .getErrorMessages()
     267                .get(0)
     268                .startsWith(MDValidator.COMPONENT_NOT_PUBLICLY_REGISTERED_ERROR));
    208269
    209270        RegistryTestHelper.addComponent(publicRegistry, id1);
    210         validator = new MDValidator(new ByteArrayInputStream(content.getBytes()), desc, publicRegistry, null, publicRegistry, marshaller);
     271        validator = new MDValidator(
     272                new ByteArrayInputStream(content.getBytes()), desc,
     273                publicRegistry, null, publicRegistry, marshaller);
    211274        assertTrue(validator.validate());
    212275        assertEquals(0, validator.getErrorMessages().size());
     
    222285
    223286        ProfileDescription desc = ProfileDescription.createNewDescription();
    224         MDValidator validator = new MDValidator(input, desc, publicRegistry, null, publicRegistry, marshaller);
     287        MDValidator validator = new MDValidator(input, desc, publicRegistry,
     288                null, publicRegistry, marshaller);
    225289
    226290        // Spec is created during validation, before it should be null
     
    229293
    230294        // Get spec created during validation
    231         final CMDComponentSpec cmdComponentSpec = validator.getCMDComponentSpec();
     295        final CMDComponentSpec cmdComponentSpec = validator
     296                .getCMDComponentSpec();
    232297        assertNotNull(cmdComponentSpec);
    233298
    234299        // Spec content should match XML
    235300        assertTrue(cmdComponentSpec.isIsProfile());
    236         assertEquals("Actor", cmdComponentSpec.getCMDComponent().get(0).getName());
     301        assertEquals("Actor", cmdComponentSpec.getCMDComponent().get(0)
     302                .getName());
    237303
    238304        // Spec copy should be a freshly unmarshalled copy
     
    249315        InputStream input = new ByteArrayInputStream(profileContent.getBytes());
    250316        ProfileDescription desc = ProfileDescription.createNewDescription();
    251         MDValidator validator = new MDValidator(input, desc, publicRegistry, null, publicRegistry, marshaller);
     317        MDValidator validator = new MDValidator(input, desc, publicRegistry,
     318                null, publicRegistry, marshaller);
    252319        return validator;
    253320    }
  • ComponentRegistry/trunk/ComponentRegistry/src/test/resources/spring-config/datasource-hsqldb.xml

    r1944 r3449  
    11<?xml version="1.0" encoding="UTF-8"?>
    22<beans xmlns="http://www.springframework.org/schema/beans"
    3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4        xsi:schemaLocation="http://www.springframework.org/schema/beans classpath:/org/springframework/beans/factory/xml/spring-beans-2.5.xsd">
    5     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    6         <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    7         <property name="url" value="jdbc:hsqldb:mem:component_registry;sql.syntax_pgs=true"/>
    8         <property name="username" value="sa"/>
    9         <property name="password" value=""/>
    10     </bean>
     3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4        xmlns:aop="http://www.springframework.org/schema/aop"
     5        xmlns:context="http://www.springframework.org/schema/context"
     6        xmlns:jdbc="http://www.springframework.org/schema/jdbc"
     7        xsi:schemaLocation="
     8     http://www.springframework.org/schema/beans
     9     http://www.springframework.org/schema/beans/spring-beans.xsd
     10     http://www.springframework.org/schema/aop
     11     http://www.springframework.org/schema/aop/spring-aop.xsd
     12     http://www.springframework.org/schema/context
     13     http://www.springframework.org/schema/context/spring-context.xsd
     14     http://www.springframework.org/schema/jdbc
     15     http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
     16     ">
    1117
    12     <bean id="jdbcTemplate"
    13         class="org.springframework.jdbc.core.JdbcTemplate">
    14         <property name="dataSource" ref="dataSource"/>
    15     </bean>
     18<!-- Without the transaction proxy, JdbcTemplate will close the active connection after each statement -->
     19        <bean id="dataSource"
     20                class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
     21                <property name="targetDataSource">
     22                        <bean class="org.apache.commons.dbcp.BasicDataSource">
     23                                <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
     24                                <property name="url"
     25                                        value="jdbc:hsqldb:mem:component_registry;sql.syntax_pgs=true" />
     26                                <property name="username" value="sa" />
     27                                <property name="password" value="" />
     28                                <property name="defaultAutoCommit" value="true"/>
     29                        </bean>
     30                </property>
     31        </bean>
     32
    1633</beans>
Note: See TracChangeset for help on using the changeset viewer.